def addbook(request):
if request.method == 'POST':
book_name =request.POST['book_name']
Book = Book.objects.get()
Book.save()
return render_to_response('book_detail.html', {'books': books},context_instance=RequestContext(request))
else:
return render_to_response('addbook.html',context_instance=RequestContext(request))
def book_detail(request):
return render(request, 'book_detail.html')
the above is my view.py i am getting this error"MultiValueDictKeyError at /addbook/"
please help me
That error means that 'book_name' isn't in your POST data.
If you want to handle that case, you can use book_name = request.POST.get('book_name'), which will default book_name to None if it isn't in the POST data.
If not, you need to make sure the form has an input called 'book_name'.
Related
I have a form with counterparty, object and sections i connected them to each other with django-forms-dynamic package but object not connected to sections
Counterparty connected to object form but sections are not connected to object how can i fix that?
I guess that im wrong with 2 functions in forms.py: section_choices and initial_sections and they`re not connected to objects but dont know how to fix that
forms.py
class WorkLogForm(DynamicFormMixin, forms.ModelForm):
def object_choices(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query
def initial_object(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query.first()
def section_choices(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query
def initial_sections(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query.first()
contractor_counter = forms.ModelChoiceField(
label='Контрагент',
queryset=CounterParty.objects.none(),
initial=CounterParty.objects.first(),
empty_label='',
)
contractor_object = DynamicField(
forms.ModelChoiceField,
label='Объект',
queryset=object_choices,
initial=initial_object,
)
contractor_section = DynamicField(
forms.ModelMultipleChoiceField,
label='Раздел',
queryset=section_choices,
initial=initial_sections,
)
views.py
#login_required
def create_work_log(request):
if request.method == 'POST':
form = WorkLogForm(request.POST, user=request.user)
if form.is_valid():
work_log = form.save(commit=False)
work_log.author = request.user
work_log = form.save()
messages.success(request, 'Данные занесены успешно', {'work_log': work_log})
return redirect('create_worklog')
else:
messages.error(request, 'Ошибка валидации')
return redirect('create_worklog')
form = WorkLogForm(user=request.user, initial=initial)
return render(request, 'contractor/create_work_log.html', {'form': form})
def contractor_object(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_object'])
def contractor_section(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_section'])
This may not be an answer you want but I use HTMX for these things. Here is a link to their example for this.
https://htmx.org/examples/value-select/
There is also a package plugin called Django-htmx.
You may need to learn HTMX but it is a mature technology, rather simple and reliable. I am unfamiliar with Django-forms-dynamic
I have a view and a model form as shown below. I initially could get a single item ID to use inn the view. Now I need multiple items selected from a Select2MultipleWidget. How would I do this? I already tried as shown in my code. I can understand that the data from the form to the view is not correct.
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
The error
Select a valid choice. That choice is not one of the available choices.
I'm struggling to understand how to submit data from two django forms into two separate database tables from the same view. I only want one submit button. While this question got me closer to the solution, I'm getting errors and the data is not writing to the database. I think this code actually checks the two forms against each other instead of submitting both forms in one go. Any ideas?
Here's what I've tried:
For one form --> one table. This works, so it's a start.
# views.py
def BookFormView(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/books/")
else:
form = BookForm()
return render(request, 'books/createbooks.html',
{'form' : form})
However, when I add this form in from forms.py to get the subsequent views.py I get local variable 'book_form' referenced before assignment. That's usually an easy global-vs-local variable issue to fix, but I don't know what it means in this case.
def BookFormView(request):
if request.method == 'POST':
if 'book' in request.POST:
book_form = BookForm(request.POST, prefix='book')
if book_form.is_valid():
book_form.save()
return HttpResponseRedirect("/books/")
bookdetailsform = BookDetailsForm(prefix='bookdetails')
elif 'bookdetails' in request.POST:
bookdetailsform = BookDetailsForm(request.POST, prefix='bookdetails')
if bookdetailsform.is_valid():
bookdetailsform.save()
return HttpResponseRedirect("/books/")
book_form = BookForm(prefix='book')
else:
book_form = BookForm(prefix='book')
bookdetailsform = BookDetailsForm(prefix='bookdetails')
return render(request, 'books/createbook.html',
{'book_form' : book_form,
'bookdetailsform': bookdetailsform})
Based on the question's comments:
def BookFormView(request):
if request.method == 'POST':
book_form = BookForm(request.POST, prefix='book')
bookdetailsform = BookDetailsForm(request.POST, prefix='bookdetails')
if book_form.is_valid() and bookdetailsform.is_valid():
book_form.save()
bookdetailsform.save()
return HttpResponseRedirect("/books/")
else:
book_form = BookForm(prefix='book')
bookdetailsform = BookDetailsForm(prefix='bookdetails')
return render(request, 'books/createbook.html',
{'book_form': book_form, 'bookdetailsform': bookdetailsform})
I think the problem is that when a user submits a bookdetails post request,
it will be handled under if 'book' in request.POST: condition. Why?
because string bookdetails contains string book, no matter the type of request they do, it will be handled with if book in request.POST: condition.
I believe fixing that if condition problem is the first step.
I am working on my first django webaite, I am trying to submit two forms one after the other.
Here is the views.py :
def home(request):
import json
if request.method == 'POST':
form = MajorForm(request.POST)
if form.is_valid():
url = 'http://www.mysite.com:8082'
dataout = {'my':'data'}
headers = {'content-type':'application/json'}
r = requests.post(url,data=json.dumps(dataout),headers=headers)
return collector(request)
else:
return HttpResponse("thnx")
else:
form = MajorForm()
return render(request,'index.html',{'form':form})
def collector(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
return HttpResponse("thanx")
else:
return HttpResponse("not valid")
else:
form = ContactForm();
return render(request,'collector.html',{'form':form})
So the first view calls the second view. The first form works fine, and the second form is also displayed fine, but submitting the second form does not work at all ( I was never able to get to form.is_valid path). Maybe this entire approach of calling one view from another is not correct? What would be the right one?
Please indent your code correctly. Also you are missing an else in the collector function when the request.method is not POST.
def itemconfirmation(request, pk):
item = Food_item.objects.get(id=pk)
userobj = request.user
user = UserProfile.objects.get(user=userobj)
if request.method == 'POST':
count_form = CountForm(data=request.POST)
if count_form.is_valid():
countform = count_form.save(commit=False)
countform.useradno = user.adno
countform.itemid = item.id
countform.save()
c = RequestContext(request, {
'item': item, 'count_form': count_form
})
return render_to_response('itemconfirmation.html', context_instance=c)
I have a view defined like this. I'm getting error in making the user object extended to UserProfile and cannot user the user.id
Is the request.user authenticated? is it an AnonymousUser?
UserProfile.objects.get() method is not for creating an object but to get it from the database.
if it doesn't exist an exception will be raised.
use UserProfile.objects.create(..) with the initial data you may need for it.
hope this helps!
== edit ==
also, note that you are referring count_form in the RequestContext even when it wasn't initialized in case that the request.method was not "POST" (i.e. "GET")