我想在我登录的当前用户下保存添加,但我不断收到主题中列出的错误。
我的模特:
class CustomUser(User):
nickname = models.CharField(max_length=255)
phone = models.CharField(max_length=255)
address = models.CharField(max_length=255)
objects = UserManager()
city = models.ForeignKey(locations, unique=False)
def __str__(self):
return self.nickname
class Admin:
pass
class listings(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey('category')
description = models.CharField(max_length=255)
published = models.DateField(auto_now=True)
user = models.ForeignKey(CustomUser, unique=False)
def __str__(self):
return self.naslov
class Admin:
pass
表格:
class jobOfferForm(forms.ModelForm):
title = forms.CharField(max_length=255)
description = forms.CharField(max_length=255)
category = forms.ModelChoiceField(queryset=kategorii.objects.all())
class Meta:
model = listings
模板:
<div class="span8">
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="Save"/>
</form>
</div>
观点!
def displisting(request):
if request.method == 'POST':
form = jobOfferForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
new_listng = form.save(commit = False)
new_listng.user = request.user
new_listng.object.save()
return HttpResponseRedirect('/listing/review')
else:
form = jobOfferForm()
return render(request,'listings.html',{'form':form,})
我担心自定义用户阻止我这样做? 但我需要额外的属性?
答案 0 :(得分:3)
如果您的用户未登录,则会发生此错误。
使用bundled / admin站点登录,您的request.user对象将是一个有效的用户实例
答案 1 :(得分:2)
request.User
不是自定义CustomerUser
的实例,而是django.contrib.auth.models.User
。因此,任务:
new_listng.user = request.user
无效。
您可能希望将您的request.User向下转发到CustomerUser
(或其他子类,如果有的话)。您可以添加一个自定义中间件,模拟django.contrib.auth.middleware.AuthenticationMiddleware
来实现此目的。
django-model-util's InheritanceManager
有一些有用的助手,例如select_subclasses
,可以轻松实现这一目标。