如何在Listview中验证其表单之前访问/修改django模型字段

时间:2016-12-27 08:59:35

标签: django django-models django-forms django-views

我有一个模型课程,其中包含以下内容:

class Course(models.Model):
    user= models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        )
    # email= models.EmailField(default=user.email)
    courseName= models.CharField(max_length=20, blank=False)

    class Meta:
        unique_together= ('user','courseName',)


    def __str__(self):
        return self.courseName

我创建了一个表单,我希望用户只输入courseName,然后在POST后,我也会在模型中添加请求的用户。

这是我的表单,它通过我的ListView

传递给模板

forms.py

class CourseForm(forms.ModelForm):
    class Meta:
        model= Course
        fields = ['courseName']

**这是我的views.py,我正在努力与**

class CoursesListView(ListView, FormMixin):
    model = Course
    form_class = CourseForm
    template_name = "userApp/courseList.html"

    def get_queryset(self):
        return Course.objects.filter(user__exact=self.request.user)

    def get_context_data(self,*args,**kwargs):
        context= super(CoursesListView,self).get_context_data(*args, **kwargs)
        context['courseForm'] = self.form_class
        return context

    def post(self,request, *args, **kwargs):
        form = self.form_class(request.POST)
        user = User.objects.get(username__exact=self.request.user)

        **I want to add the user to my model.user field here**

        return self.get(redirect, *args, **kwargs)

    def get(self,request, *args, **kwargs):
        self.object=None
        self.form = self.get_form(self.form_class)
        return ListView.get(self, request, *args, **kwargs)

所以基本上我的问题是如何在调用form.is_valid()之前在我的模型中添加用户。

2 个答案:

答案 0 :(得分:0)

这样的事情?

def post(self,request, *args, **kwargs):
    form_data = copy.copy(request.POST)
    form_data['user'] = User.objects.get(username__exact=self.request.user).pk
    form = self.form_class(form_data)

    # form handling follows

    return self.get(redirect, *args, **kwargs)

答案 1 :(得分:0)

此答案是由删除此答案的用户建议的。没有获得他的用户ID,但无论你是谁,非常感谢你的帮助!!!

只需使用form.save(commit = False)然后进行必要的更改。

def post(self,request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
        user = User.objects.get(username__exact=self.request.user)
        instance = form.save(commit=False)
        instance.user = user
        instance.save()