Django Form Errors not showing - python

I have a form validator and when it fails, the error message doesn't show. Any idea what I'm missing?
views.py:
def setup_onesheet(request):
# if the form has been submitted
if request.method == 'POST':
if 'unverified_username' in request.POST:
form = OnesheetURL(request.POST)
if form.is_valid():
...
form = OnesheetURL()
variables = RequestContext(request, {
'error_message': error_message,
'form' : form,
});
return render_to_response('onesheet_setup/setup_new_onesheet.html', variables)
forms.py:
class OnesheetURL(forms.Form):
unverified_username = forms.CharField(label='http://onesheet.com/', max_length=75, validators=[validate_slug])
template:
<form method="post" action="/setup/new/" id="verify-identity" class="full">
{% csrf_token %}
<ul>
<li>
{{ form.unverified_username.errors }}
{{ form.unverified_username.label_tag }}
{{ form.unverified_username }}
<p>Onesheet URL can only contain letters, numbers, underscores ( _ ) or hyphens ( - ).</p>
</li>
</ul>
<input type="submit">
</form>

Try:
def setup_onesheet(request):
# if the form has been submitted
if request.method == 'POST':
if 'unverified_username' in request.POST:
form = OnesheetURL(request.POST)
if form.is_valid():
...
else:
form = OnesheetURL()
variables = RequestContext(request, {
'error_message': error_message,
'form' : form,
});
return render_to_response('onesheet_setup/setup_new_onesheet.html', variables)

Related

multiple form handling Django python 3.x

i wanted to make simple page with two input forms
first one for posting data into file
second for taking index and deleting data from file
and both of them working independent
but so far i can only use first form like the second one its not even reached not a single method from second form is completed
here goes the code:
###############
#Views.py
class HomeView(TemplateView):
template_name = 'index/num.html'
def get(self, request):
form = AddForm()
form2 = DeleteForm()
result = printResult()
return render(request, self.template_name, {'form': form, 'form2': form2,'result': result})
def post(self, request):
result = "result"
####____add option###################
if request.method == 'POST':
form = AddForm(request.POST)
form2 = DeleteForm(request.POST)
if form.is_valid():
text = form.cleaned_data['post']
if (re.match("[0-9]+", str(text))):
text = text
else:
text= None
result = addToFile(text)
args = {'form': form, 'form2': form2, 'text': text, 'result': result }
return render(request, self.template_name, args)
##########
###____Delete option#######
if form2.is_valid():
index = form2.cleaned_data['dell']
result = DeleteIndexFromFile(index)
args2 = {'form': form, 'form2': form2, 'text': index, 'result': result }
return render(request, self.template_name, args2)
##########
#forms.py
from django import forms
class AddForm(forms.Form):
post = forms.CharField(required = False)
class DeleteForm(forms.Form):
delete = forms.IntegerField(required = False)
#num.html
<div class="container">
<p>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
<form method="delete" >
{% csrf_token %}
{{ form2 }}
<button type="submit">Delete</button>
</form>
</p>
<p>
<h4>Data: {{ text }}</h4>
<h4>{{ result }}</h4>
</p>
</div>
there's a package called django-shapeshifter for doing this:
https://github.com/kennethlove/django-shapeshifter
In the interest of full disclosure, I am a contributor to the project.

Dajngo: refreshing page resubmit last form

I have a view like:
def some_view(request, page_url):
form = UserTicketForm(request.POST)
if request.method == 'POST':
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
data = dict(
form=UserTicketForm,
)
return render(request, 'front/some_page.html', data)
and in HTML page it has:
{% csrf_token %}
{% bootstrap_form form %}
{% block submit %}
<div class="button_holder">
<button type="submit" name="register-submit" class="btn btn-primary" value="send">
submit
</button>
</div>
{% endblock %}
each time I refresh the page, it resubmits the last submitted form. how can fix this issue?
You need to redirect to a different url after the form is submitted and saved
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
return HttpResponseRedirect(reverse('some_url'))
Write Like this
def some_view(request, page_url):
if request.method == 'POST':
form = UserTicketForm(request.POST)
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
data = dict(
form=UserTicketForm,
)
return render(request, 'front/some_page.html', data)

Django ModelForm error message not showing in template

