ユーザーが互いにメッセージを送信できるアプリケーションがあります。
私が取り組んでいる現在の関数は、メッセージ ID を取得し、メッセージ オブジェクトをフォームに入力します。下書きメッセージのようなもので、ユーザーはメッセージフォームを編集して送信できます。
person という User モデルがあり、 inbox という属性があります。この属性は、ユーザーが自分の受信トレイを有効にするか無効にするかを決定します
問題は、私が困っていることです。ユーザーが受信ボックスを非アクティブ化しても、draftform というフォームでエラーが発生しませんでした。ただし、フィールドが欠落している場合やユーザーが存在しない場合はエラーが発生します
request.user をフォームおよび views.py に渡す方法に関連して、それらが問題であると想定しています。誰か助けてください
ビュー.py
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')
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)
ビュー
@login_required
def ReadDraft(request,id):
try:
messages = Message.objects.get(pk=id,recipient=request.user)
except Message.DoesNotExist:
return HttpResponseRedirect(reverse('world:Display'))
thread = Thread.objects.get(message=messages)
initial = {}
initial.update({'hidden_field': messages.id})
draft = DraftForm(request,instance=messages,initial=initial)
thread = ThreadForm(instance=thread)
person = Person.objects.get(user=request.user)
if request.method =='POST':
id = request.POST.get('hidden_field', False)
form = ThreadForm(request.POST)
forms = DraftForm(request,request.POST)
if form.is_valid() and forms.is_valid():
m = Message.objects.get(pk=id,)
recipient = forms.cleaned_data['recipient']
subject = form.cleaned_data['subject']
body = forms.cleaned_data['body']
person = Person.objects.get(user=request.user)
m.user =request.user
m.recipient = recipient
m.body = body
m.draft = False
m.sentmessage = True
m.save()
return HttpResponseRedirect(reverse('world:message'))
else:
ctx = {'DraftForm': forms, 'ThreadForm': form,'person':person}
return render(request, 'create.html', ctx)
return render(request,'create.html',{'DraftForm':draft,'ThreadForm':thread,'person':person})
フォーム.py
class DraftForm(forms.ModelForm):
recipient = forms.CharField(required=True,max_length=51)
body = forms.CharField(widget=forms.Textarea,required=True,max_length=51)
hidden_field = forms.CharField(widget=forms.HiddenInput())
def __init__(self, request, *args, **kwargs):
self.request = request
super(DraftForm, self).__init__(*args, **kwargs)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
person = Person.objects.get(user=self.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
class Meta:
model = Message
fields = ('body',)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
try:
recipient = User.objects.get(username=recipient)
except User.DoesNotExist:
raise forms.ValidationError("This username does not exist")
return recipient
class ThreadForm(forms.ModelForm):
class Meta:
model = Thread
fields = ('subject',)
create.html
{% if DraftForm and ThreadForm %}
<form method="POST" >{% csrf_token %}
{{DraftForm.recipient}}
{{ThreadForm.subject}}
{{DraftForm.body}}
{{DraftForm.hidden_field}}
<input type = "submit" value= "send" class="save" id="send" />
</form>
{% endif %}
{{ThreadForm.subject.errors}}
{{DraftForm.recipient.errors}}
{{DraftForm.body.errors}}