POST doesnt work - python

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.

Related

Initial values for some fields from db

Is it possible to put data from the database in the initial form?
def add_customer_from_list(request, pk):
application = Contact.objects.get(pk=pk)
params = {'name': application.name,
'email': application.email,
'phone_number': application.phone_number,
'dog_name': application.dog_name,
'service_type': application.service_type}
form = CustomerForm(request.POST or None, initial=params)
if form.is_valid():
"""form.name = form.cleaned_data['name']
form.email = form.cleaned_data['email']
form.phone_number = form.cleaned_data['phone_number']
form.address = form.cleaned_data['address']
form.dog_name = form.cleaned_data['dog_name']
form.dog_age = form.cleaned_data['dog_age']
form.service_type = form.cleaned_data['service_type']
form.training_place = form.cleaned_data['training_place']
form.contact_date = form.cleaned_data['contact_date']
form.source = form.cleaned_data['source']
form.status = form.cleaned_data['status']
form.notes = form.cleaned_data['notes']"""
form.save()
return redirect('xxx')
return render(request, 'xxx', {'form' : form})
I would like some fields to be automatically filled in from the database with data, I have already tried various ways but to no avail
What I wrote above for some reason does not fill the fields for me
Initial values you pass with initial=... are only displayed for "unbound forms", i.e. forms not having request data. Since you pass request.POST or even None that do not work. The usual idiom is:
if request.method == "POST":
# May skip passing initial here unless you use `form.has_changed()`
form = CustomerForm(request.POST, initial=initial)
if form.is_valid():
form.save()
return redirect(...)
else:
form = CustomerForm(initial=initial)
# pass either an invalid or a new form to template ...
If you need to pass initial values from a model instance it usually makes sense to use a ModelForm and use instance=... instead of initial=....
def create_customer(request, pk=None):
form = CustomerForm(request.POST or None)
if request.method == 'GET':
if pk is not None:
instance = Contact.objects.get(pk=pk)
form = CustomerForm(request.POST or None, instance=instance)
elif request.method == 'POST':
if form.is_valid():
form.save()
messages.success(request, 'Klient został pomyślnie utworzony')
return HttpResponseRedirect(reverse('xxx'))
return render(request, 'xxx', {'form': form})
I changed the whole concept, sent a link to the get to view methods where I used the method from a friend who posted here.
The optional parameter is because the function serves as a normal addition without a parameter as well
Regards and thanks for your help

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)

How to set default values in Forms

I am Building a BlogApp and i am stuck on a Problem.
What i am trying to do :-
I am trying to set the Default Value in forms.py for a Form.
views.py
def new_topic(request,user_id):
profiles = get_object_or_404(Profile,user_id=user_id)
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(data=request.POST)
new_topic = form.save(commit=False)
new_topic.owner = profile
new_topic.save()
return redirect('mains:topics',user_id=user_id)
#Display a blank or invalid form.
context = {'form':form}
return render(request, 'mains/new_topic.html', context)
forms.py
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['topic_no','topic_title']
What have i tried :-
I also did by using initial , BUT this didn't work for me.
form = DairyForm(request.POST,request.FILES,initial={'topic_title': 'Hello World'})
The Problem
Default value is not showing when i open form in browser.
I don't know what to do
Any help would be appreciated.
Thank You in Advance
You need to pass initial in the GET method, like this:
if request.method == 'GET':
form = TopicForm(initial={'topic_title': 'Hello World'})
else:
More information can be found in documentation.
You have to use instance=TopicInstance If you want any specific instance to be default. Or you want any other initial you should pass it like this
def new_topic(request,user_id):
profiles = get_object_or_404(Profile,user_id=user_id)
if request.method != 'POST':
form = TopicForm(initial={'topic_title': 'Hello World'})#When displaying it for first time
else:
form = TopicForm(data=request.POST)
new_topic = form.save(commit=False)
new_topic.owner = profile
new_topic.save()
return redirect('mains:topics',user_id=user_id)
#Display a blank or invalid form.
context = {'form':form}
return render(request, 'mains/new_topic.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)

form.cleaned_data not working in django

def kw(request):
global form
ans="this is the default value"
form = NameForm(initial={'C': ans})
if form.is_valid():
print("helooo")
d = (form.cleaned_data['C'])
print("the value of d =",d)
return render(request, 'keyword.html', {'form': form})
This is my code but dont know why the form is not taken as valid ..
neither the print("helooo') cmd is working nor the next one .
if condition is not satisfied..
from django import forms
class NameForm(forms.Form):
C = forms.CharField(widget=forms.Textarea)
this is my form.py file
is_valid will never return True if the form is not bound, and yours is not, because you didn't pass any data. You would need to instantiate the form like this:
form = NameForm(request.POST)
There are many other problems with your code. You can take a look at this example to see how you might structure a view that processes a form.
def kw(request):
ans = "this is the default value"
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
print("helooo")
d = (form.cleaned_data['C'])
print("the value of d =",d)
else:
form = NameForm(initial={'C': ans})
return render(request, 'keyword.html', {'form': form})

Categories