1đź‘Ť
âś…
You shouldn’t use one view function for two different actions.
You should do view for add/edit Crave objects like this:
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
@login_required
def crave_edit(request, id=None):
instance = get_object_or_404(crave_data, pk=id) if id else None
if instance and instance.person != request.user:
raise PermissionDenied()
if request.method=="POST":
form=CraveDataForm(request.POST, request.FILES, instance=instance)
if form.is_valid():
crave_made = form.save(commit=False)
crave_made.person = request.user
crave_made.save()
else:
form=CraveDataForm(instance=instance)
return render(request, "crave/crave_edit.html", {'form' : form})
Once again, you shouldn’t mix add/edit Crave with add comments. You can’t add comment to non-exist entity:
@login_required
def crave_view(request, id):
crave = get_object_or_404(crave_data, pk=id)
if request.method=="POST":
form=CraveReplyForm(request.POST, request.FILES)
if form.is_valid():
reply = form.save(commit=False)
reply.person=request.user
reply.crave = crave
reply.save()
else:
form=CraveReplyForm()
return render(request, "crave/crave_view.html", {'crave': crave, 'form' : form})
And please note that names for models should be capitalised, without underlines – “crave_data” is bad style
👤Eugene Soldatov
0đź‘Ť
You can make the foreign key field optional in Django model
Try this way,
crave=models.ForeignKey(crave_data, blank=True, null=True)
If you want submit the forms independently. then put the hidden input field in one form and separate the form logic in view based on hidden input. Like this,
if 'hidden_input' in request.POST.keys():
👤dhana
Source:stackexchange.com