Django在保存新对象之前添加主键

时间:2017-01-29 13:20:44

标签: python django django-models django-forms

我是Django的新手,并且有一个Q& A项目。对于每个问题,您可能有多个已存在的标签或新的标签。应在保存问题之前创建新标记。我该如何正确解决这个问题?到目前为止,我有:

def question_add(request):
    # redirect user to login page if not authenticated
    if not request.user.is_authenticated():
        return render(request, 'account/login.html')

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = QuestionForm(request.POST)

        if form.is_valid():
            # process the data in form.cleaned_data as required
            instance = form.save(commit=False)
            instance.created_by = request.user
            instance.save()

            messages.success(request, 'Question added with success.')
            # redirect to the main page:
            return HttpResponseRedirect('/')
        else:
            messages.warning(request, 'Please correct the errors.')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = QuestionForm()

    return render(request, 'question/add.html', {'form': form})

这应该在form.is_valid()之前完成,或者它是否存在这样做的神奇方法?

1 个答案:

答案 0 :(得分:0)

我假设tag是问题模型的ManyToMany字段。

form.is_valid()内添加manyToMany字段数据。

if form.is_valid():
     instance = form.save(commit=False)
     instance.created_by = request.user
     instance.save()
     # returns the list of tag names
     tags = request.POST.get('tags')
     for tag in tags:
         # create if tag not found with given name or return existing tag
         obj, created = Tag.objects.get_or_create(name=tag)
         instance.tags.add(obj)

如果标签是ForiegnKey:

if form.is_valid():
     instance = form.save(commit=False)
     instance.created_by = request.user
     tag_name = request.POST.get('tag')
     obj, created = Tag.objects.get_or_create(name=tag_name)
     instance.tag = obj.id
     instance.save()