Вопрос

I'm trying to use get_initial within a FormView to pre-populate the field "Subject" to have a "Wholesaler is interested" text, but it's not working. If it matters, I'm using Django 1.5, Python 2.7. Here is my code. Am I missing a step?

class ContactView(FormView):
    """
    ContactForm is a ModelForm
    """
    template_name = 'core/contact-us.html'
    form_class = ContactForm
    success_url = reverse_lazy('products:index')
    initial = {'subject': 'I am interested in making a wholesale purchase'}


    def get_initial(self):
        """
        Returns the initial data to use for forms on this view.
        """
        return self.initial

    def get_form_kwargs(self):
        kwargs = {'initial': self.get_initial()}
        return kwargs

    def form_valid(self, form):
        cd = form.cleaned_data
        contact = Contact.objects.create(**form.cleaned_data)
        if contact:
            print 'contact created'
        else:
            print 'not created'
        if contact is not None:
            # send contact email
            msg = contact_email(name=cd['name'], email=cd['email'], subject=cd['subject'], message=cd['message'])
            msg.send()
            # Add success message 
            msg = 'Your contact email has been successfully sent.  We look forward to speaking with you.'
            messages.info(self.request, msg)
        return super(ContactView, self).form_valid(form)

EDIT

I removed the get_initial and get_form_kwargs but still no luck. Here is a paste of my Form if that helps. Do I need to attach the initial for what I would like to put in the Form in some way? Thanks for your help!

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact  
        fields = ('name', 'email', 'subject', 'message',)
        widgets = {
            'message': forms.Textarea(attrs={'cols': 20, 'rows': 20}),
        }
Это было полезно?

Решение

Instead of using FormView, try CreateView. It's a subclass of FormView which takes care of your actual model.

Also, how do you display the form in the template? If you manually go through all the fields you might be not displaying the initial value.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top