问题描述
我刚刚编写Django并寻找我刚才写的代码的最佳实践(下面)。代码目前存在于我的view.py中,只需创建一个新的事件。熟悉其他语言,如果你知道我的意思,它就会闻起来很糟糕。有人可以指出他们将如何做这个简单的任务。唯一再次看到我的代码(从阅读文档多一点),将是移动request.user进入models.py保存功能。
还有其他什么是下面的一个大的新手错误?
@ login_required
def event_new(request):
#如果我们有一个POST,然后获取请求的帖子值。
如果request.method =='POST':
form = EventForm(request.POST)
#检查我们有效的数据
如果form.is_valid():
#如果表单已通过所有验证检查,则继续保存。
city = City.objects.get(name = form.cleaned_data ['autocompleteCity'])
category = form.cleaned_data ['category']
event = Event(
name = form.cleaned_data ['name'],
details = form.cleaned_data ['details'],
date = form.cleaned_data ['date'],
start = form.cleaned_data [ 'start'],
end = form.cleaned_data ['end'],
category = category,
city = city,
user = request.user,
)
event.save()
messages.add_message(request,messages.SUCCESS,'Event has been created。')
return HttpResponseRedirect('/ events / invite /' )
else:
messages.add_message(request,messages.ERROR,'Error')
context = {'form':form}
返回render_to_response('events / e通过上面的例子,我们可以通过这个方法来获得一个简单的例子。 ('events / event_edit.html',context,context_instance = RequestContext(request))
您应该阅读有关或。因为你接缝有一些特殊的表单处理方式,可能对你没有任何用处,但可能值得一看。
这段代码不完整100%你的城市的特殊逻辑缺失),但除此之外应该是相当完整的,并给出一个想法如何使用通用视图。
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
如果提交:
event.save()
views.py
from django.views.generic.edit import CreateView
class EventCreate(CreateView):
mod el = Event
form_class = EventForm
template =events / event_edit.html
success_url =/ events / invite /#XXX使用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(请求,事件已创建)
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'),
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 other languages it just 'smells bad' if you know what I mean. Could someone point out how they would do this simple task.
The only thing looking at my code again (and from reading the docs a little more), would be to move the request.user into the models.py save function.
Anything else which is a big newbie mistake below?
@login_required
def event_new(request):
# If we had a POST then get the request post values.
if request.method == 'POST':
form = EventForm(request.POST)
# Check we have valid data
if form.is_valid():
# If form has passed all validation checks then continue to save it.
city = City.objects.get(name=form.cleaned_data['autocompleteCity'])
category = form.cleaned_data['category']
event = Event(
name=form.cleaned_data['name'],
details=form.cleaned_data['details'],
date=form.cleaned_data['date'],
start=form.cleaned_data['start'],
end=form.cleaned_data['end'],
category=category,
city=city,
user=request.user,
)
event.save()
messages.add_message(request, messages.SUCCESS, 'Event has been created.')
return HttpResponseRedirect('/events/invite/')
else:
messages.add_message(request, messages.ERROR, 'Error')
context = {'form': form}
return render_to_response('events/event_edit.html', context, context_instance=RequestContext(request))
else:
form = EventForm
context = {'form': form}
return render_to_response('events/event_edit.html', context, context_instance=RequestContext(request))
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'),
这篇关于基于示例代码保存视图的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!