Reputation: 96
I'm writing a contact application for django, where users can contact another one responding to a specific post. Here is my message model:
class Message(models.Model):
person_src = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
person_dst = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
replyTo = models.ForeignKey("self", on_delete=models.CASCADE) # reply to another message
post = models.ForeignKey(Post, on_delete=models.CASCADE) # posts concerned by the message
date = models.DateTimeField()
content = models.CharField(max_length=1000)
This is my django form for message
class NewMessageForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Message
fields = ['content']
And the associated view:
class NewMessageFormView(View):
form_class = NewMessageForm
template_name = 'messaging/new_message.html'
#get just displays an empty form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
message = form.save(commit=False)
message.content = request.content
message.date = datetime.date.today()
message.save()
if message is not None:
return redirect('messages:detail', message.id)
return render(request, self.template_name, {'form': form})
I want to be able to send in addition to the form, the associated post which the user is responding to, and all previous messages associated with the current one (in case the user is answering). Is it possible to render additional information in the view ?
Upvotes: 0
Views: 234
Reputation: 11891
Add it into the context (the dictionary where the form is):
return render(request, self.template_name, {'form': form, 'additional_item_1': additional_item_1_value})
Access it in the template using the key you used:
{{ additional_item_1 }}
Upvotes: 1