Best practices on saving in a view, based on example code

前端 未结 2 1907
悲哀的现实
悲哀的现实 2021-02-11 08:30

I\'m new to Django and looking for best practices on the code I just wrote (below). The code currently exists in my view.py and simply creates a new event. Being familiar with o

2条回答
  •  执笔经年
    2021-02-11 08:52

    You should read about create forms from models. The ModelForm class will save you from copying the fields from the form to the model.

    Apart from that this view looks pretty normal to me.

    You can even get rid of some of the boilerplate code (if request.method == "POST", if form.is_valid(), etc.) with the generic FormView or CreateView. Since you seam to have some special form handling it might not be of any use for you, but it might be worth a look.

    This code is not 100% complete (your special logic for cities is missing) but apart from that should be pretty complete and give you an idea how generic views could be used.

    forms.py

    from django.forms import ModelForm
    
    class EventForm(ModelForm):
    
        def __init__(self, user, **kwargs):
            self.user = user
            super(EventForm, self).__init__(**kwargs)
    
        class Meta:
            model = Event
    
        def save(self, commit=True):
            event = super(EventForm, self).save(commit=False)
            event.user = self.user
            if commit:
                event.save()
    

    views.py

    from django.views.generic.edit import CreateView
    
    class EventCreate(CreateView):
        model = Event
        form_class = EventForm
        template = "events/event_edit.html"
        success_url = "/events/invite/" # XXX use reverse()
    
        def get_form(form_class):
            return form_class(self.request.user, **self.get_form_kwargs())
    
        def form_valid(form):
            form.user = self.request.user
    
            messages.success(request, 'Event has been created.')
            super(EventCreate, self).form_valid(form)
    
        def form_invalid(form):
            messages.error(request, 'Error')
            super(EventCreate, self).form_invalid(form)
    

    urls.py

    url(r'event/add/$', EventCreate.as_view(), name='event_create'),
    

提交回复
热议问题