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})
Related
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
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)
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)
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)
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.