Django 'PictureForm' object has no attribute 'save' - django

I'm trying to add a new feature to my existing app that let users create a profile and upload a pictures of their pets.
When a user login , he gets redirected into the profile which display his name and also he can add a picture of himself into the model which will get displayed on the profile page.
At the moment , I can retrieve the name into the template but I can't seem to display the user's name and upload picture at the same time.
Whenever I click Add picture , It doesn't let the user upload a picture instead I get this error
'PictureForm' object has no attribute 'save'
pet = form.save(commit =False) ...
I could design the page to let the user upload a picture but not display the name at the same time.
I think the problem lays in my profile.html and Profile function at views.py
Parts of my views.py
#login_required
def Profile(request):
Person = request.user.get_profile()
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method == "POST":
form = PictureForm(request.POST ,request.FILE or None)
if form.is_valid():
pet = form.save(commit =False)
pet.save()
context = (
{'Person': Person} ,
{'form':PictureForm()}
)
return render_to_response('profile.html', context, context_instance=RequestContext(request))
Parts of my forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from pet.models import *
class PictureForm(forms.Form):
class Meta:
model = Person
fields = ('image')
My profile.html
{% if Person %}
<ul>
<li>Name : {{Person.name}} </li>
</ul>
{% endif %}
<form method="POST" enctype="multipart/form-data" "action" >
{% csrf_token %}
<ul>
{{ form.as_ul }}
</ul>
<input type = "submit" value= "Add Picture" />
</form>
My models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
image = models.FileField(upload_to="images/",blank=True,null=True)
def __unicode__(self):
return self.name
class Pet(models.Model):
Person = models.ForeignKey(Person)
description = models.CharField(max_length=100)
image = models.FileField(upload_to="images/",blank=True,null=True)
def __unicode__(self):
return self.description

PictureForm needs to inherit from forms.ModelForm, not forms.Form.

Erase your form.save(commit=False). You will only do that if you override your save method
#login_required
def Profile(request):
Person = request.user.get_profile()
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method == "POST":
form = PictureForm(request.POST ,request.FILES)
if form.is_valid():
form.save()
context = (
{'Person': Person} ,
{'form':PictureForm()}
)
return render_to_response('profile.html', context, context_instance=RequestContext(request))
UPDATE:
[.....]
board = Board.objects.get(board=picture.board)//remove this
the_id = board.id //remove this
return HttpResponseRedirect(reverse('world:Boat', kwargs={'animal_id': picture.board.id })) // change the_id into picture.board.id

You have a typo. It should be request.FILES.

no buddy. your problem is in your model.py:
just add this function to your model
def save(self,*args, **kw):
super(PictureForm,self).save(*args, **kw)

Related

Data from django model form not being saved to database

I created a model form with a few fields and would like to save the data when a user enters values into the template and clicks submit.
However when I click 'submit' the values are not cleared from the form, and the data is not getting saved into the sqlite3 database which I checked using select * from notes_note;
I am not getting any error, it simply isn't saving that data.
Models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Note(models.Model):
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
title = models.CharField(max_length=100)
text = models.CharField(max_length=500)
createTime = models.DateTimeField()
from django.forms import ModelForm
class NoteForm(ModelForm):
class Meta:
model = Note
#fields = '__all__'
#fields = ['title', 'text', 'createTime']
exclude = ['owner']
Template
Log Out
<h2>Dashboard {{ user }}</h2>
<table>
<tr>
<td>
<form_name="noteForm" action="/notes/dashboard/" method="post"> {% csrf_token %}
{{ form.as_p }}
<input type= "submit" value="New Note"/>
</form>
</td>
</tr>
</table>
Views.py
#login_required(login_url="/notes/index/")
def dashboard(request):
if request.method == 'POST':
# d dict is a copy of our request.Post because it's immutable and we need to add owner
d = request.POST.copy()
d.update({'owner': request.user.id})
form = NoteForm(d)
if not form.is_valid():
template = loader.get_template('dashboard.html')
context = {
'form': form,
}
return HttpResponse(template.render(context, request=request))
# save the note to the database
# if the form is valid
note = form.save()
note.owner = request.user
note.save()
return redirect("dashboard")
else:
print("this prints out")
template = loader.get_template('dashboard.html')
context = {
'form': NoteForm(),
}
return HttpResponse(template.render(context, request=request))
I checked using a print statement in my dashboard function in views.py to see what is being processed, and it is hitting the else portion.

