我有一个功能可以让您创建消息并发送它。我有一个名为 person 的用户模型,它有一个名为 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})