Display Table and Form in Django View - python

I am attempting to return a form and table in the same view so that they appear in the same screen.
I know that the below code does not work, it is to illustrate what I want to do - I have my CreateManifestForm and manifests = Manifests.objects.all() should populate the table which is present in the template. The problem is when I render this - it shows the form, and just the blank table. I have populated the table using a separate view so I know that it is set up properly on its own, but how can I render {'form': form} and context at the same time?
Views.py:
def add_manifest(request):
manifests = Manifests.objects.all()
context = {
'manifests' : manifests,
}
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
return redirect('display_orders')
else:
form = CreateManifestForm()
return render(request, 'add_manifest.html', {'form': form})
return render(request, 'add_manifest.html', context)

You need to just return everything you need in the context. You have 2 returns there so the second one never happens.
You'll need to do;
def add_manifest(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
return redirect('display_orders')
# Leave this down here so that you don't hit
# the database for manifests on a POST when
# the form is valid, because that returns above
form = CreateManifestForm()
manifests = Manifests.objects.all()
context = {
'form': form,
'manifests': manifests,
}
return render(request, 'add_manifest.html', context)

Related

Why Djano forms fields value not rendering in html template for function based update view?

This is my update views:
def EditDoctor(request,slug=None):
if request.method == "POST":
obj = get_object_or_404(Doctor,slug=slug)
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom()
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms.
You need to pass the instance to the form in case of a GET request as well:
def EditDoctor(request,slug=None):
obj = get_object_or_404(Doctor,slug=slug) # 🖘 fetch the object for both paths
if request.method == "POST":
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom(instance=obj) # 🖘 pass the instance to edit
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)

Using Value From One View in Another View Django

In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist".
This is what I'm trying (I've commented the code in view2 to indicate where im getting the error).
views.py
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('view2')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
...
reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id
Something like this:
from django.urls import reverse
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
obj = form.save()
reference_id = request.POST.get('reference') or obj.reference.id
return redirect(reverse('view2')+f'?reference={reference_id}')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
...
data = getattr(request, 'POST', None) or getattr(request, 'GET', {})
reference_id = data.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)

Initial value of inputs in Django not working

I defined an initial value to my title field, but once I execute it, it shows no error and the initial value is not showing in my field how do I solve it? Thanks
def form_view(request):
if request.method == "POST":
initial_data = {
'title': 'default title'
}
form = ProductForm(request.POST, initial=initial_data)
if form.is_valid():
form.save()
form = ProductForm()
else:
form = ProductForm()
return render(request, "form.html", {"form": form})
You've put it in the wrong place. If you want it to show when the form is first rendered, you shouldn't put it in the POST block - which is called when the form is submitted - but the else block.
if request.method == 'POST':
form = ProductForm(request.POST)
...
else:
form = ProductForm(initial=initial_data)

django - how to redirect page after save modelform

I want to redirtect page, after saving modelform. when i pushed save button, page redirecte, but no any things saved.
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args=[channelid]))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
This will get you closer to the solution. I'm not positive if you have 'updateChannelInfo' as the name in urls.py (so please double-check that). I think the complexity here is getting the correct channelId to be sent
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args = [self.object.id])))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
If you are willing to share your urls.py and forms.py files, this would help with getting the correct names into arguments
Another way I have had success with the dynamic direct after form submission is to use
def add_channel (request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channel.save()
return HttpResponseRedirect(reverse('channel_detail', args=[channel.id]))
else:
form = ChannelForm()
return render(request, 'channel_example.html', {'form': form})
Edit your view like this,
if form.is_valid():
form.save()
return redirect('updateChannelInfo', channelId=self.object.id)

POST doesnt work

Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):
Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):
if request.method == "POST":
form1 = PersonForm(request.POST, prefix="form1")
form2 = EmailForm(request.POST, prefix="form2")
name = form2['email'].value
return HttpResponse(name)
else:
form1 = PersonForm()
form2 = EmailForm()
return render(request, 'CreatePersonEmail.html', locals())`
but when i separate them i.e.
Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):
if request.method == "POST":
# form1 = PersonForm(request.POST, prefix="form1")
form2 = EmailForm(request.POST, prefix="form2")
name = form2['email'].value
return HttpResponse(name)
else:
form1 = PersonForm()
form2 = EmailForm()
return render(request, 'CreatePersonEmail.html', locals())`
it gives me the value of the field.
Why? and how can i make it to obtain the values of both forms fields?
Basically, you're doing it wrong.
Firstly, you need to check if the form is valid. Users could type any crap in, you don't want to let them do that:
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
# Now you can access the fields:
name = form.cleaned_data['name']
If the form isn't valid, just pass it back to render() and it will show the errors.
Also, don't do this:
return render(request, 'CreatePersonEmail.html', locals())`
Build your context dictionary properly, don't use locals(), it's hacky and you pollute your context.
So a full view might look like this (taken from django docs and changed a bit:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
name = form.cleaned_data['name']
return render(request, 'some_page.html', {'name': name})
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
You need to use the prefix both times you instantiate the forms; both on GET and on POST.
Also, you get values from the form's cleaned_data dict, not from the field.

Categories