Unique=True in Form not throwing any error - django

I'm entering a duplicate value (already saved in another instance of the same model) in my form to test the unique=True attribute. form.is_valid() returns 'False', as expected, but I don't receive any prompt in the template. Shouldn't I get prompted something like "obj with this value already exists"? The page simply reloads... What am I missing?
forms.py
def update_route(request, pk):
instance = Route.objects.get(id=pk)
if request.method == "POST":
form = RouteForm(request.POST)
if form.is_valid():
data = form.cleaned_data
instance.name = data['name']
instance.priority = data['priority']
instance.url = data['url']
return redirect('campaigns:routes_list')
form = RouteForm(instance=instance)
context= {
'form': form,
}
return render(request, "campaigns/route_form.html", context)
models.py
class Route(models.Model):
name = models.CharField(max_length=48)
priority = models.SmallIntegerField(choices=PRIORITY_LEVEL, default=0, unique=True)
url = models.URLField()
Template
<form method="post" action="">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>

Your update_route() view handles the condition in which the submitted form is valid (form.is_valid()), but not the condition in which the form is invalid.
The errors you are looking for are stored in the form object that you created with RouteForm(request.POST). The errors are generated when the is_valid() method is called.
This form object needs to be added to the context dict and rerendered to the user for the errors to surface. But your code currently overwrites that object with form = RouteForm(instance=instance), so the POST data and the related errors disappear.
One solution could be to handle it in the conditional statement:
if form.is_valid():
...
else:
context = {'form': form}
return render(request, "campaigns/route_form.html", context)
Another solution could be to create a conditional statement for GET requests, for example:
elif request.method == 'GET':
form = RouteForm(instance=instance)

Related

Validation for current user

How to realize checking 'name' for current user in forms.py in ValidationError('Same name already added, change name').
views.py
#login_required
def main_page(request):
form = URL_listForm(request.POST)
if request.method == "POST":
if form.is_valid():
name = form.cleaned_data['name']
if URL_list.objects.filter(user=request.user, name=name).exists():
return HttpResponse('Same name already added, change name')
new_post = form.save(commit=False)
new_post.user = request.user
new_post.save()
return HttpResponse("Data added")
return render(request, 'link/main.html', {'form': form})
If you want validate in database
#-------ADDED CODE
data_tmp = """SELECT count(*) from jobtest WHERE link = %s""", (line)
data_tmp = cur.fetchall()
#-------END ADDED CODE
if (data_tmp == 0 ) :
Not exist
add form with name
<input type="text" id="projectName" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
when press post button and action to api you can get value in input field using request.form['Name']
if you want send data from server code to html
return render_template('index.html', data=userinfo)
and render as
{% userinfo %}

Django checkbox do not return nothing

I mading a project and i need to get checkbox values in sequence, but django do not return anything when that checkbox are unchecked.
how can i do that return False instead of nothing?
forms.py
class myFormExemple(forms.Form):
checkbox = forms.BooleanField(required=False)
views.py
def MyViewExemple(request):
if request.method == 'POST':
print(request.POST.getlist('checkbox'))
context = {
'form': myFormExemple
}
return render(request, "cadastro/myHTMLTemplate.html", context)
and myHTMLTemplate.html:
<form method="post" id='form'>
{% csrf_token %}
{{form.checkbox}}
<button type="submit">save</button>
</form>
If the checkbox is not checked, the POST request will indeed not contain the name of that checkbox, that is how the HTML form works.
You can however validate and clean the data with your form, and transform this into a boolean with:
def MyViewExemple(request):
if request.method == 'POST':
form = myFormExemple(request.POST)
if form.is_valid():
print(form.cleaned_data['checkbox'])
context = {
'form': myFormExemple()
}
return render(request, "cadastro/myHTMLTemplate.html", context)
We thus construct a form with request.POST as data source, and then if the form is valid, we can obtain a boolean with form.cleaned_data['checkbox'].
Django's forms are thus not only used to render a form, but also to process data of a form, validate that data, and convert the data to another type.

Django templated does not display inputs to be filled

