Django - 将我的模型链接到配置文件(UserProfile)模型

tkh*_*h44 3 django django-models django-views

我正在尝试为用户创建一个小应用程序来建立联系人.我使用django-profiles作为我的个人资料的基础.现在一切正常,直到我尝试提交编辑联系表单,我收到此错误.

Cannot assign "<Contact: Contact object>": "Contact.user" must be a "UserProfile" instance.
Run Code Online (Sandbox Code Playgroud)

作为Django的新手,我甚至不确定我是否采取了正确的方法.我的最终目标是让用户能够添加尽可能多的联系人.任何建议表示赞赏.

扩展用户的我的UserProfile模型如下所示:

class UserProfile(models.Model):
#User's Info
user = models.ForeignKey(User, unique=True)
first_name = models.CharField("first name", max_length=30)
last_name = models.CharField("last name", max_length=30)
home_address = models.CharField(max_length=50)
primary_phone = PhoneNumberField()
city = models.CharField(max_length=50)
state = USStateField()
zipcode = models.CharField(max_length=5)
birth_date = models.DateField()
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
Run Code Online (Sandbox Code Playgroud)

我的联系人模型如下:

class Contact(models.Model):    
user = models.ForeignKey(UserProfile)

contact_description = models.CharField("Relation or Description of Contact", max_length=50, blank=True)
contact_first_name = models.CharField("contact first name", max_length=30)
contact_last_name = models.CharField("contact last name", max_length=30)
contact_primary_phone = PhoneNumberField("contact primary phone number")
contact_secondary_phone = PhoneNumberField("contact secondary phone number",blank=True)
Run Code Online (Sandbox Code Playgroud)

和我的观点:

def editContact(request, username, object_id=False, template_name='contacts/edit.html'):

user = UserProfile.user

AddContactFormset = inlineformset_factory(UserProfile,Contact, extra=1)
if object_id:
    contact=Contact.objects.get(pk=object_id)
else:
    contact=Contact()
if request.method == 'POST':
    f= ContactForm(request.POST, request.FILES, instance=contact)
    fs = AddContactFormset(request.POST, instance=contact)
    if fs.is_valid() and f.is_valid():
        f.save()
        fs.save()
        return HttpResponse('success')
else:
    f = ContactForm(instance=contact)
    fs = AddContactFormset(instance=contact)

return render_to_response(template_name ,{'fs':fs,'f':f,'contact': contact}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

bx2*_*bx2 9

基本上django-profiles用于其他方面 - 它只是帮助在应用程序中创建和管理用户配置文件.

首先 - 您应该将Contact模型直接链接到django.contrib.auth.models.UserviaKeyKey.这样,您可以通过简单的查询访问给定用户的联系人,即.User.contact_set.all() - 它将返回用户联系人列表.这也将摆脱你的错误.

第二个 - 像文件一样first_name,last_name已经定义了django.contrib.auth.models.User,所以不需要再次定义它们UserProfile.在此处阅读用户模型的来源:http://goo.gl/8oDv3

第三 - 如果您的用户只能拥有一个配置文件并且您不打算使用非常旧版本的django,那么您应该使用OneToOneField而不是ForeignKey.

第四件事 - 您可以RequestContext()通过使用与django捆绑在一起的通用视图来省略其使用- 请在此处阅读:http://goo.gl/U4DWs

最后一点 - 请记住,处理用户的主要模型是User模型本身.任何自定义配置文件只是一个扩展,因此将与用户相关的所有内容链接到用户模型本身.

快乐的编码!