我正在学习Django,在我对给定的代码感到困惑之前,它一直很不错。 有人可以逐行向我解释那里发生了什么吗?
from .forms import NewsLinkForm
from .models import NewsLink
class NewsLinkUpdate(View):
form_class = NewsLinkForm
template_name = 'organizer/newslink_form_update.html'
def get(self, request, pk):
newslink = get_object_or_404(NewsLink, pk=pk)
context = {
'form':self.form_class(instance=newslink),
'newslink':newslink,
}
return render(request, self.template_name, context)
def post(self,request,pk):
newslink = get_object_or_404(NewsLink, pk=pk)
bound_form = self.form_class(request.POST, instance=newslink)
if bound_form.is_valid():
new_newslink = bound_form.save()
return redirect(new_newslink)
else:
context = {
'form':bound_form,
'newslink':newslink,
}
return render(
request,
self.template_name,
context
)
答案 0 :(得分:0)
我添加了一些评论,希望您能理解
from .forms import NewsLinkForm
from .models import NewsLink
class NewsLinkUpdate(View): # class based view
form_class = NewsLinkForm # class of a form which seems to be in the view
template_name = 'organizer/newslink_form_update.html' # Link to the html template
def get(self, request, pk): # this is called when someone makes a GET request to your view, always takes in the request, additionally, a pk
newslink = get_object_or_404(NewsLink, pk=pk) # get object of model NewsLink by passed in pk, if there is none, returns 404
context = { # define context object, usually gets passed in into the template
'form':self.form_class(instance=newslink), # there is a form in the context, which fills with data from out NewsLink object
'newslink':newslink, # our NewsLink object
}
return render(request, self.template_name, context) # renders the page using the specified template and context
def post(self,request,pk): # this is called when someone makes a POST request to your view
newslink = get_object_or_404(NewsLink, pk=pk) # get object of model NewsLink by passed in pk, if there is none, returns 404
bound_form = self.form_class(request.POST, instance=newslink) # get an object of the form, filled with data from the post request and an instance of your object
if bound_form.is_valid(): # if the form data is valid
new_newslink = bound_form.save() # save changes to your form, automatically saves changes to your NewsLink
return redirect(new_newslink) # I only know redirect to redirect you to another view...
else:
context = { # context, as above
'form':bound_form, # your form with data
'newslink':newslink, # your NewsLink object
}
return render(
request,
self.template_name,
context
) # renders the page using the specified template and context