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

前端 未结 2 1908
悲哀的现实
悲哀的现实 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'),
    
    0 讨论(0)
  • 2021-02-11 09:08

    I think this looks great. You have followed the conventions from the docs nicely.

    Moving request.user to a model would certainly be an anti pattern - a views function is to serve in the request/response loop, so access this property here makes sense. Models know nothing of requests/responses, so it's correct keep these decoupled from any view behavior.

    Only thing that I noticed was creating a category variable out only to be used in construction of the Event, very minor.

    0 讨论(0)
提交回复
热议问题