Home > Net >  Add a contact form to an existing contact page view using class based views in Django
Add a contact form to an existing contact page view using class based views in Django

Time:10-24

I'm trying to add a "contact us" form to my existing "contact us" page using a model form and class based views. First I've created the model below:

class ContactUsForm(models.Model):
    first_name = models.CharField(max_length=200, blank=False, null=False)
    last_name = models.CharField(max_length=200, blank=False, null=False)
    email = models.EmailField(blank=False, null=False)
    subject = models.CharField(max_length=250, blank=False, null=False)
    message_body = models.TextField()

    def __str__(self):
        return self.subject

Then I've created my form in forms.py as below:

class ContactForm(ModelForm):
    class Meta:
        model = ContactUsForm
        fields = "__all__"

My previously existing contact page view is as below:

class ContactUsPageView(ListView):
    """
    In this view we are fetching site data from database, in a function named
    get_context_data. In this function, we filter the model for objects that contains
    the word 'تماس', therefore fetching data referring to the about page only.
    After that the context list is sent to the template, and there with a for loop
    and an if statement, each key, value set is chosen for the proper place.
    """

    model = SiteDataKeyValue
    template_name: str = "core/contact-us.html"

    def get_context_data(self, **kwargs):
        context = super(ContactUsPageView, self).get_context_data(**kwargs)
        context["contact_page_data"] = self.model.objects.filter(key__icontains="تماس")
        return context

Now, I have no idea how to proceed. How am I supposed to add this form to my view, then send it along with the contact_page_data to the template, and how to style it (styling is not the question here and I'll deal with it as soon as the view is complete.).

CodePudding user response:

You have to use a simple FormView:

class ContactUsPageView(FormView):

    form_class = ContactForm
    template_name: str = "core/contact-us.html"
    success_url = "..."

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(ContactUsPageView, self).get_context_data(**kwargs)
        context["contact_page_data"] = self.model.objects.filter(key__icontains="تماس")
        return context

and display with {{form}} your form in html

CodePudding user response:

See whether this helps

class ContactUsPageView(ListView):

    model = SiteDataKeyValue
    template_name: str = "core/contact-us.html"
    context_object_name = 'contact_page_data'

    def get_queryset(self):
        return SiteDataKeyValue.objects.filter(key__icontains="تماس")

    def get_context_data(self, **kwargs):
        form = ContactForm()
        context = super(self).get_context_data(**kwargs)
        if not kwargs.get("form"):
            context['form'] = form
        return context

    def post(self, request, pk, **kwargs):
        data = request.POST
        form = ContactForm(request.POST)
        # form = ContactForm(request.POST, request.FILES) # If your sending files in the form
        if form.is_valid():
            form.save()
            return direct to success_url

        # render form with errors
        context = self.get_context_data(form=form)
        return self.render_to_response(context)
  • Related