簡體   English   中英

Django:如何使用外鍵字段創建表單(輸入為 CharField)

[英]Django: How to create form with ForeignKey field (input as CharField)

我創建了兩個模型文章和作者,如下所示:

模型.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 (在作者模型中)中。 這是可能的嗎? 我似乎無法讓它工作。 這是我嘗試過的:

表單.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']

視圖.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)

提前致謝!

您需要將作者姓名輸入作為字符字段提供,並手動獲取或創建作者。 您還需要在author_name上設置unique=True 試試這樣的表格:

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()

對我有用的是將代碼從保存移動到清理

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()

然后在 views.py 中只是一個常規過程

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

我剛到這里遇到類似的問題。 從您的代碼開始,就我而言,我添加了“__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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM