V
V
VadimJr2016-08-19 15:15:58
Django
VadimJr, 2016-08-19 15:15:58

Is there an analogue of update_fields in ModelForm?

Hello!
I'm learning django, making a one-page website. The site consists of the main page (contains the text and title) and the admin panel, where the information on the main page changes through the form.
The database (sqllite3) consists of one table with id, text, headline fields. I don't want to create many lines, so I always overwrite the entry with pk=1. I don't even know if this is right.
In the model, the "text" field is optional and can be empty.
Tell me, what code should I write in views (or in models) so that when saving the form in the database, the empty text value does not overwrite the previous value in the database? I saw the update_fields attribute in the docs, but it only works in Models descendants, not ModelsForm.
I will be glad to help, and in general comments on the project. Thank you!

models.py

class Info(models.Model):
    headline = models.TextField()
    text = models.TextField(blank=True)

    def get_headline(self):
        return self.headline

    zagolovok = property(get_headline)

    def __str__(self):
        return self.headline

form.py

class InfoForm(ModelForm):
    class Meta:
        model = Info
        fields = ['headline', 'text',]
        widgets = {
            'headline': TextInput(attrs={'size' : 100}),
            'text': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

UPDATE
get_headline is needed to get the row-level value.
view.py

text = Info.objects.get(pk=1)
    
def admin(request):
    if request.method == 'POST':
        form = InfoForm(request.POST, instance=text)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = InfoForm()

    return render(request, 'admin.html', {
        'form': form,
        'text': text,
    })

admin.html

<form action="change-admin" method="post">
        {% csrf_token %}
    <h2>Текущий заголовок</h2>
    <p>{{ text.headline }}</p>
        {{ form.headline }}
    <h2>Текущий текст</h2>
    <p>{{ text.text }}</p>
        {{ form.text }}
    <br /><input type="submit" value="Изменить">
  </form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question