Django:如何使用ForeignKey字段创建表单(输入为CharField)

时间:2016-03-03 06:15:44

标签: python django django-models django-forms

我创建了两个模型文章和作者:

model.py

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField(max_length = 5000)
    author = models.ForeignKey('Author', on_delete=models.CASCADE)

class Author(models.Model):
    author_name = models.CharField(max_length=200)
    author_intro = models.TextField(max_length = 3000)

我正在尝试创建一个允许用户输入文章信息*的表单(包括标题,内容,仅限作者)。因此,无论何时用户输入作者,该输入数据都存储在author(在文章模型中)和author_name(在作者模型中)中。这可能吗?我似乎无法让它工作。这是我试过的:

form.py:

class articleForm(forms.ModelForm):

    author = forms.ModelMultipleChoiceField(queryset=Author.objects.all())

    class Meta:
        model = Article
        fields = ['title']          
        widgets = {
        'content': forms.Textarea(attrs={'cols': 75, 'rows': 50})}


class authorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['author_name']

views.py:

def compose_article(request):

    form_article = articleForm(request.POST or None)
    if form_article.is_valid():
        instance = form_article.save(commit=False)
        instance.save()

    context = {
        "ArtileForm":form_article,
    }
    return render(request,"Upload.html",context)

提前致谢!

3 个答案:

答案 0 :(得分:1)

您需要将作者姓名输入作为字段提供,并手动处理或创建作者。 您还需要在unique=True上设置author_name。试试这样的表格:

class ArticleForm(forms.ModelForm):
    author = forms.CharField()

    class Meta:
        model = Article
        fields = ['title', 'author', 'content']
        widgets = {
            'content': forms.Textarea(attrs={'cols': 75, 'rows': 50}),
        }

    def save(self, commit=True):
        author, created = Author.objects.get_or_create(
            author_name=self.cleaned_data['author'],
            defaults={'author_intro': ''}
        )
        self.cleaned_data['author'] = author.id
        return super(ArticleForm, self).save(commit)

这样的观点:

from django.views.generic.edit import CreateView

class ArticleFormView(CreateView):
    form_class = ArticleForm
    template_name = 'Upload.html'

    # You can skip this method if you change "ArtileForm" to "form"
    # in your template.
    def get_context_data(self, **kwargs):
        cd = super(ArticleFormView, self).get_context_data(**kwargs)
        cd['ArtileForm'] = cd['form']
        return cd
compose_article = ArticleFormView.as_view()

答案 1 :(得分:0)

what worked for me was to move the code from the save to clean

def clean(self):
        group, created = Ideas_Group.objects.get_or_create(
                    category_text=self.cleaned_data.get('group'))
        self.cleaned_data['group'] = group
        return super(IdeasForm, self).clean()

and then in the views.py was just a regular process

def post(self, request):
    if request.method == 'POST':
        form = IdeasForm(request.POST)                                                                 
        if form.is_valid():
            ideapost = form.save(commit=False)                                       
            ideapost.save()

答案 2 :(得分:0)

我刚来这里是为了解决类似的问题。从您的代码开始,就我而言,我添加了“__id”。

class articleForm(forms.ModelForm):

     author__id = forms.IntegerField(...

打印表格的这一部分。 (27 是我的测试用例的 ID。)

<tr><th><label for="id_author">Author:</label></th><td><select name="author" required id="id_author">
   <option value="">---------</option>

   <option value="27" selected>Author</option>

 </select></td></tr>