Instantiating a ModelForm with initial values in CBVs

25 views
Skip to first unread message

Frankline

unread,
Jun 14, 2014, 1:24:54 PM6/14/14
to django...@googlegroups.com
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.

Simone Dalla

unread,
Jun 14, 2014, 2:28:16 PM6/14/14
to Michele Magazz
Hi,

you need overriding of get_initial [1] method into your MessageCreateView

[1] https://docs.djangoproject.com/en/1.6/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_initial

Simone

--
Simo

- Registered Linux User #395060

- Software is like sex, it is better when it is free --> Linus B. Torvalds
Reply all
Reply to author
Forward
0 new messages