I have created some custom error message following the documentation (as best as I can find) but I'm not getting any errors, let alone my custom errors. Here's my code:
forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = Job
fields = ['jobID','original_file']
labels = {
'jobID': _('Job ID'),
'original_file': _('File'),
}
error_messages = {
'jobID': {
'max_length': _("Job ID is limited to 50 characters."),
'required': _("Please provide a Job ID."),
'invalid': _("Job ID must be a combination of letters, numbers, - and _.")
},
'original_file': {
'required': _("Please provide a file."),
'validators': _("Please ensure you are selecting a zipped (.zip) GDB."),
},
}
help_texts = {
'original_file': _('Please provide a zipped (.zip) GDB.'),
}
upload.html
<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data" name="uploadForm">
{% csrf_token %}
{% for field in form %}
<div>
<strong>{{ field.errors }}</strong>
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class ="help-text">{{ field.help_text }}</p>
{% endif %}
</div>
{% endfor %}
<br />
<button type="button" id="uploadButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off" style="margin: auto 20%; ">Upload</button>
</form>
views.py
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES, user = request.user)
if form.is_valid():
form.save()
request.session['jobID'] = request.POST['jobID']
#job = Job.objects.filter(user_id = request.user.id).filter(jobID = request.POST['jobID']).latest()
# initialize(job)
return render(request,'precheck/run_precheck.html')
form = UploadFileForm()
historyList = Job.objects.filter(user_id = request.user.id)[:10]
return render(request, 'precheck/upload.html',{'form': form, 'history': historyList})
I've included everything I think is relevant, let me know if you need anything more.
The problem is that if the form is not valid, you're resetting the form to the initial form:
form = UploadFileForm()
historyList = Job.objects.filter(user_id = request.user.id)[:10]
return render(request, 'precheck/upload.html',{'form': form, 'history': historyList})
Your flow should render the bound form (with its errors) so it should be:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES, user = request.user)
if form.is_valid():
# do stuff for valid form
return redirect
elif request.method == 'GET':
form = UploadFileForm()
# flow common for GET and invalid form
return render(request, template, {'form': form})

django form not rendering in template. Input fields doesn't shows up

I'm not able to see the django form in my template. it is not being rendered properly. I've tried working on this, but the form not shows up. Tried the same code in a new project to test-that worked fine but here it doesn't work. This {{ form.as_p }} not shows up anything i.e. no input fields for me to enter the details and check the other part. Thanks in advance.
# forms.py
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
contact_subject = forms.CharField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea
)`
and:
# views.py
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get(
'contact_name'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
contact_subject = request.POST.get(
'contact_subject'
, '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = Context({
'contact_name': contact_name,
'contact_email': contact_email,
'contact_subject' : contact_subject,
'form_content': form_content,
})
content = template.render(context)
email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['youremail#gmail.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return redirect('contact')
return render(request, 'contact.html', {
'form': form_class,
})
The template for the same looks like this.
template
<section id="contact">
<div class="container text-center">
<div class="row text-center">
<div class="bg-image">
<div class="col-md-6 col-md-offset-3 text-center share-text wow animated zoomInDown heading-text">
<p class="heading">
If you got any questions, please do not hesitate to send us a message.
</p>
</div>
</div>
</div>
{% block content %}
<h1>Contact</h1>
<form role="form" action="" method="post">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
</div>
</section>
Add an else clause for generating a form on GET:
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
# ... more code from above ...
else:
form = form_class() # this is important
return render(request, 'contact.html', {
'form': form, # NOTE: instead of form_class!!!!
})
You are passing the form class to your template instead of a form instance.
You haven't handled the case when request.method is not POST.
Your view should look like this:
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form handling logic here
# ...
# ...
return redirect('some-link')
else:
return render(request, 'template.html', dict(form=form))
else:
form = ContactForm()
return render(request, 'template.html', dict(form=form))

trouble with subscribing form (Django)

Please, help.. I do not udersatand what I should do this code to work..
home.html:
<form class="subscribe-form" action="{% url 'subscribe' %}" method="POST">{% csrf_token %}
{{ form }}
<button class="btn btn-main btn-lg" type="submit">Подписаться!</button>
</form>
{% if success %}
<div class="subscribe-result">
{{ success }}
</div>
{% endif %}
urls.py:
url(r'^$', 'interior_app.views.home', name='home'),
url(r'^subscribe/$', 'interior_app.views.subscribe', name='subscribe')
models.py:
class Subscriber(models.Model):
email = models.EmailField('', max_length=100, null=True, blank=True)
forms.py:
class SubscriberForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ['email']
admin.py:
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email',)
admin.site.register(Subscriber, SubscriberAdmin)
views.py:
def home(request):
portfolios = PortfolioObject.objects.all()
photos = []
for portfolio in portfolios:
for obj in portfolio.photo_set.all():
photos.append(obj)
form = SubscriberForm()
context = {"photos": photos[::2], "form": form}
return render(request, "home.html", context)
def subscribe(request):
print request
success = ''
if request.method == "POST":
print request.POST
form = SubscriberForm(request.POST)
print form
if form.is_valid():
form.save()
success = "Ваш Email успешно отправлен"
form = SubscriberForm()
else:
form = SubscriberForm()
context = {"photos": photos[::2], "form": form, "success": success}
return render(request, "home.html", context)
I input email in the form, push button and nothing is happening.
Any data in admin, any {{ success }}.
I need not AJAX.. I would like to do this feature only with Django

Categories