only my Submit button is popping up when i am trying to pass a form.
I even tried just copying the code from the Django website... Still does not work for me.
This is my forms.py
from django import forms
class contactForm(forms.Form):
name = forms.CharField(required=False, max_length=100, help_text='100 max.')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
This is my views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .forms import contactForm
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
print(request.POST)
context = locals()
return render(request, 'contact/contact.html', context)
def index(request):
return render(request, 'contact/contact.html')
This is my contact.html
{% extends "contact/base.html" %}
{% block content %}
<h1>Contact</h1>
<form method='POST' acion=''> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit form'/>
</form>
{% endblock %}
I really do not know what is wrong with this code...please help! Thanks
ps: I am new to python, maybe i need another version?
You have two views rendering the same template. One of them, contact, passes the form to the template. The other, index, does not, so there is nothing called form in the context and the result will be blank.
Related
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
Two Correction :
First : In AppsForm.html
<form action="" method="POST">
Provide a url to your form, where it should submit data
<form action="{% url 'url_name_for_Apps_view' %}" method="POST">
Second : In AppS view
This should be
if request == 'POST':
if request.method == 'POST':
im making a signup page in a django project using the UserCreationForm but when rendering my html i only see the submit button
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm
return(render(request, 'register.html', {form: form}))
{% extends 'base.html' %}
{% block title %}Sign Up{% endblock %}
{% block body %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="button">
<button type="submit">Sign up</button>
</form>
{% endblock %}
You can not use the form as key of the context, you should use 'form'. Furthermore it is not a good idea to pass a reference to the class, you should create an instance of the form in the view, so:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
# use 'form' instead of form ↓ ↓
return render(request, 'register.html', {'form': form})
If you had used a form object, instead of a reference to the class, it would have raised an error that a Form is not hashable. But since you used a reference to the form class, there was no error, and thus this remained undetected.
The problem is within the django views function..Use below code instead..
you should pass it as a string variable {'form' :form}
return render(request, 'register.html', {'form': form})
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.
Code on Github
I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!
mysite/blog/forms.py
from django import forms
from .models import BlogPost
class BlogPostModelForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'slug', 'content']
mysite/blog/views.py
from .forms import BlogPostModelForm
def blog_post_create_view(request):
# create objects
# ? use a form
# request.user -> return something
form = BlogPostModelForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
form.save()
form = BlogPostModelForm()
template_name = 'form.html'
context = {'form': form}
return render(request, template_name, context)
mysite/blog/models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
title = models.TextField()
slug = models.SlugField(unique=True)
content = models.TextField(null=True, blank=True)
mysite/mysite/urls.py
from blog.views import (
blog_post_create_view,
)
urlpatterns = [
..
path('blog-new', blog_post_create_view),
..
]
mysite/templates/form.html
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1>{{ title }}</h1>
{% endif %}
<form method='POST' action='.'> {% csrf_token %}
{{ form.as_p }}
<button type='submit'>Send</button>
</form>
{% endblock %}
You need to point to right url in action attribute of form.
<form action="/blog-new/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
I think it's not necessary in your case but you could also refactor your view to match the docs.
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import SomeForm
def some_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SomeForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = SomeForm()
return render(request, 'template_name.html', {'form': form})
You need to point to right url in action attribute of form.
That was not actually the solution but something that helped me to figure out what was wrong.
It is not necessary to point to /blog-new/ as . for action will point to the same page, but I have tried with /blog-new/ as action URL and I was surprised to see that /blog-new/ page doesn't exist.
The bug was in mysite/mysite/urls.py for missing a /:
path('blog-new', blog_post_create_view),
It is funny (and annoying) how a symbol like / missing from your code will mess up everything and make you spend hours trying to find a solution as simple as that.
Thank you for your time spend to have a look over my code and try to help me!
I am trying to display a simple form (3 fields) on a webpage using Django but no fields are displaying - see code below.
I've gone through the Django doc, MDN doc, most of the StackOverflow posts here, but it's still not working.
I was able to see, using {% debug %}, that there is no object EmailInput on the page.
At this point, I am not sure what is causing this issue. Any help would be very much appreciated.
Thanks
forms.py
from django import forms
class EmailInput(forms.Form):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
views.py
from django.shortcuts import render
from .models import journalEntry
from django.http import HttpResponseRedirect
from django.urls import reverse
from journal.forms import EmailInput
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
return render(request, 'journal_index.html', context = {'post':post,'latest_post':latest_post})
def email_input(request):
if request.method == 'POST':
form = EmailInput(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('journal-index'))
else:
form = EmailInput()
return render(request, 'journal_index.html',{'form':form})
journal_index.html
{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
{% endblock content %}
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='journal-index'),
]
If you want to display it in the index page then you have to send it as a context variable in your index function. And now it will be available in your journal_index.html template file.
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
form = EmailInput()
context = {
'post': post,
'latest_post': latest_post,
'form': form
}
return render(request, 'journal_index.html', context = context)
The code from your email_input function is not called anywhere so there is no way this form could be displayed. Also you have to figure out where do you want to display this form. If you don't want to display it together with the stuff from your index page then you would have to create a new template file, add the form there and add a new url path to display that page.
It is because you are not even calling email_input.
you need to bind it to a url like this
urlpatterns = [
url(r'^$', views.email_input),
]
I am beginner to python Django. And trying build an posting article website with the help of tutorials. I got stuck at UserCreationForm. I have created a form using UserCreationForm, but when I am submitting the form I am not able to neither submit the form nor getting any error message on the page.
My views.py code
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post"> {% csrf_token %}
{{form}}
<input type="submit" value="Register"/>
</form>
{% endblock %}
register_success.html
{% extends "base.hml" %}
{% block content %}
<h2>You have registered!</h2>
<p>Click Here to login again</p>
{% endblock %}
The problem is that you are always creating a blank form.
args['form'] = UserCreationForm()
This means that you do not see any errors for POST requests when the form is invalid.
Instead, you should only create the blank form for GET requests.
from django.shortcuts import render
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'register.html', args)
Note that I have simplified the view by using render instead of the obsolete render_to_response. That means you don't need to handle csrf manually.
You can use Django Generic Views, specifically CreateView, it will make your life a lot easier. You can use it like so:
from django.views.generic import CreateView
class CreateUserView(CreateView):
template_name = 'register.html'
form_class = UserCreationForm
success_url = '/accounts/register_success'
Add this to your urls.py and you are good to go:
from mysite.views import CreateUserView
# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),