my todo list has two different functions
add_task & view_task
I don't want to create one single function
I want that view task will call add task
# Add Task Page
def add_task(request):
submitted = False
if request.method == "POST":
form = TodoForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_task?submitted=True')
else:
form = TodoForm
if 'submitted' in request.GET:
submitted = True
return render(request, "core/add_task.html", {'form':form, 'submitted': submitted})
# Task List Page
def view_task(request):
task_list = Todo.objects.all()
#This is the part of view_task function where I have been trying to call add_task function
# If you see a few lines below, I am calling already form,
return render(request, "core/view_task.html", {
'task_list': task_list,
#'form':form,
})
Why don't you just add your list of tasks to your add_taskview?
def add_task(request):
task_list = Todo.objects.all()
submitted = False
if request.method == "POST":
form = TodoForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_task?submitted=True')
else:
form = TodoForm()
if 'submitted' in request.GET:
submitted = True
return render(request, "core/add_task.html", {'form':form, 'task_list': task_list, 'submitted': submitted})
Related
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and i have tried diffrent solutions to fix this
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
# error is showing "instance" is not access using visual studio code
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
indentation error here:
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
You only need to tab once. Not twice.
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
I have 2 views, display_quote and quoteline_update
After updating a quoteline, I want to redirect to display_quote (quote to which the quoteline updated belongs).
I obtain the error:
Reverse for 'display_quote' with no arguments not found. 1 pattern(s) tried: ['\\^display_quote/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)\\$$']
Exception Type:NoReverseMatch
Views:
def display_quote(request, pk):
items_quote = Quote.objects.filter(pk=pk)
items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk)
form = QuoteLineForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
total = 0
for item in items_quote_line:
total = total + item.get_price()
context = {'items_quote': items_quote,
'items_quote_line': items_quote_line,
'form': form,
'total':total
}
return render(request, 'quote/quote_display.html', context)
def quoteline_update(request, pk):
model = QuoteLine
cls = LigneDevisForm
item = get_object_or_404(model, id=pk)
if request.method == "POST":
form = cls(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('display_quote')
else:
form = cls(instance=item)
return render(request, 'quote/quoteline_update.html', {'form': form})
I have this TemplateView:
class DamageEntry(TemplateView):
template_name = "damage/damageadd.html"
def get(self, request):
general = General.objects.get(pk=1)
form = DamageEntryForm()
args = {'form': form,
'general': general,
}
return render(request, self.template_name, args)
def post(self, request):
general = General.objects.get(pk=1)
form = DamageEntryForm(request.POST)
form.non_field_errors()
if form.is_valid():
post = form.save(commit=False)
if self.request.user.is_authenticated():
post.user = request.user
post.userip = get_client_ip(request) # το IP του χρήστη
location = get_cocation(post.lat, post.lng)
post.location = location
post.formatted_address= location.formatted_address
post.entry_date = datetime.datetime.now(tz=timezone.utc)
post.save()
form = DamageEntryForm()
args = {'form': form,
'general': general
}
return http.HttpResponseRedirect('damage/add/')
else:
print('form is not valid')
print(form.errors)
# form = DamageEntryForm()
args = {'form': form,
'general': general
}
return render(request, self.template_name, args)
It works fine for create new record.
I want to use thw same view for update, because of the extra code on Post section.
I use this URL for update:
# /damage/damage/list/1
url(r'damage/list/(?P<pk>[0-9]+)/$', views.DamageEntry.as_view(), name="damage-by-id"),
Can I do this? How can I pass pk for create and update record?
I have a problem in registration with django, here is my views code:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)
,but i always get:
ValueError at /user/register/ The view Users.views.register didn't
return an HttpResponse object. It returned None instead. Request
Method: POST Request URL: http://127.0.0.1:3001/user/register/ Django
Version: 2.0.2 Exception Type: ValueError Exception Value: The view
Users.views.register didn't return an HttpResponse object. It returned
None instead. Exception
Location: /home/iah/.local/lib/python3.5/site-packages/django/core/handlers/base.py
in _get_response, line 139
Check you code and ask yourself what happens if you have a POST request and the form doesn't validate - you'll find out that in this case you have no explicit return path, so the function implicitely returns None.
The fix is dead simple : deindent the last two line of your function, so you when the form doesn't validate you return the rendered template too:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
# MAKE SURE WE ALWAYS RETURN A RESPONSE:
# we end up here when it's a GET request
# AND when it's a POST request and the form
# did not validate
args = {'form': form}
return render(request, 'users/reg_form.html', args)
You have to return response from the inner else block:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
# here
...
Make sure you return something if the form is not valid and your form.is_valid() fails.
Example:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/') # or render(...)/whatever you need to redirect to
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)
Hope this helps!
You are missing the else code. Your if statement says: If the form is valid, save the form. But what if the form is not valid, What if the username is all special characters(ex: !##$%%%^^) or what if the username is only 1 Character long ex: (username:A). Or what if the password is only 3 characters long (ex: pas) In all these scenarios, the user should get the blank form back. You should also consider using class based views for registration This link will help
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
**if form.is_valid():**
# What if the form is not valid you haven't accounted for that
form.save()
return redirect('/')
else:
# Adding a else solves this problem. The user gets a blank form back
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)**
I have created an invoice and items in it using Modelform and inlineforset_factory.
Now I am trying to create edit form, but I am getting MultiValueDictKeyError when I try to edit those inline fields. If I just create new inlineformsets I can edit Modelform just fine. After one hour of googling I am no closer to finding any solution.
maxItems = 20
ItemFormSet = inlineformset_factory(Invoice, Item, can_delete=True, extra=maxItems)
Creating of new invoice (working perfectly)
def new_invoice(request):
if request.method == "POST":
form = InvoiceForm(request.POST)
if form.is_valid():
invoice = form.save(commit=False)
item_formset = ItemFormSet(request.POST,instance=invoice)
if item_formset.is_valid():
invoice.dateCreated = datetime.datetime.now()
invoice.save()
item_formset.save()
return redirect('list/new0')
else:
form = InvoiceForm()
item_formset = ItemFormSet(instance=Invoice())
return render(request, "form.html", {"form": form, "item_formset": item_formset })
Editing invoice (MultiValueDictKeyError)
def edit_invoice(request, invoice_id):
invoicer = get_object_or_404(Invoice, pk=invoice_id)
if request.method == "POST":
form = InvoiceForm(request.POST, instance=invoicer)
if form.is_valid():
invoice = form.save(commit=False)
item_formset = ItemFormSet(request.POST,instance=invoice)
if item_formset.is_valid():
invoice.dateCreated = datetime.datetime.now()
invoice.save()
item_formset.save()
return redirect('list/new0')
else:
form = InvoiceForm(instance=invoicer)
item_formset = ItemFormSet(instance=invoicer)
return render(request, "form.html", {"form": form, "item_formset": item_formset })
You have two variables, invoicer and invoice that I assume are different instances of the same object. Try re-writing your edit view like this:
def edit_invoice(request, invoice_id):
invoice = get_object_or_404(Invoice, pk=invoice_id)
if request.method == 'POST':
form = InvoiceForm(request.POST, instance=invoice)
formset = ItemFormSet(request.POST, instance=invoice)
if form.is_valid() and formset.is_valid():
invoice = form.save()
invoice.dateCreated = datetime.datetime.now()
invoice.save()
formset.save()
return redirect('list/new0')
else:
form = InvoiceForm(instance=invoice)
formset = ItemFormSet(instance=invoice)
context = {
'form': form,
'formset': formset,
}
return render(request, 'form.html', context)
Let me know if that works for you.
Ok, so I've found that problem was not in the views.py nor in forms.py, but in template. Because I've built the template without using {{form.as_p/table/...}} The form had some extra inputs - DELETE,ID and foreignKey... after adding them to my for loop, everything works fine :)