ModelForm中的默认值来自数据库

时间:2018-05-13 14:02:29

标签: django django-forms

我的Django应用程序中有一个ModelForm应始终在表单中显示最新的给定选项作为默认输入,但它不起作用:

models.py

from django.db import models

Anmeldung = (
    ('1', 'Ja'),
    ('2', 'Nein'),
    ('3', 'Noch nicht entschieden'),
)

Essen = (
    ('1', 'Fleisch'),
    ('2', 'Fisch'),
    ('3', 'Vegetarisch'),
)

class Eintrag(models.Model):
    Name = models.CharField(max_length=200)
    Anmeldung = models.CharField(
        max_length=2,
        choices=Anmeldung,
        default=Eintrag.objects.filter(Name=request.user).Anmeldung # Thats not working
    Essen = models.CharField(
        max_length=2,
        choices=Essen,
        default=1)
    pub_date = models.DateTimeField('date published')

每个用户只有一行在数据中,因此不应该是一个问题。 我该如何实现这一目标? models.py甚至是正确的地方,还是我必须将其写入视图或构成部分?

forms.py和models.py如果有帮助:

forms.py

from django import forms
from .models import Eintrag

class NameForm(forms.ModelForm):

    class Meta:
            model = Eintrag
            fields = ['Anmeldung', 'Essen']

views.py

from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect

from .forms import NameForm
from .models import Eintrag

@login_required()
def get_name(request):

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            Eintrag.objects.filter(Name=request.user).delete()
            eintrag = form.save(commit=False)
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            eintrag.Name = request.user  # Set the user object here
            eintrag.pub_date = timezone.now()  # Set the user object here
            eintrag.save()

            return HttpResponseRedirect(request.path)  # generate an empty form

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    posts = Eintrag.objects.filter(Name=request.user)
    return render(request, 'form/name.html', {'form': form, 'posts': posts})

感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

如果只想在表单中显示默认值,则应在表单中设置默认值。在views.py中使用以下代码并从模型中删除默认值

form = NameForm()
form.fields['Anmeldung'].initial = Eintrag.objects.filter(Name=request.user).last().Anmeldung