Image upload in Django no error - django

Trying to save images to a specific folder in django. I get no error but the file doesn't show up where its supposed to.
Here is the model:
class FileUploadHandler(models.Model):
title = models.CharField(max_length=100)
file = models.ImageField(upload_to='/wiki/static/')
View:
def image_upload(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
FileUploadHandler(request.FILES['image'])
form.save
return render_to_response('wiki/gallery.html')
else:
form = UploadImageForm()
return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))
Totally stumped since I don't get an error.

don't you need parenthesis at the end of form.save,
i.e. form.save()

FileUploadHandler.objects.create(file=request.FILES['image'])
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.create
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files

Related

Django: form.is_valid() error, but only after "if request.method == 'POST'"?

When I print(formexam) BEFORE the if request.method == 'POST', it shows the appropriately filled out form items (the exam was created earlier, now I'm just updating it to make changes as desired).
However, when I print(formexam) AFTER if request.method == 'POST', it shows the form fields (at least several of them, I didn't look at every single one) to be empty. What makes that happen?
(In my example code below, I am printing the errors instead of the form.)
Also, a very very similar views.py function (changeExam, bottom of this post) works just fine.
Thank you!
views.py
def updateExam(request, pk):
exam = Exam.objects.get(id=pk)
formod = form_od.ODForm(instance=exam.od)
formos = form_os.OSForm(instance=exam.os)
formexam = ExamForm(instance=exam)
print(f'The errors are: {formexam.errors}')
if request.method == 'POST':
formexam = ExamForm(request.POST, instance=exam)
print(f'The errors are: {formexam.errors}')
formod = form_od.ODForm(request.POST, instance=exam.od)
formos = form_os.OSForm(request.POST, instance=exam.os)
if formod.is_valid() and formos.is_valid():
print("these are valid")
if formexam.is_valid():
print("so is this one.")
#save exam
instance = formexam.save(commit=False)
instance.save()
#save OD
instance = formod.save(commit=False)
instance.save()
#save OS
instance = formos.save(commit=False)
instance.save()
else:
print("Exam form not valid.")
#save OD
instance = formod.save(commit=False)
instance.save()
#save OS
instance = formos.save(commit=False)
instance.save()
else:
print("No forms are valid.")
context = {
'formod': formod,
'formos': formos,
'formexam': formexam,
'exam': exam,
}
return render(request, 'accounts/form_exam_update.html', context)
Results of hitting submit button:
The errors are:
The errors are: <ul class="errorlist"><li>doctor<ul class="errorlist">.<li>This field is required.</li></ul></li><li>examtype<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
these are valid
Exam form not valid.
However, this very similar one works:
views.py
def changeExam(request, pk):
exam = Exam.objects.get(id=pk)
form = ExamForm(instance=exam)
if request.method == 'POST':
form = ExamForm(request.POST, instance=exam)
if form.is_valid():
print(form)
form.save()
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
context = {
'form': form,
}
return render(request, 'accounts/form_exam.html', context)def
Figured it out!
On changeExam, the resultant HTML page (form_exam.html) has <form> tags with all of the fields within the <form> tags. Therefore, no error.
On updateExam, it's a larger page (form_exam_update.html) using Django template tags to include things in different sections, and I realized a few of the fields (e.g. doctor, examtype) were outside of the <form> tags.
I updated the HTML code so that all corresponding fields were within the <form> tags, and it now works as desired!

Delete record without accessing it directly

I am creating a data visualisation site in django and using the rest api for my data. Is there any way of deleting a record without accessing its url directly, as in this case it is impossible.
Something like
def employee_delete(request):
instance = Employee.objects.get(social_security=request.POST)
instance.delete()
return render(request, "dashboard.html")
This only works if you have access to the console as I learned, so I tried to access the data from a form like so
def employee_delete(request):
if request.method == "POST":
form = delete_EmployeeForm(request.POST, request.FILES)
if form.is_valid():
instance = Employee.objects.get(social_security=request.POST)
instance.delete()
return render(request, "dashboard.html")
else:
form = delete_EmployeeForm()
return render(request, "deleteemployee.html",{'form': form})
Would this work if I was able to be more specific about which piece of data I was accessing from the form? I got a typeError trying to use request.Post in that manner. That form contained a single field in 'social_security' from the Employee model.
Thanks
def employee_delete(request):
if request.method == "POST":
form = delete_EmployeeForm(request.POST, request.FILES)
if form.is_valid():
instance = Employee.objects.get(social_security=request.POST['social_security'])
instance.delete()
return render(request, "dashboard.html")
else:
form = delete_EmployeeForm()
return render(request, "deleteemployee.html",{'form': form})
use this in your view

Save and retrieve a form with session?

I have a context_processor.py file with the following function
def include_user_create(request):
if 'form' not in request.session:
form = CreateUserForm()
else:
form = request.session['form']
return { 'create_user_form' : form }
I use this to display my register in my base.html template, so that I may reuse it for all pages. A function create_user handles the form submit
def create_user(request):
form = CreateUserForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(username=user.email, password=user.password)
else:
request.session['form'] = form #<--- save
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
If the form is invalid I'd like to save the form so that the context_processor may reuse the form, for the purpose of saving the errors so they may be displayed in the template.
Doing this gives me a error:
TypeError: <CreateUserForm bound=True, valid=False, fields=(email;password;confirm_password)> is not JSON serializable
Is it possible to get this to work somehow?
You have this error because a form object is not JSON serializable, and the default session serializer is serializers.JSONSerializer.
Try to change it to a pickle serializer in your settings.py:
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
EDIT:
With this setting, you don't have to care about pickle serialization, you just have to write:
request.session['form'] = form

File Uploading Using Django

i'm new in django and i have a problem with Uploading File Please Help me!! :X
here is my view.py
def uploadimg(request):
try:
user = request.session['user']
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
#if form.is_valid():
usr_img = User_image(imgfile = request.FILES['imgfile'])
return HttpResponse("yes")
#usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
return HttpResponse("Noooooo!!!")
except:
pass
this is my form.py
class User_image_form(forms.Form):
imgfile = forms.FileField()
and this is my models.py
class User_image(models.Model):
imgfile = models.ImageField(upload_to = 'User-Image')
#user = models.ForeignKey(User_account)
and i have problem in view.py at line which
usr_img = User_image(imgfile = request.FILES['imgfile'])
and it's never get to the
return HttpResponse("Yes")
error:
Exception Value: The view User.views.uploadimg didn't return an HttpResponse object.
Plz Help
If there is an exception, you are not returning an HttpResponse object. Hence the error.
use form.is_valid() to see if the form is valid.
Something like this:
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
if form.is_valid():
usr_img = User_image(imgfile = form.cleaned_data['imgfile'])
usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
print form.errors #for debugging purposes only.
return HttpResponse("Noooooo!!!")

Auto Fill ModelForm with data already stored in database

I got a form as shown below and I want it to be filled with information from the database when its HTML is rendered. I am passing the id of the Coworker as a parameter for the view.
See code below:
view.py
def EditCoworker(request, id):
form = FormEditCoworker(Coworkers.objects.get(id=id))
if request.method == "POST":
form = FormEditCoworker(request.POST)
if form.is_valid():
form.save()
confirmation_message = "Coworker information updated successfully!"
return render(request, "coworkers/coworkers.html", locals())
else:
return render(request, "coworkers/edit_coworker.html", locals())
return render(request, 'coworkers/edit_coworker.html', locals())
forms.py
class FormEditCoworker(ModelForm):
class Meta:
model = Coworkers
urls.py
url(r'^edit_coworker/(?P<id>[\d]+)$', views.EditCoworker),
Of course the code in my views.py is not right.
Can someone help me on this?
Thanks in advance!
This line
form = FormEditCoworker(Coworkers.objects.get(id=id))
Should be
form = FormEditCoworker(instance=Coworkers.objects.get(id=id))
Although you should really handle the case where the Coworker doesn't exist
form = FormEditCoworker(instance=get_object_or_404(Coworkers, id=id))
EDIT: As Alisdair said, you should also pass the instance keyword arg to the bound form also
instance = get_object_or_404(Coworkers, id=id)
form = FormEditCoworker(instance=instance)
if request.method == "POST":
form = FormEditCoworker(request.POST, instance=instance)