我收到错误:
AttributeError: 'User' object has no attribute 'zipcode'
当用户填写表单以销售商品时,我收到此错误。
以下是我的观点:
def get_entry(request):
if request.method == 'POST':
f = SellForm(request.POST)
if f.is_valid():
form=f.save(commit=False)
form.author = request.user
form.zipcode = request.user.zipcode
form.pubdate = datetime.datetime.now
form.save()
else:
f = SellForm()
return render(request, 'sell.html', {'form': f})
以下是我的模特:
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
from django.conf import settings
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='my_profile')
city = models.TextField(null=True, blank=True)
state = models.TextField(null=True, blank=True)
zipcode = models.IntegerField(_('zipcode'),
max_length=5, null=True, blank=True)
coverpic = models.ImageField(upload_to="/site_media/media/covers/", null=True, blank=True)
class Entry(models.Model):
headline= models.CharField(max_length=200,)
body_text = models.TextField()
author=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='entryauthors')
pub_date=models.IntegerField(max_length=8)
zipcode =models.ForeignKey(settings.AUTH_USER_MODEL, related_name='entryzipcodes')
price1 = models.TextField()
price2 = models.TextField()
item_picture = models.ImageField(upload_to="/site_media/media/items/", null=True, blank=True)
这是我的表格:
class SellForm(ModelForm):
class Meta:
model = Entry
fields = ['headline', 'body_text', 'author', 'pub_date', 'zipcode', 'price1', 'price2', 'item_picture']
我是否对模型做错了什么?
答案 0 :(得分:1)
如您所知,甚至在评论中重申,zipcode是MyProfile的属性,而不是User的属性。那么为什么要尝试在用户上访问它?您需要遵循与个人资料的关系:
form.zipcode = request.user.my_profile.zipcode
(请注意,“form”是变量的一个非常糟糕的名称:你拥有的是一个Entry的实例,所以也许你应该相应地命名它。)