django - How to define initial values for ModelForm rightly? -


i have no idea , need ask advice.

i have simple form:

class commentform(modelform):     class meta:         model = comment         fields = ['text','author','news'] 

i want add form in detailview , hadle form there:

class newsdetailview(detailview):     model = news     template_name = 'news/detail.html'      def get_initial(self):         return {'news': self.get_object(), 'author': self.request.user}      def get_context_data(self, **kwargs):         context = super(newsdetailview, self).get_context_data(**kwargs)         context['form'] = commentform(initial=self.get_initial())         return context      def post(self, request, *args, **kwargs):         '''         comment_form = commentform(request.post)         if comment_form.is_valid():             comment_form.save() 

i don't want show 'author' , news fieds. if hide them can't initial values..

updated:

after form validation need return current form instance in template through updating page. attempted next:

        comment_form = commentform(request.post, request=request)         if comment_form.is_valid() , comment_form.validate_user():             comment_form.save()             return httpresponseredirect(request.meta.get('http_referer'))         else:             context = super(newsdetailview,self).get_context_data(**kwargs)             context['form'] = comment_form             return self.render_to_response(context) 

but did not work.

if don't render fields using {{ form.author }} , {{ form.news }} form won't validate. try using hiddeninput each field, can overriding __init__ method of form:

class commentform(modelform):     def __init__(self, *args, **kwargs):         super(commentform, self).__init__(*args, **kwargs)         self.fields['author'].widget = forms.hiddeninput()         self.fields['news'].widget = forms.hiddeninput()      class meta:         model = comment         fields = ['text','author','news'] 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -