Setting value of a form field in Django - django

I'm attempting to modify a field after the user has submitted the form. I've found several pieces of code online, but none seem to work. Below is my attempt in views.py. Any guidance would be greatly appreciated.
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
form.cleaned_data['condition'] = 1 #form.condition = 1 also fails
form.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})

you can do like:
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.condition = 1
obj.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})

Related

Django, problem with render request: "The view main.views.licz didn't return an HttpResponse object. It returned None instead."

I'am trying to do a website and I have problem with uploading the file. On admin site I can upload and import any file but when I create view, I get this:
"The view main.views.licz didn't return an HttpResponse object. It returned None instead."
Here is the code from main.models:
class Plik(models.Model):
file = models.FileField(upload_to='uploads/')
Code from forms.py:
class upload(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
And code from views.py:
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html", {"form":form})
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})
Plz I am trying to solve this like 5 days...
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html", {"form":form})
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})
# if request is GET, python will execute this part of the function
Your livz function does not return anything on a GET request.
If no return statement is given, Python will return None.
The return render(...) is only executed on a POST request (when the form is submitted) with invalid form.
You need to also render your page on other request method.
A typical form view should look like the following (pay attention to the indent):
def form_view(request):
if request.method == 'POST':
form = MyForm(data=request.POST)
if form.is_valid():
# do stuff with the form
return HttpResponseRedirect('/success-url')
else:
form = MyForm()
return render('my-template', {'form': form})
Pay attention to your conditions (if/else/...) and make sure your page return a response in every possible path the code execution takes.
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html")
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})

Where should I place my context for the forms_as.p to work properly

basically, i'm trying to form.as_p to list the values but its not working. Its not really that its not working, but it only works (it only appears in my template) after i press submit. I believe I have placed the context in the wrong place or the wrong indentation but im not sure where i should shift context['form'] = form to. I tried to shift it but it says that lcoal variable referenced before assignment. Could someone advise?
The reason why I put it below else is because i want to display the errors if there are errors
def create_blog_view(request):
context = {}
user = request.user
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
else:
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)
def create_blog_view(request):
context = {}
user = request.user
form = CreateBlogPostForm()
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
else:
context['form'] = form
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)
Before your if statement, you need to add:
form = CreateBlogPostForm()
context['form'] = form
This will initialise a blank form and add it to your context.
Currently, you are only adding 'form' to your context, if the form has been submitted (/ a POST request has been sent to the view) and the form has validation errors.
To avoid repeated code, better still would be something like this:
def create_blog_view(request):
user = request.user
form = CreateBlogPostForm()
if request.method == 'POST':
form = CreateBlogPostForm(request.POST, request.FILES)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)

Form validation in function views

Is there any difference between the 2 parts of code?
def test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
title = form.cleaned_data.get('title') #<<--
print(title)
return redirect('blog-home')
else:
form = TestForm()
return render(request, 'blog/test.html', {'form': form})
def test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
title = request.POST.get('title') # <<--
print(title)
return redirect('blog-home')
else:
form = TestForm()
return render(request, 'blog/test.html', {'form': form})
Since both cases is part of form.is_valid() condition I believe it should be same right?
No, it does not necessary produce same result as cleaned_data documentation states
Each field in a Form class is responsible not only for validating
data, but also for “cleaning” it – normalizing it to a consistent
format. This is a nice feature, because it allows data for a
particular field to be input in a variety of ways, always resulting in
consistent output.

Saved model is None

So i have a model that i'm trying to save using a form which submits successfully, but in the Admin the object value None. I know the problem is in the views but i can't figure it out. Here's my code:
Views.py
def profilecreate(request):
if request.method == 'GET':
form = ProfileForm()
else:
form = ProfileForm(request.POST)
if form.is_valid():
description = form.cleaned_data['description']
caption= form.cleaned_data['caption']
photo = form.cleaned_data['photo']
profile = Profile.objects.create(description=description, caption=caption, photo=photo)
return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id}))
return render(request, 'profile_form.html', {'form': form})
Someone please assist
Second view attempt
def profilecreate(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 = ProfileForm(request.POST)
# check whether it's valid:
if form.is_valid():
photo = form.cleaned_data['photo']
description = form.cleaned_data['description']
caption = form.cleaned_data['caption']
form.save(commit=True)
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = ProfileForm()
return render(request, 'profile_form.html', {'form': form})

Is it possible for superuser to create more than one post, and user to be post only one post?

currently, user can create only one post. but as a superuser I want to create more than one. I tried to do it in admin page but it won't work. Is there a way to do this?
#login_required
def add_category(request):
if Category.objects.filter(author=request.user).exists():
return render(request,'main/category_already_exists.html')
if request.method == 'POST':
category = Category(author=request.user)
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save(commit=True)
return redirect('index')
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})
#login_required
def add_category(request):
if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
return render(request,'main/category_already_exists.html')
if request.method == 'POST':
category = Category(author=request.user)
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save(commit=True)
return redirect('index')
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})