Saved model is None - django

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})

Related

Form Django can't update data

here's my code
i can't update my data if i used type "file"
My form can't be updated, I try print(form.error) but "this field requirement" appears, even though the form is filled out
views.py :
#login_required
def data_karyawan_edit(request, id):
karyawan = Karyawan.objects.get(id=id)
ar_divisi = Divisi.objects.all()
if request.method == 'POST':
form = KaryawanForm(request.POST, request.FILES, instance=karyawan)
print(form.errors)
if form.is_valid():
form.save()
messages.success(request, "Berhasil disimpan")
return redirect('data_karyawan')
else:
form = KaryawanForm()
return render(request, "data_karyawan/edit.html", {'karyawan': karyawan, 'ar_divisi': ar_divisi})

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})

Django how to assign posts to user

I need to assign posts to user in Django. I created
user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)
and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :
def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
ogloszenie = form.save(commit=False)
ogloszenie.user = request.user
ogloszenie.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {
'form': form,}
return render(request, 'formularz.html', context)
Can i please know how to resolve it?
Rewrite the form to exclude the user field:
class DodajForm(forms.ModelForm):
class Meta:
model = Dodaj
exclude = ['user']
In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:
def formularz(request):
if request.method == 'POST':
form = DodajForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {'form': form}
return render(request, 'formularz.html', context)

Django. How can I prevent another user from editing and deleting my listings?

Please help me implement these features so that another user cannot delete or edit my ads. So far, only unregistered users can not edit and delete.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
listing.delete()
return redirect('index')
#login_required
def listing_edit(request, listing_id):
form = ListingForm(instance = Listing.objects.get(id = listing_id))
if request.method == "POST":
form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id))
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
#login_required
def listing_add(request):
form = ListingForm()
if request.method == "POST":
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
listing = form.save(commit=False)
listing.realtor = request.user.realtor
listing.save()
return redirect('dashboard')
return render(request, 'listings/listing_add.html', {'form': form})
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')
...
class Realtor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')
You just need to check that the user making the POST request is the author (realtor) of the listing:
#login_required
def listing_edit(request, listing_id):
listing = Listing.objects.get(id=listing_id) # avoid multiple database calls
form = ListingForm(instance=listing)
if request.method == "POST" and request.user == listing.realtor.user:
form = ListingForm(request.POST, request.FILES, instance=listing)
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
The same applies for the delete view.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
if request.user == listing.realtor.user:
listing.delete()
return redirect('index')

Setting value of a form field in 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})