simple django code snippet from file upload - python

sorry for dumb question.
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
what happens really in the background when i bind the request to the Form?

It creates an empty form to be passed to the template upload.html since the previous form in upload.html did not pass the validation. When a form has some error, Validation Error exception is raised, then the form is invalid, or when the view is called and request does not include the method POST therefor you must render it again.

Related

(django)I created a todo app in django but everytime I update the task. It creates a new object

It creates new object everytime I update the task.
I tried alot but it still does mot work correctly .Help me please
Models.py contains only a charfield for title, boolean field for task status(task completed or not completed) , a dattime field with auto_add_now=True and an str function returning title
def index(request):
task = Task.objects.all().order_by('-created_on')
form= TaskForm()
if request.method=='POST':
form= TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect ('/')
return render(request('task/list.html',{'task':task,'form':form})
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
form.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
Try this:
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
f = form.save(commit=False)
f.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
It could be the problem with your primary key if it isn't the AutoField() or is not defined. As you could be changing your primary key in the form.
Another approach is you could check out which fields are changed, then manually change their values in the task instance.
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
if 'some_field_in_task' in form.changed_data:
task.some_field_in_task = form.cleaned_data['some_field_in_task']
task.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
You should post your Models.py here also. The issue seems to come from that, not from the views.py
Your views.py looks pretty good.
I got the same issue in my todo app. In my case the problem was that in my "update.html", i had a slash("/") within form action attribute.
Like:
form method="POST" action="/">
And actually it was redirecing me do my index view(which creates new tasks) and so creating new task.
To solve the problem, just delete this slash and leave it empty.
Check urls.py once
urlpatterns = [
path('updateTask/<str:pk>/', views.updateTask, name="updateTask"),
]

Django show error in form that comes from another function

I am trying to post a ModelForm, but after the is_valid() function, I run another validation coming from another function.
What I want to do is, if the result of the other function is false, the form should raise an error, above the form as in the case "your password cannot be the same".
Since the function runs during the process, I cannot use a clean method in model.
Thanks in advance!
function
def somefunction():
.
.
print ("NOT WORKING")
return False
views.py
def index(request):
form = SomeForm(request.POST)
if request.method == "POST":
if form.is_valid():
if somefunction() == True:
form.save()
return HttpResponseRedirect("/contact/")
else:
form
else:
form
return render(request, "home.html", {'form': form})
You can use add_error method to add error to form manually like this.
form.add_error('<FIELD_NAME>)', 'your password cannot be the same')
But I suggest you to override clean method of form instead.

Why calling method inside views.py after successful submission of forms doesn't clear the form?

Views.py
def form_name_view(request):
form = FormName()
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
return render(request, 'first_app/form_page.html', {'form': form})
When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane:
After reaching index page if I hit refresh then alert appears says:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be
repeated. Do you want to continue?
If i want to get back to the same form page, by calling that same method again like
return form_name_view(request)
The new form is already filled with previous inserted data, with the message on the form
Topic with this Topic name already exists.
The question is what is the reason, calling method results like this?
def form_name_view(request):
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
else:
form = FormName()
return render(request, 'first_app/form_page.html', {'form': form})
use this

Django - difficulty in image upload using forms

I want to upload an image from django forms and process it using OpenCV. Here is the code I've written with the help of Django documentation:
1.forms.py:
class UploadFileForm(forms.Form):
image = forms.ImageField()
2.views.py:
def upload_file(request):
context = {'status':'not working'}
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
context['status'] = 'working'
process(request.FILES['test_01.png'])
return render(request,'create.html',context)
else:
form = UploadFileForm()
return render(request, 'create.html', {'form': form})
Here process() is the function which processes the uploaded image.Running this code gives me MultiValueDictKey Error on the line where I call process()
After searching for the error, referring to this SO answer I changed process(request.FILES['test_01.png']) to process(request.FILES.get('test_01.png')) I get Attribute Error on the same line(which I guess is because I'm not able to retrieve the uploaded image properly)
Where am I going wrong and what is the correct way of doing so?

Do I need extra code for Image Field in Django

I have this in Model
image_name = models.ImageField(upload_to='accounts/')
In my view I have
def account_form(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm() # An unbound form
return render_to_response('account_form.html', {
'form': form,
})
Do I need to do extra coding for saving image or django will do it itself
Also make sure your form enctype is set in the HTML to submit file data:
<form action="..." method="POST" enctype="multipart/form-data">
You need to pass request.FILES to your account form as well.
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
Reference: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
Other than the save() and save_m2m() methods, a ModelForm works exactly the same way as any other forms form. For example, the is_valid() method is used to check for validity, the is_multipart() method is used to determine whether a form requires multipart file upload (and hence whether request.FILES must be passed to the form), etc.

Categories

Resources