我有一个允许您创建消息并发送它的功能。我有一个名为person的Usermodel,它有一个名为inbox的属性。此属性确定用户是否要启用其收件箱。
我有一个名为NewMessageForm的表单。我试图通过表单提出错误,如果经过身份验证的用户已将其收件箱停用,但为了这样做,我必须通过表单获取request.user,这不允许我这样做但仅在视图中。
有人可以帮助我。
global name 'request' is not defined
File "C:\mysite\pet\forms.py" in clean_recipient
329. user = User.objects.get(user=request.user)
Exception Type: NameError at /create/
Exception Value: global name 'request' is not defined
模型
class Person(models.Model):
inbox = (
('A', 'Activate'),
('D', 'Deactivate'),
('F', 'Permit To Friends Only'),
)
user = models.ForeignKey(User)
inbox = models.CharField(max_length=1, choices=inbox ,default='A')
def __unicode__(self):
return self.user.username
class Thread(models.Model):
subject = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(User)
class Message(models.Model):
user = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
created = models.DateTimeField(auto_now_add=True)
body = models.CharField(max_length=1000)
read = models.BooleanField(default=False)
sentmessage = models.BooleanField(default=False)
thread = models.ForeignKey(Thread)
draft = models.BooleanField(default=False)
def __unicode__(self):
return self.body
形式
class NewMessageForm(forms.ModelForm):
recipient = forms.CharField(required=False,max_length=15)
message = forms.CharField(widget=forms.Textarea,required=True,max_length=15)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
user = User.objects.get(user=request.user)
if person.inbox == D:
raise forms.ValidationError("You have deactivated your inbox , Please enable it at profile settings")
if recipient:
try:
recipient = User.objects.get(username=recipient)
except User.DoesNotExist:
raise forms.ValidationError("This username does not exist")
return recipient
else:
return recipient
视图
@login_required
def Create(request):
person = Person.objects.get(user=request.user)
form = NewMessageForm()
if request.POST.get('_send', False):
form = NewMessageForm(request.POST)
if form.is_valid():
recipient = form.cleaned_data['recipient']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
if recipient:
thread = Thread.objects.create(subject=subject,user=request.user)
recipient = User.objects.get(username=recipient)
message = Message.objects.create(user=request.user,recipient=recipient,body=message,thread=thread,sentmessage=True,read=False)
return HttpResponseRedirect(reverse('world:message'))
return render(request,'create.html',{'messages':messages,'form':form,'person':person})
答案 0 :(得分:1)
您可以覆盖表单的__init__
以要求参数:
class NewMessageForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(NewMessageForm, self).__init__(*args, **kwargs)
并在您的视图中实例化您的表单:
form = NewMessageForm(request)
和
form = NewMessageForm(request, request.POST)
现在您的self.request
个实例中有NewMessageForm
,可以使用self.request.user
。