"parcella_pk" not okay there, it cause a "ValueError". What should I use?

I don't know what type of data should I use there. With primary key I think is there are no problem. But it's not that what I needed.
This is part of my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
class Parcella(models.Model):
###
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.parcellanev
class Muvelet(models.Model):
###
parcella = models.ForeignKey(Parcella, on_delete=models.CASCADE)
This is part of my views.py:
#login_required
def muvelethozzaadas(request, parcella_pk):
if request.method == 'GET':
return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm()})
else:
try:
form = MuveletForm(request.POST)
ujmuvelet = form.save(commit=False)
ujmuvelet.parcella = parcella_pk
ujmuvelet.save()
return redirect('parcellak')
except ValueError:
return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm(), 'error':'Nem megfelelő adat. Kérlek prbáld újra!'})
This is part of my parcellaegy.html:
<form method="POST" action="{% url 'muvelethozzaadas' parcella.id %}">
{% csrf_token %}
<button type="submit">Hozzáadás</button>
</form>
First You have to get object of Parcella using parcella_pk and assign that object to ujmuvelet.parcella as...
parcella_obj = Parcella.objects.get(id=parcella_pk)
ujmuvelet.parcella = parcella_obj
ujmuvelet.save()

Modelforms : not able to view the editable content while updating

Possibly a newbie question, so please bear with me.
I have a Django form that edits a certain instance of a Model. I am using Modelforms. I am able to edit the instance but I am not able to see the content of instance that I want to edit.
I am learning django right now using video tutorials and in the tutorial adding instance=instance to ModelForm instance and then using form.as_p the values were populated in the input box.
In my case when I got to edit url my input fields are blank. However, whatever I write in new blank form gets updated to that object. What could have been wrong here? I am stuck at this point for 4 days so this question is a very desperate one :)
My form class:
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['name','type', 'date', 'description']
My Model:
from django.db import models
class Entry(models.Model):
name = models.CharField(max_length=200)
type = models.CharField(max_length= 200)
date = models.DateTimeField()
description = models.TextField()
My views look like this :
def update(request,pk):
instance = get_object_or_404(Entry,pk=pk)
if request.method == 'POST':
form = EntryForm(request.POST or None,instance=instance )
if form.is_valid():
instance =form.save(commit=False)
instance.save()
return HttpResponseRedirect('/')
else:
form = EntryForm()
return render(request, "form.html", {"name":instance.name,'instance':instance,'form': form})
Form template :
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-success" type='submit'>Submit</button>
</form>
You are not passing the instance for the second case. Update your views.py to this.
def update(request,pk):
instance = get_object_or_404(Entry,pk=pk)
if request.method == 'POST':
form = EntryForm(request.POST or None,instance=instance )
if form.is_valid():
instance =form.save(commit=False)
instance.save()
return HttpResponseRedirect('/')
else:
form = EntryForm(instance=instance)
return render(request, "form.html", {"name":instance.name,'instance':instance,'form': form})

Django modelForm is not saving file to DB

