How to set default values in Forms - python

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)

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 Default Value in a Form from another Form in Django

I have two forms, one CreateOrderForm and one CreateManifestForm. Submitting CreateOrderForm renders CreateManifestForm.
There is an input in CreateOrderForm 'reference' which is user entered but then should default into the 'reference field of CreateManifestForm. I seem to be unable to figure out how to pass that value from form to form
FORMS.PY
class CreateOrderForm(forms.ModelForm):
class Meta:
model = Orders
fields = ('reference', 'ultimate_consignee', 'ship_to', 'vessel', 'booking_no', 'POL',....)
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'description', 'count')
VIEWS.PY
def add_order(request):
if request.method == "POST":
form = CreateOrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('add_manifest')
else:
form = CreateOrderForm()
return render(request, 'add_order.html', {'form': form})
def add_manifest(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
return redirect('add_manifest')
form = CreateManifestForm()
manifests = Manifests.objects.all()
context = {
'form': form,
'manifests': manifests,
}
return render(request, 'add_manifest.html', context)
As you can see there is a field in each form for 'reference' I would like to user enter it in CreateOrderForm and pass that value to default when creating the manifest. Any help is greatly appreciated and thank you in advance.
There is a solution that you can try:
make the add_manifest URL have a Parameter like
path('add-manifest/<int:reference_id>/', name='add_manifest`)
and in your View update:
return redirect('add_manifest') # in add_order function
to:
return redirect('add_manifest', kwargs={'reference_id': form.reference})
now in the add_manifest View you can access the Reference from:
request.resolver_match.kwargs.get('reference_id')

Remove user in Django

I would like to remove user.
I know that probably I can use some library like allauth but I want to do this on my view.
I didn't find any tutorial for that so I am trying to do this learn-by-mistakes way.
Ok. so in urls I have:
urlpatterns = [
('^remove$', views.remove_user, name="remove"),
]
forms:
class RemoveUser(forms.ModelForm):
class Meta:
model = User
fields = ('username',)
views:
#login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
username = request.POST.get('username')
if form.is_valid():
rem = User.objects.get(username=username)
rem.delete()
return redirect('main')
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
I can access website and type text in textfield. When I type random username I get error "user does not exist" so everything ok, but when I type correct username I get message: "A user with that username already exists" and this user is not removed.
Please, can you help me with that?
Change your form to a normal form-
class RemoveUser(forms.Form):
username = forms.CharField()
The view will be as follows -
#login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.delete()
return redirect('main')
else:
## Send some error messgae
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
EDIT-- Another way to approach the same problem is to deactivate the user
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.is_active = False
rem.save()

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