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!
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'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient.
My suggestion looks like this:
urls.py:
path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"),
path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"),
Views. py:
def kartotek(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
E_patient = kliniknavn.patient_set.all()
context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient}
return render(request,'DentHelp/kartotek.html', context )
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek/<str:kl_id>/')
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context)
When running code I get an OSError for the last line of code shown here.
Have you guys have any advise for this to work?
You are mixing up render with redirect. render renders a template dynamically with attributes from context, where redirect redirects the user to a different view. To call render, you need to provide template name and context. For redirect, you need to provide url name and parameters (if required). Here is how you should do in your code:
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek', kl_id) # url name and parameter
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request, 'DentHelp/kartotek/opretpatient.html', context) # template name and context
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.
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)
Sorry if my english is bad, but if you need question, i'm here :)
I saw many answers about this subject of HttpResponse object in Django, but i can't resolve it.
Normally the user insert his email address in order to recieve an email for his new password.
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
sendResetPasswordMail(user, request.META['HTTP_HOST'])
else:
form = PasswordResetRequestForm()
return render(request, 'front/reset_password_form.html', {'form': form})
After these error is displayed : "View" didn't return an HttpResponse object. It returned None instead. I can recieve the mail anyway, so the problem is in this function but i can't resolve it.
If you have some ideas, i am open :)
You are missing a return in your if statement.
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
return sendResetPasswordMail(user, request.META['HTTP_HOST'])
else:
form = PasswordResetRequestForm()
return render(request, 'front/reset_password_form.html', {'form': form})
I am assuming that the sendResetPasswordMail is also returning a HttpResponse
Hope this helps
It is happening because your view doesn't return a response for a POST request.
You should add something like redirect page when the email is successfully sent, something like this:
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
sendResetPasswordMail(user, request.META['HTTP_HOST'])
return redirect('/password-reset-email-sent/')
......