Django在表单提交时将数据添加到manyToManyField

当表单提交时,我想自动将提交表单的用户添加到下面给出的模型上的多对多用户字段中,我该如何从视图中进行操作?

该模型:

class Project(MainAbstractModel):
    users = models.ManyToManyField(User)
    title = models.CharField(max_length=25, default="Conflict")

风景:

def myconflicts(request):
    if request.method == "POST":
        form = ProjectForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            form = ProjectForm()
    return render(request, 'conflictmanagement/myconflicts.html')

我的形式很简单:

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ["title"]
评论
君追
君追

您可以在视图中添加用户,例如:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def myconflicts(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            project.users.add(request.user)
            return redirect('name-of-some-view')
    else:
        form = ProjectForm()
    return render(request, 'conflictmanagement/myconflicts.html', {'form': form})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

点赞
评论