Django-在表单字段中预设外键值

时间:2018-06-19 19:37:18

标签: django django-forms

我正在努力解决这个问题,希望这里有人可以帮助我。我有一个名为“ Team”的模型,该模型具有一个ForeignKey字段,该字段对应于我在其上显示的ModelForm页面(“部门”)。因为它在页面上,所以我想在后端(视图或表单)中设置ForeignKey,而不是让用户选择它。

在其他示例中,我进行了设置,以便将值添加到表单部分,但是在提交表单时,在终端中出现以下错误(随后是request.POST打印出来):

<ul class="errorlist"><li>Department<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

<QueryDict: {'csrfmiddlewaretoken': ['KeEJF7KFr6l9dbkmZWA7u4Qg3eKqqFGcB2qq2AIEmilLP87AySi60ig3hJl6TBS0'], 'title': ['test'], 'description': [''], 'events': [''], 'current_status': [''], 'notes': [''], 'impact': [''], 'timeliness': [''], 'likelihood': [''], 'risk': [''], 'summary': [''], 'documents': ['']}>

表格:

class TeamFormCreate(forms.ModelForm):

    class Meta:
        model = Team
        fields = ('department', 'title', 'description', 'events', 'current_status', 'notes', 'impact',
                  'timeliness', 'likelihood', 'risk', 'summary', 'documents')

查看:

@login_required
def new_team(request):

    if request.method == "POST":
        form = TeamFormCreate(request.POST)
        if form.is_valid():
            team = form.save(commit=False)
            team.author = request.user
            team.modified_date = timezone.now()
            team.save()
            return redirect('/dashboard/1')
        else:
            return redirect('/dashboard/1')

    else:
        cd_id = request.GET.get('id', None)
        form = TeamFormCreate(cd_id)
        return render(request, 'app/sidebar_team.html', {'form': form}) 

型号:

class Team(models.Model):
    department = models.ForeignKey('MyApp.Department', related_name='teams')
    author = models.ForeignKey('auth.User')
    modified_date = models.DateTimeField(default=timezone.now)
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    events = models.TextField(blank=True, null=True)
    current_status = models.TextField(blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    order = models.IntegerField(default=0)
    # icon = models.ImageField()

    # Document files
    summary = models.FileField(upload_to='team', blank=True, null=True)
    documents = models.FileField(upload_to='team', blank=True, null=True)

    # Ratings
    RATING_CHOICES = [(x, x) for x in range(1, 6)]
    impact = models.IntegerField(choices=RATING_CHOICES, blank=True, null=True)
    timeliness = models.IntegerField(choices=RATING_CHOICES, blank=True, null=True)
    likelihood = models.IntegerField(choices=RATING_CHOICES, blank=True, null=True)
    risk = models.IntegerField(choices=RATING_CHOICES, blank=True, null=True)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:0)

通过将我的视图从基于函数的视图更改为以下基于类的视图,我终于能够实现这一目标。

# Required Imports
from django.views.generic import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin

class TeamCreate(LoginRequiredMixin, CreateView):
    model = Team
    form_class = TeamFormCreate
    template_name = 'app/sidebar_team.html'

    def get_initial(self):
        pk = self.request.GET.get('id')
        return {
            'department': pk,
        }

    def post(self, request, *args, **kwargs):
        form = TeamFormUpdate(request.POST)
        if form.is_valid():
            team = form.save(commit=False)
            team.author = request.user
            team.modified_date = timezone.now()
            team.save()
            return redirect('/dashboard/' + str(team.department.id))
        else:
            return redirect('/dashboard/' + str(form.department.id))