I am a Django newbie working with Django CBVs and having difficulty setting initial values for my ModelForm. To give an overview, I am trying to learn by creating a simple messaging app.
Here is my code: models.py --------------------------------------------------------- import datetime from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone class Message(models.Model): subject = models.CharField(_("Subject"), max_length=100) body = models.TextField(_("Body")) sender = models.ForeignKey(User, db_index=True, related_name='sent_messages') recipient = models.ForeignKey(User, db_index=True, related_name='received_messages') parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True) forms.py --------------------------------------------------- from django.forms import ModelForm from .models import Message class MessageForm(ModelForm): class Meta: model = Message exclude = ('sender', 'recipient', 'parent_msg',) views.py -------------------------------------------------- class MessageCreateView(CreateView): form_class = MessageForm model = Message template_name = 'messages/compose.html' def form_valid(self, form): form.instance.sender = self.request.user return super(MessageCreateView, self).form_valid(form) urls.py --------------------------------------------------------------------------- ... url(r'^compose/(?P<recipient>[\w.@+-]+)/$', MessageCreateView.as_view(), name='messages_compose_to'), ... As you can see from the urls.py file, I am using the 'recipient' parameter as such: http://localhost:8000/members/compose/someusername Now my problem is that I wish to open the compose message view, and initialize the recipient field by getting the username from the URL, then using the username from the url to get User with that particular username, and instantiate the form with it. Where do I do this, in the view itself or in the form? Unless their is a better way of how to handle this. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEAUGdUGugEimEjjV%3DN-ue1403m3XBF67FEwijKUzQVSJ31T_g%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.