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
Related
def create_new(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
form.id_author = request.user.id
if form.is_valid():
form.save()
return redirect('home')
return render(request, 'main/create_new.html')
def create_new(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
return redirect('home')
return render(request, 'main/create_new.html')
Is it possible to change the 2nd code into the first code??
it shows some kind of error
No, at first you always need to check whether the form is valid or not, then after you can save the form with commit=False which creates a temporary instance, then you should assign any value in that instance.
The second approach is correct.
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'm new at Python & Django and currently struggling right now.
I created an update/edit form with Django Model forms, but it just doesn't prepopulate the form fields and post it to the database at the same time.
I think the problem lies in form = AdvertForm(request.POST or None, request.FILES or None, instance=form).
Without request.POST or None, request.FILES or None, it does prepopulate the fields but won't update the data to database.
Here's my views.py:
def update_advert(request, id):
if not request.user.is_authenticated():
return render(request, 'forum/login.html')
else:
form = get_object_or_404(Advert, pk=id)
if request.method == 'POST':
form = AdvertForm(request.POST or None, request.FILES or None, instance=form)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect('forum:user_account')
else:
form = AdvertForm(instance=form)
context = {'form': form}
return render(request, 'forum/update_advert.html', context)
In the moment it looks like this, when I try to open the update form:
opening the form --> not prepopulated :(
According to https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values, you can use the initial attribute when instantiating forms in order to prepropulate your forms.
def update_advert(request, id):
if not request.user.is_authenticated():
return render(request, 'forum/login.html')
else:
advert_obj = get_object_or_404(Advert, pk=id)
if request.method == 'POST':
form = AdvertForm(request.POST or None, request.FILES or None, instance=advert_obj)
if form.is_valid():
form.save()
return redirect('forum:user_account')
else:
# Prepopulation happens here:
data = {"some_field": advert_obj.some_val} # Insert all the values of advert_obj here and their field names as keys.
form = AdvertForm(initial=data)
context = {'form': form}
return render(request, 'forum/update_advert.html', context)
In your AdvertForm, put this code:
class AdvertForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(AdvertForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
instance = super(AdvertForm, self).save(commit=False)
instance.user = self.request.user
if commit:
instance.save()
return instance
The overriding save method simply does what you were doing in the views to link up the request.user to the instance, however I have placed that code in the form class to keep your views simple.
Also, I can see one confusing (but not vital) issue - you have mixed up the variable names.
When calling form = get_object_or_404(Advert, pk=id), this should return to a variable name such as advert or something similar. Not form as that can be confusing as we are returning a model object not a form. Similarly, form.save(commit=False) returns an "instance" not a model form. This won't solve your problem but should be pointed out for more clarification on what exactly is being returned and how you should then name your variables.
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.