首页 > 解决方案 > 获取用户表中注册的不同用户名并使用表单集将其保存为外键

问题描述

我正在保存一个具有如下表单集的动态表单:-

表格.py

AuthorFormset = modelformset_factory(
    Author,
    fields=('title','content','due_date','author' ),
    extra=1,
    widgets={'title': forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Author Name here'}),
            'content': forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Description'}),
            'due_date': forms.DateInput(attrs={
            'class': 'form-control', 'placeholder': 'Date'}),
            'author': forms.TextInput(attrs={
            'class': 'form-control author-input',
            'placeholder': 'Participants'
        }),

“作者”字段之一,我使用自动完成模型从用户表中获取用户名。在我的 models.py 中,我将作者保存为 Author 表中的外键。类作者(models.Model):

    title = models.CharField(max_length=100, null=True)
    content = models.TextField(null=True)
    due_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'author'

    def __str__(self):
        return self.author.username

但是在调试时,我发现 POST 请求中返回的 formset 对象对作者字段显示'id': 'none'。我认为“作者”输入字段只接受 userId 而不是用户名。我是 django 的新手,我不知道如何从 User 模型中保存userId中的用户请指出我正确的方向。

视图.py

def create_book_with_authors(request):
    template_name = 'store/create_with_author.html'
    if request.method == 'GET':
        formset = AuthorFormset(request.GET or None)
    elif request.method == 'POST':
        formset = AuthorFormset(request.POST) 
        if formset.is_valid(): # Error saying that formset is not valid
            for form in formset:
                # so that `book` instance can be attached.
                author = form.save(commit=False)
                author.save()
            return redirect('mom:home')
    return render(request, template_name, {'formset': formset})

标签: djangopython-3.xdjango-modelsdjango-forms

解决方案


我认为由于作者是 ForeignKey,因此您必须使用 TextInput 的值获取实际的用户实例,然后将该实例另存为值。尝试:

 if formset.is_valid(): # Error saying that formset is not valid
     for form in formset:
         # so that `book` instance can be attached.
         author = form.save(commit=False)
         a = Author.objects.get(username=author.author) # Or however you get the unique author
         author.author = a
         author.save()

推荐阅读