Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to subclass django's generic CreateView with initial data?
    text
    copied!<p>I'm trying to create a dialog which uses jquery's .load() function to slurp in a rendered django form. The .load function is passed the pk of the "alert" object. Also available in the class functions are things like <code>self.request.user</code> so I can pre-fill those fields, shown below in the Message model (models.py):</p> <pre class="lang-python prettyprint-override"><code>class Message(models.Model): user = models.ForeignKey(User) alert = models.ForeignKey(Alert) date = models.DateTimeField() message = models.TextField() </code></pre> <p>Subclassing django's CreateView makes it pretty easy to generate a context with an instance of the ModelForm (views.py):</p> <pre class="lang-python prettyprint-override"><code>class MessageDialogView(CreateView): """ show html form fragment """ model = Message template_name = "message.html" def get_initial(self): super(MessageDialogView, self).get_initial() alert = Alert.objects.get(pk=self.request.POST.get("alert_id")) user = self.request.user self.initial = {"alert":alert.id, "user":user.id, "message":"test"} return self.initial def post(self, request, *args, **kwargs): super(MessageDialogView, self).post(request, *args, **kwargs) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(form=form) return self.render_to_response(context) </code></pre> <p>The problem here is that <code>self.initial</code> does not get rendered with the form. I have insured that the form is indeed calling <code>get_initial</code> and the form instance has the proper initial data in <code>post</code>, but when the form is rendered in the template <code>message.html</code> it doesn't grab any of the initial data like I would expect. Is there a special trick to get this to work? I've scoured the docs (seems to be lacking examples on generic based class views) and source but I can't see what I'm missing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload