Please how do connect a modelform to a CreateView

28 views
Skip to first unread message

Netesy Emmanuel

unread,
Sep 20, 2016, 8:17:03 PM9/20/16
to Django users
My View.py

class EducationCreate(CreateView):
    model = Education
    form_class = EducationForm

    def form_valid(self, form):
        form.instance.student = self.request.user
        return super(EducationCreate, self).form_valid(form)

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(EducationCreate, self).dispatch(*args, **kwargs)

url.py
url(r'^settings/education/add/$', views.EducationCreate.as_view(), name='education-add')

model.py
class Education(models.Model):
    student = models.ForeignKey(settings.AUTH_USER_MODEL)
    school = models.CharField(max_length=250)
    started = models.DateField()
    finished = models.DateField()
    degree = models.CharField(max_length=250)

Forms.py
class EducationForm(forms.ModelForm):
    school = forms.CharField(label="School Name",max_length=250,help_text="Please enter the school name.")
    started = forms.DateField(label="Started School",)
    finished = forms.DateField(label="Finished School",)
    degree = forms.CharField(label="Degree Earned",max_length=250, help_text="Please enter the degree earned.")
   
    class Meta:
        model = Education
        fields = ('student','school','started','finished','degree')

James Schneider

unread,
Sep 20, 2016, 8:28:59 PM9/20/16
to django...@googlegroups.com

On Sep 20, 2016 5:16 PM, "Netesy Emmanuel" <net...@gmail.com> wrote:
>
> My View.py
>
> class EducationCreate(CreateView):
>     model = Education
>     form_class = EducationForm
>

This is the linkage, so it looks like you already have it in place. Is there a specific issue you are having?

>     def form_valid(self, form):
>         form.instance.student = self.request.user
>         return super(EducationCreate, self).form_valid(form)
>
>     @method_decorator(login_required)
>     def dispatch(self, *args, **kwargs):
>         return super(EducationCreate, self).dispatch(*args, **kwargs)
>

Are you using 1.10? If so, you can take advantage of the new LoginRequiredMixin so that you don't need to decorate the dispatch() method.

https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-loginrequired-mixin

-James

Reply all
Reply to author
Forward
0 new messages