I made a web service with Django. It was completed, but I checked again where it was fluffy.
Example:
views.py
class ThreadView(ModelFormMixin, generic.DetailView):
model = Group
form_class = CommentCreateForm
def form_valid(self, form):
group_pk = self.kwargs['pk']
comment = form.save(commit=False)
comment.create_user = self.request.user
comment.post = get_object_or_404(Group, pk=group_pk)
comment.save()
return redirect('<app name>:group_thread', pk=group_pk)
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
self.object = self.get_object()
return self.form_invalid(form)
form.save(commit=False) Returns an instance of the Model object associated with the form. Do not register in DB
I used render, but I used it properly
HttpResponse Hand over strings and iterators (and it's officially written, but I haven't used it so I can't really imagine it.)
render The render method basically takes three arguments: request, template_name, and context. request: get or post template_name: html file context: Information on the data stored in the DB In the description of the official document, "Load the template, populate the context, and return the result of rendering the template in an HttpResponse object"
redirect Discard the data returned by POST and transition to a different view
Recommended Posts