0

I have no idea and I need to ask your advice.

I have simple form:

class CommentForm(ModelForm): class Meta: model = Comment fields = ['text','author','news'] 

I want to add form in DetailView and hadle this 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 to show 'author' and news fieds. But if I hide them I can't to get initial values..

UPDATED:

After form validation I need return current form instance in the template through updating page. I attempted the next:

 comment_form = CommentForm(request.POST, request=request) if comment_form.is_valid() and 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.

9
  • How are you hiding them? Commented Jul 14, 2015 at 12:06
  • I tried not show them. Just used {{ form.text }} in the template. Commented Jul 14, 2015 at 12:13
  • You can show them in your template if you have a HiddenInput Commented Jul 14, 2015 at 12:17
  • Should I necessarly show 'author' and 'news' fields even I did them HiddenInput? I thoght exists other way. Commented Jul 14, 2015 at 12:21
  • If you don't render them the form will only submit the input from the text field, and that will end as an invalid form since you are defining fields = ['text','author','news'] in the Meta class of your form. Commented Jul 14, 2015 at 12:27

1 Answer 1

1

If you don't render your fields using {{ form.author }} and {{ form.news }} the form won't validate. Try using a HiddenInput for each field, You can do that by overriding the __init__ method of your 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'] 
Sign up to request clarification or add additional context in comments.

Comments