S
S
Sasha Fedorov2021-05-27 21:38:51
Django
Sasha Fedorov, 2021-05-27 21:38:51

Why is django form not working?

Why is django form not working?
Here is the views.py code:

def create_trailer(request):
    form = TrailerForm()
    if request.method == 'POST':

        if form.is_valid():
            form = TrailerForm(request.POST, request.FILES)
            form.save()
    return render(request, 'polls/create_trailer.html', {'form': form})

Here is the create_trailer.html code:
<div class="create_trailer">
        <form class="create_trailer_form" method="post">
            {% if form.is_valid %}
            <h1>Форма валидна</h1>
            {% else %}
            {{ form.errors }}
            {% endif %}
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Создать статью">
        </form>
</div>

Here is the models.py code:
class Trailer(models.Model):
    name_trailer = models.CharField("Название трейлера", max_length=200)
    pub_date = models.DateTimeField('Дата публикации трейлера', default=timezone.now)
    preview_trailer = models.ImageField("Превью трейлера", upload_to='photo', default=None)
    trailer = models.FileField("Трейлер", upload_to='video')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default="anonim")

Here is the forms.py code:
class TrailerForm(ModelForm):
    class Meta:
        model = Trailer
        fields = ['name_trailer', 'preview_trailer', 'trailer', 'author']

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sasha Fedorov, 2021-05-28
@fedosacha02

There was a problem in views.py
So it was necessary:

def create_trailer(request):
    form = TrailerForm(request.POST, request.FILES)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
    return render(request, 'polls/create_trailer.html', {'form': form})

D
d051a, 2021-05-27
@d051a

Try like this:

<form enctype="multipart/form-data" method="post" action="/foo/">

I
Ivan, 2021-05-28
@JamesWest

Is the template rendered at all? Try to remove this part of the code:

{% if form.is_valid %}
            <h1>Форма валидна</h1>
{% else %}
            {{ form.errors }}
{% endif %}

and add, just in case, an attribute to the form tag: action="."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question