简体   繁体   中英

Problem setting initial Django ModelForm field value

I'm trying to set the default value in the form (the field is the date for publishing the article “public”), but when loading the form on the page, the field is empty. I tried to set the default value in the "header" field (any value, not necessarily today's date) - also does not appear.

form:

from main.models import Article
from datetime import datetime


class AddArticleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AddArticleForm, self).__init__(*args, **kwargs)
        self.fields['publish'].initial = datetime.now()

    class Meta:
        model = Article
        fields = ('title', 'author', 'body', 'publish', 'status')
        labels = {
            'body': 'Text'
        }
        widgets = {
            'title': forms.TextInput(attrs={'class': 'md-form'}),
            'author': forms.TextInput(attrs={'class': 'md-form'}),
            'body': forms.Textarea(attrs={'class': 'md-textarea', 'rows': 3}),
            'publish': forms.DateTimeInput(attrs={'class': 'md-form'}),
            'status': forms.Select(attrs={'class': 'custom-select'})

        }

views:

def add_article(request):
    form = AddArticleForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/articles/')
    args = {
        'form': form
    }
    return render(request, 'html/add_article.html', args)

html:

...
<form action="." method="post" class="add-article">
            {% csrf_token %}
            {% for field in form %}
                <div class="md-form">
                    {% if field.name != 'status' and field.name != 'publish' %}
                        <label for="{{ field.name }}">{{ field.label }}</label> {{ field }}
                    {% else %}
                         <label for="{{ field.name }}"></label> {{ field }}
                    {% endif %}
                </div>
            {% endfor %}
            <button type="submit" class="btn btn-pink btn-block">Share</button>
        </form>
...

表格

Probably the issue is you are sending request.POST as argument to the form class even if it is a GET request.

form = AddArticleForm(request.POST)
                      ^^^^^^^^^^^^^

So I suggest to update the view like this:

def add_article(request):
    form = AddArticleForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            return redirect('/articles/')
    context = {
        'form': form
    }
    return render(request, 'html/add_article.html', context)

So that, it will handle POST requests explicitly, and send request.POST as argument only if there is request.POST .

I think you should add initial argument in your field form. For example:

name = forms.CharField(initial='Your name')

Here is documentation on this:https://docs.djangoproject.com/en/3.0/ref/forms/fields/#initial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM