pythondjangoformsdetailsview

Details for model and form model on detail page


I have problem with connect two models on one page, detail page (Django 1.11).

I have model Event - I want to display details for this model on detail page - this is working for me.

class Event(models.Model):
    title = models.CharField(max_length=500)
    date = models.DateField()
    text = models.TextField()
    image = FilerImageField(null=True, blank=True)
    free_places = models.IntegerField()

    class Meta:
        ordering = ['-date']

    def __str__(self):
        return self.title

On another hand I have model Register

class Register(models.Model):
    event = models.ManyToManyField(Event)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    company = models.CharField(max_length=30, blank=True)
    street = models.CharField(max_length=50, blank=True)
    post_code = models.CharField(max_length=30, blank=True)
    city = models.CharField(max_length=30, blank=True)
    email = models.EmailField()
    phone_number = models.IntegerField(max_length=30)

    def __str__(self):
        return self.first_name

I want to signup user on event with folder on detail page, below details for events.

Here is my detail view, where I want to display details for event and take data from user to Register model:

class EventDetailView(DetailView, FormMixin):
    model = models.Event
    form_class = forms.RegisterForm

    def get_success_url(self):
        return reverse('events:list')

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Template:

{% extends 'base.html' %}

{% block content %}
    <ul>
        <h1>Detail page:</h1>
        <li>{{ object.title }}</li>
        <li>{{ object.text }}</li>
        <li>{{ object.date }}</li>
    </ul>

    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>

{% endblock content %}

After push submit button I have no items in Register model.


Solution

  • The default definition of form_valid on FormMixin is simply to redirect to the success URL. That's because it doesn't know anything about models, so it is not expecting a .save() method on the form.

    You should use ModelFormMixin instead.