如何允许用户为新问题表格创建其他选项

时间:2019-07-19 18:13:53

标签: python html django

我目前有一个表格,允许用户向我的网站发布新问题。当前,如果类别已经存在,则用户只能为他们的问题选择一个类别。我想允许用户能够为他们的问题添加一个新的类别。

我的模特

class Question(models.Model):
    title = models.CharField(max_length=200, help_text='Enter a question here')
    description = models.TextField(
        max_length=5000, help_text='Type your question description here')
    date_posted = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    times_favorited = models.PositiveIntegerField(
        default=0, help_text='Enter the number of times this question has been favorited')
    category = models.ManyToManyField(
        "Category", help_text='Enter the category for this question')


class Category(models.Model):
    name = models.CharField(
        max_length=100, help_text="Chose a category for your question.")

我的观点

@login_required 
def add_new_question(request):
    from core.forms import QuestionForm
    from django.views.generic.edit import CreateView
    # question = get_object_or_404(Question)
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.owner = request.user
            question.post = Question
            form.save()
            return redirect('question-list')
    else:
        form = QuestionForm()
    return render(request, 'core/question_form.html', {'form': form})

我的表格

class QuestionForm(forms.ModelForm):

    class Meta:
        model = Question
        fields = ('title', 'description', 'category',)

当前,如果没有现有类别,则用户不能发布他们的问题,因为类别是必填字段。我可以在管理页面中添加很多类别,但这不是理想的解决方案。任何帮助将不胜感激!

0 个答案:

没有答案