Django 2.0
Python 3.6
I am having trouble with a Django form that is not saving the file that is selected through the form; whenever you select a file to upload, I receive the message "This Field is Required.".
I placed a blank=True and a null=True in the Model FileField to get rid of the same, but whenever I attempt to load the html, I get this error: "The 'copydoc' attirbute has no file associated with it."
I would like for a user to be able to log in, create an entry and upload a file along with said entry. Why doesn't the DB accept the file from the form?
Thank you.
views.py:
from django.shortcuts import render, redirect
from .models import notarizer, CustomUser, notarizerCreateForm
# from .forms import notarizerCreateForm
# Create your views here.
def home(request):
t = 'home.html'
return render(request, t)
def page1(request):
t = 'log1/page1.html'
if request.user.is_authenticated:
logger = notarizer.objects.filter(userziptie=request.user).order_by('-date')
return render(request, t, {'logger': logger})
else:
return redirect(home)
def create_entry(request):
createPath = 'log1/create_entry.html'
if request.method == 'POST':
if request.method == 'FILES':
form = notarizerCreateForm(request.POST, request.FILES)
if form.is_valid():
instance =notarizerCreateForm(
file_field=request.FILES['file']
)
instance.save()
else:
print(form.errors)
else:
form = notarizerCreateForm(request.POST)
if form.is_valid():
form.save()
else:
print(form.errors)
else:
form = notarizerCreateForm()
return render(request, createPath, {'form': form})
create_entry.html:
{% extends "base.html" %}
{% block placeholder1 %}
<div class="form-holder">
<form name="form" enctype="multipart/form-data" method="POST"
action="/create_entry/" >
{% csrf_token %}
{{ form.as_table }}
<input type="submit"/>
</form>
</div>
{% endblock %}
models.py:
from django.db import models
from users.models import CustomUser
from django.forms import ModelForm
# Create your models here.
class notarizer(models.Model):
date = models.DateField(auto_now_add=True)
docName = models.CharField(max_length=25, null=False)
describe = models.TextField(max_length=280)
signee = models.CharField(max_length=25, null=False)
signeeDets = models.TextField(max_length=280)
copydoc = models.FileField(upload_to='users/', blank=True, null=True)
userziptie = models.ForeignKey('users.CustomUser',
on_delete=models.DO_NOTHING, null=True)
def __str__(self):
return "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}".format(
self.pk,
self.date,
self.docName,
self.describe,
self.signee,
self.signeeDets,
self.userziptie
)
class notarizerCreateForm(ModelForm):
class Meta:
model = notarizer
fields = ['docName','describe','signee','signeeDets', 'copydoc']
There are some things that make the view workflow very weird:
you check request.method, first you check if it is a 'POST' which is a good idea, but then you check if it is 'FILES', there is no HTTP method named FILES, there are only GET, POST, PATCH, PUT, OPTIONS, etc.;
you call form.is_valid() which is again what should happen, but then you create a new Form, and only pass it a single parameter; and
in case of a POST you should not return a rendered page, but redirect to a GET page (for example showing the result). The workflow is typically Post-redirect-get, since if the user refreshes their browser, we do not want to make the same post again.
The workflow should look like:
def create_entry(request):
createPath = 'log1/create_entry.html'
if request.method == 'POST': # good, a post (but no FILES check!)
form = notarizerCreateForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
else:
# you probably want to show the errors in that case to the user
print(form.errors)
# redirect to a page, for example the `page1 view
return redirect(page1)
else:
form = notarizerCreateForm()
return render(request, createPath, {'form': form})

ModelForm. Why my form is not filled with data from model?

Why my form is not filled with data from model?
This is my model.py
class People(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
address = models.CharField(max_length=255)
This is my forms.py
from django.forms import ModelForm
class EditForm(ModelForm):
class Meta:
model = People
exclude=('user',)
views.py
def edit_data(request):
user = request.user
people = People.objects.get(user=user)
form = EditForm(request.POST, instance = people)
if request.method == 'POST':
if form.is_valid():
form.save()
else:
print 'Error'
else:
form = EditForm()
return render_to_response('profile.html',{'form':form}, context_instance=RequestContext(request))
profile.html
<form action="/profile/" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
The problem is that you're redefining form in your else clause (to a new instance of your EditForm, which doesn't have the instance variable set). Remove the else (and the line under it) and you should be good to go.