M
M
maniacus262019-01-11 16:59:40
Django
maniacus26, 2019-01-11 16:59:40

How can I disable the creation of empty posts in Django?

Greetings!
There is a form on Django, it has 10 fields, of which 5 are required, and if they are not filled in, then pressing the submit button will report that the required fields are not filled, while there is a "back" button next to it, and if you leave the form empty and "return", then an empty record appears in the database, where all required fields are empty.
Why is this happening?
This does not happen with other similar models
Django 2.0.7

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Shatalov, 2019-01-11
@maniacus26

Make these 5 required fields mandatory at the base level
. And now, without the view code, it is not clear what is there
At the model level, remove all default, blank=True, null=True from the fields.
Then the database itself will not allow you to create a record

M
maniacus26, 2019-01-11
@maniacus26

class UNew(CreateView):
    model = U
    fields = '__all__'
    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.helper = FormHelper()
        form.helper.add_input(Submit('submit', 'Create', css_class='btn-primary'))

        form.fields['ZAY_NUM'].label = "Номер заявления"
        form.fields['ZAY_TYPE'].label = "Тип заявления"
#-	далее описание кучи аналогичных полей       
#------ Причина записи в БД

        obj = form.save(commit=False)
        obj.author += self.request.user.username
        obj.save()

        return form

Thanks for the feedback. In the park, I didn’t notice a block (the last three lines) that spoils all my raspberries.
Here there is a saving of the user under which the form in a DB is filled.
Now it's interesting how to prevent creating a record in the database with this code if the fields are not filled in, or add the author in an alternative way.
Or

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question