I need a call a form on an HTML template where the user posts data which saves to model
The code is running without any errors
But the html page display only title and button
No text input fields
I have a form which is to be displayed on a html page so the user can input data and it saves the data into the model.I am not getting any errors while executing th code but the template does not display the form it just shows the title and submit button
def boqmodel1(request):
form = boqform(request.POST)
if form.is_valid():
obj=form.save(commit=False)
obj.save()
context = {'form': form}
return render(request, 'create.html', context)
else:
context = {'error': 'The post has been successfully created.
Please enter boq'}
return render(request, 'create.html', context)
MyTemplate
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create boq"/>
</form>
MY Url
urlpatterns = [
url(r'^create/', views.boqmodel1, name='boqmodel1'),
path('', views.boq, name='boq'),
]
First of all, your first request, without submitting form is GET. When you submit a form you send POST.
The form is not displaying, because your form is not valid in the first place. Your function should look like this:
def boqmodel1(request):
context = {}
if request.method == "GET":
form = boqform()
context["form"] = form
# if you post a form do all the saving
if request.method == "POST":
form = boqform(request.POST)
context = {'form': form}
if form.is_valid():
obj=form.save()
return render(request, 'create.html', context)
else:
context["errors"] = form.errors
return render(request, 'create.html', context)
If method is GET init your form and pass it to your context, so you can display it on frontend.
If method is POST, init your form with your data from frontend (request.POST), check if the form is valid. If it is valid - save it. If it is not valid, return your errors and display them as you wish.

Retaining uploaded file (FileField) when form is not valid

Given a Model with a required field called number and a ClearableFileInput FileField called upload_file:
class ExampleModel(models.Model):
number = models.IntegerField()
upload_file = models.FileField(blank=True, null=True)
In my view, on POST, if the form is_valid then I can populate the clearable part of the FileField when returning to the same page.
def example_view(request):
context = RequestContext(request)
if request.method == 'POST':
form = ExampleForm(request.POST, request.FILES)
if form.is_valid():
form_instance = form.save()
form = ExampleForm(instance=form_instance)
# or alternatively, for just the upload file field
form = ExampleForm(initial={'upload_file': form_instance.upload_file})
else:
form_instance = form.save(commit=False)
form = ExampleForm(initial={'upload_file': form_instance.upload_file})
# unfortunately, this also does not work:
form = ExampleForm(initial={'upload_file': form.fields['upload_file']})
else:
form = ExampleForm()
return render_to_response('enterrecords/example.html', {'form': form}, context)
This is how it looks:
However, if the form is not valid (see first else case), I can not form.save(commit=False) and therefore cannot populate the clearable part of the FileField.
The form.save(commit=False) gives the following error:
ValueError at /en/myapp/example/
The ExampleModel could not be created because the data didn't validate.
Is there a workaround for this problem?
For completeness...
ModelForm
class ExampleForm(forms.ModelForm):
class Meta:
model = ExampleModel
Template
<form enctype="multipart/form-data" method="POST" action="{% url 'eg' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" name="next" value="Next" />Next</button>
</form>
Use the form.clean_xxx with xxx being the field to clean in your form. It is called before the call to is_valid() of your view.
Here's a sample of what I do when I get an Excel file in my form (my UploadedFileHandler class is useless here, it's just to show you the principle).
The idea is that, even if the form is not valid, the Excel file is always saved and thus I keep a trace of what happened:
def clean_excel_file(self):
uploaded_file = self.files.get('excel_file')
if uploaded_file:
try:
nom = UploadedFileHandler.generate_filename(
splitext(basename(uploaded_file.name))[1])
dst = UploadedFileHandler.get_url(nom, 'imports/excel/')
# sauver le fichier
dst_full = UploadedFileHandler.full_filename(dst)
UploadedFileHandler.make_dir(dst_full)
UploadedFileHandler.save(uploaded_file, dst_full)
retour = ExcelFile.objects.create(
# description = nom de fichier sans l'extension :
description=path.splitext(basename(str(uploaded_file)))[0],
fichier_origine=uploaded_file,
excel_file=dst)
retour.save()
return retour
except IOError:
self.errors['excel_file'] = ErrorList([_("Unknown file type")])
return None

ModelForm with ImageFields, not clearing properly if validation error

First the code.
The ModelForm (im1 and im2 are models.ImageField):
class TestForm(forms.ModelForm):
checkme = forms.BooleanField(required=True)
class Meta:
model = UserProfile
fields = ('im1', 'im2')
The view:
def test(request):
profile = request.user.get_profile()
form = TestForm(instance=profile)
if request.method == "POST":
form = TestForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return render(request, 'test.html', {'form':form})
The template:
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
</body>
</html>
The problems:
If im1 contains a valid image, and I check the clear checkbox next to it but don't check checkme and submit, the form comes back with an error saying that checkme is required. Although the form returns with the error, it appears as if im1 has been cleared. In reality it has not because if I reload the form im1 shows back up with its file and clear checkbox.
My question is how can I fix this? Is it something I am doing or is this something to do with django?
Django is acting exactly as it should.
If the request is a POST request, then your form is bound to the data from request.POST and request.FILES. instance=profile is simply telling the form what particular object to save to if all validation passes. Even if your form isn't valid, it's still bound to the data with the cleared image, and that's what you're passing to render().
Firstly, you shouldn't be creating the first bound form if the request method is POST:
def test(request):
profile = request.user.get_profile()
if request.method == "POST":
form = TestForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
else:
form = TestForm(instance=profile)
return render(request, 'test.html', {'form':form})
Secondly, why do you want your user to do the same exact action twice if they did indeed want to delete an image but simply missed another checkbox?
If you really need Django to act this way, I would do one of two things. Either create a bound form from an instance of UserProfile and pass both the non-valid form and the newly created form to the template and use the non-valid form for displaying the errors and the other one for displaying the rest of the form:
def test(request):
profile = request.user.get_profile()
if request.method == "POST":
errors_form = TestForm(request.POST, request.FILES, instance=profile)
if errors_form.is_valid():
errors_form.save()
form = errors_form
else:
form = TestForm(instance=profile)
return render(request, 'test.html', {'form':form, 'errors_form': errors_form})
else:
form = TestForm(instance=profile)
return render(request, 'test.html', {'form':form})
OR I'd do the same thing but save the errors from the non-valid form to the newly created form so you don't end up with renders() all over the place:
def test(request):
profile = request.user.get_profile()
if request.method == "POST":
errors_form = TestForm(request.POST, request.FILES, instance=profile)
if errors_form.is_valid():
errors_form.save()
form = errors_form
else:
form = TestForm(instance=profile)
#this is left up to you to implement, but you'd do something like
#form.errors = errors_form.errors
#and also iterate through every form attribute.errors and assign it to
#errors_form attribute.errors etc...
else:
form = TestForm(instance=profile)
return render(request, 'test.html', {'form':form})
Both aren't very elegant solutions and I'm not positive the second one will even work as expected without some more hacks since I'm not completely familiar with the Django Forms implementation.
I don't see that doing this is worth it. As I stated before, you're just creating more work for your user...