- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试为用户创建一个小应用程序以获取联系人。我使用 django-profiles 作为我的个人资料的基础。现在一切正常,直到我尝试提交编辑联系表单并收到此错误。
Cannot assign "<Contact: Contact object>": "Contact.user" must be a "UserProfile" instance.
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)
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)
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))
最佳答案
基本上,django-profiles 用于其他用途 - 它只是帮助创建和管理跨应用程序的用户配置文件。
首先 - 您应该通过 ForeignKey 将 Contact
模型 直接 链接到 django.contrib.auth.models.User
。这样你就可以通过一个简单的查询来访问给定用户的联系人。 User.contact_set.all()
- 它将返回给您一个用户联系人列表。这也将摆脱你的错误。first_name
、 last_name
等第二个字段已经在 django.contrib.auth.models.User
中定义,所以不需要在 UserProfile
中再次定义它们。阅读 User 模型 here 的源码
第三 - 如果您的用户只能拥有一个 Profile 并且您不打算使用非常旧版本的 django,那么您应该使用 OneToOneField
而不是 ForeignKey
。
第四件事 - 您可能可以通过使用与 django 捆绑的通用 View 之一来省略 RequestContext()
的使用 - 阅读有关 here 的信息
最后一件事 - 请记住,处理用户的主要模型是 User
模型本身。任何自定义配置文件只是一个扩展,因此将与用户相关的所有内容链接到用户模型本身。
快乐编码!
关于Django - 将我的模型链接到配置文件(UserProfile)模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249661/
我正在开发一个 voip 调用应用程序。我需要做的是在接到来电时将 Activity 带到前台。我在应用程序中使用 Twilio,并在收到推送消息时开始调用。 问题是我试图在接到任何电话时显示 Act
我是一名优秀的程序员,十分优秀!