How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.
Related
i'm doing a django project for adding and updating things with a mysql database, but i was told that it's not safe to add and update thing directly without JSON, is this possible? how can i do that?
here's my create function:
form = RoomForm()
if request.method == 'POST':
form = RoomForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'tasks/room_form.html', context)```
I am trying to have more control of my Django forms by adding a custom filter
from django import template
register = template.Library()
#register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
but getting the AttributeError: 'str' object has no attribute 'as_widget' error
here is my view
def index(request):
notes = Note.objects.all()
form = NoteForm()
if request.method == 'POST':
form = NoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('keep:index')
context = {'notes':notes, 'form':form}
return render(request,'Keep/note_form.html',context)
def update(request,id):
notes = Note.objects.get(id=id)
form = NoteForm(instance=notes)
if request.method == 'POST':
form = NoteForm(request.POST, instance=notes)
if form.is_valid():
form.save()
return redirect('keep:index')
context = {'notes': notes, 'form': form}
return render(request,"Keep/update.html",context)
def delete(request,id):
obj = get_object_or_404(Note,id=id)
if request.method == "POST":
obj.delete()
return redirect('keep:index')
return render(request,"Keep/delete.html")
PS. Before you throw me links to other similar questions, i want you to know i checked pretty much all the links and none of the solutions worked for me.
Most common is this:
else:
form = UserForm()
return render(request, 'register_user.html', {'form': form})
but as you can see, i did exact same thing but that doesn't work
In my case (I was struggled by the same error: 'CommentForm' object has no attribute 'as_widget') I was using a pipe with some function of widget_tweaks library on CommentForm, which doesn't work.
Try to look for unused libraries but imported in INSTALLED_APPS(settings.py); you also can check your HTML5 file for unused {% load some_library %}; If nothing wrong with what is said above, try to check for Django Template Tags incorrect syntax
(in my case it was {{comment_form|add_class:"form-control" }})
I hope it would help you!
I have a form and a model, in my views I take the data from form and use it to delete the object from my model, but it does not delete the object at all, even though if I use the shell and create the same query set with the same syntax it works. What am I missing here?? Thx
Code from views:
form = SecondForm()
query_list = DictWord.objects.all()
dict_DictWord = {'words': query_list,"form":form}
if request.method == "POST":
form = SecondForm(request.POST)
if form.is_valid():
##Does not delete the object from models
data = form.cleaned_data['name']
DictWord.objects.filter(name=data).delete()
return render(request, 'appone/index.html', context = dict_DictWord)
else:
messages.error(request, "Error")
return render(request,'appone/index.html',context=dict_DictWord)
But if I use manage.py shell, I import my model and this syntax works, and it returns the dict with the deleted object:
from app.models import DictWord
DictWord.objects.filter(name="SomeName").delete()
#try this
record=DictWord.objects.get(name=data)
record.delete()
return render(request, 'appone/index.html', context = dict_DictWord)
Views.py
def form_name_view(request):
form = FormName()
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
return render(request, 'first_app/form_page.html', {'form': form})
When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane:
After reaching index page if I hit refresh then alert appears says:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be
repeated. Do you want to continue?
If i want to get back to the same form page, by calling that same method again like
return form_name_view(request)
The new form is already filled with previous inserted data, with the message on the form
Topic with this Topic name already exists.
The question is what is the reason, calling method results like this?
def form_name_view(request):
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
else:
form = FormName()
return render(request, 'first_app/form_page.html', {'form': form})
use this
I am working on a web application which works with entities that all have their unique IDs.
I have a submit form for users to create these entities and this form is in several steps (i.e. view 1 redirects to view 2, etc... until the end of the submission process).
The first view will create the ID of the entity after form submission and I then need to use the ID of the instance created in the other views.
I do not want to pass this ID as a URL parameter to the other views as these will be POST and that means that users could easily manipulate these and create records in models for several IDs. I have managed to pass this ID to several views using the session parameters (request.session) but this is not ideal as this is permanent for the session. Current code below:
def view1(request):
if request.method == 'POST':
form = xxx_creation_form(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
... object creation ...
)
request.session['xxx_id'] = xxx_entry.id
return HttpResponseRedirect(reverse('form_2'))
else:
form = xxx_creation_form()
return render(request, 'xxx_form.html', {'form': form})
def view2(request):
xxx_id = request.session['property_id']
if xxx_id == 'SET_BACK_BLANK':
return render(request, 'no_xxx_id.html')
if request.method == 'POST':
form = xxx_form2(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
id = xxx_id, #use the id created in step 1
... rest of object creation ...
)
request.session['xxx_id'] = 'SET_BACK_BLANK' #to avoid the misuse during other user interactions.
return HttpResponseRedirect(reverse('thanks'))
else:
form = xxx_form2()
return render(request, 'xxx_form2.html', {'form': form})
Ideally, I would like to pass this ID parameter in the headers of the response as this will avoid having the ID as a session parameter. So I have amended the code to the below:
def view1(request):
if request.method == 'POST':
form = xxx_creation_form(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
... object creation ...
)
response = HttpResponseRedirect(reverse('form_2'))
response['xxx_id'] = xxx_entry.id
return response
else:
form = xxx_creation_form()
return render(request, 'xxx_form.html', {'form': form})
def view2(request):
xxx_id = HttpResponseRedirect(request).__getitem__('xxx_id')
if request.method == 'POST':
form = xxx_form2(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
id = xxx_id, #use the id created in step 1
... rest of object creation ...
)
return HttpResponseRedirect(reverse('thanks'))
else:
form = xxx_form2()
return render(request, 'xxx_form2.html', {'form': form})
However the above does not work and the error message seems to indicate that there is no 'xxx_id' in the response header.
It would be great if anyone could let me know how to access a response's header in a view as it seems that we cannot amend the request's headers.
Thanks.
What you're asking doesn't really make sense. The response is what is sent from Django to the browser, it is not what the browser sends to Django. That's a completely separate request; in the case of a redirect, your response is simply an instruction to the browser to make that request to a new URL.
The correct thing to do is to use the session, as you are doing. If you are worried about the value being persisted, then pop it out of the session when you use it:
xxx_id = request.session.pop('property_id')