Django UserCreationForm not responding when button clicked with input in fields - python

I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens.
views.py:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register(response):
form = UserCreationForm()
return render(response, "register/register.html", {"form":form})
register.html:
{% extends "main/base.html" %}
{% block title %}Create an Account{% endblock %}
{% block content %}
<form method="POST" class="form-group">
{{form}}
<button type="submit" class="btn btn-success">Register</button>
</form>
{% endblock %}
urls.py:
from django.contrib import admin
from django.urls import path, include
from register import views as v
urlpatterns = [
path('', include("main.urls")),
path("register/", v.register, name="register"),
path('admin/', admin.site.urls),
]
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("<int:id>", views.index, name='index'),
path("", views.home, name='home'),
path("create/", views.create, name='create'),
]
I added the application to my settings.py file as well.
This is my first question on here and I tried to format it properly so sorry if I didn't

In order for Django to recieve the data the user entered in the form, you need to pass the request's POST data to the form, if it exists. That would look like this:
form = UserCreationForm(response.POST)
But note that response.POST will not exist if it's not a POST request. (For example, if the user is viewing the form for the first time.) The Django docs have an example of how to process form data.
Alternatively, you can look at the tutorial you're using, which has an example of how to get the POST data out of the form:
# views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
return render(response, "register/register.html", {"form":form})
(Source.)

Related

Django Forms not working. Does not display anything. Any helps?

I was doing some How-To tutorials about Django Forms.
But it will not display anything for me. Any ideas why? Picture below illustrates my problem.
This is my Login -> index.html
<body>
<div class="gradient-border" id="box">
<h2>Log In</h2>
<form action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</div>
</body>
this is forms.py
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
password = forms.CharField(widget = forms.PasswordInput())
this is views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
def index(request):
return render(request, 'login/index.html')
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "index.html", context)
def main(request):
return render(request, 'login/main.html')
this is urls.py
from django.contrib import admin
from django.urls import path, include
from login.views import index, main
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', index),
path('main/', main),
path('accounts/', include('django.contrib.auth.urls')),
]
Login Page
You are not passing the form context for the login route. In your index function, you don't have any context, and you put the form in home_view function which is not the view function being called by the /login route.

Django UserCreationForm on homepage

I'm trying to create a usercreationform on the homepage of my website. After reading and watching tutorials on user creation I noticed everyone creates a separate HTML page for "signup", however, I want my signup page to be directly on my homepage - is this a possibility? I'm finding it difficult to understand with 'accounts' having its own separate app, as well as the homepage having its own app, which I have called mine 'game'. Do both apps have to be separate? Am I able to make the accounts app my main 'homepage' app?
Can anyone recommend any tutorials on this? I think I should also mention I'm quite new to django. Thank you.
My homepage app (titled game)
urls.py:
from django.contrib import admin
from django.urls import path
from.import views
urlpatterns = [
path('', views.game_start),
]
views.py:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .models import Game
def game_start(request):
games = Game.objects.all().order_by('date') # grabs all records in game in db table, order by date
return render (request, 'game/game_start.html', {'games':games})
def signup_view(request):
form = UserCreationForm()
return render(request, 'game/game_start.html', {'form': form})
accounts/urls.py:
from django.conf.urls import url
from .import views
app_name = 'accounts'
urlpatterns = [
path('', game_views.game_start, name="home"),
]
accounts/views.py:
from django.http import HttpResponse
from django.shortcuts import render
def about(request):
# return HttpResponse('Price is right game one')
return render(request, 'about.html')
I want my signup page to be directly on my homepage - is this a possibility?
Yes it's a possibility that you can define a custom signup function in your accounts app and then import that inside of your homepage app like this:
accounts/views.py:
def signup(request):
data = {'form':None, 'user_created': False}
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
# do soemthing with the registered user
data['user_created'] = True
else:
form = UserCreationForm()
data['form'] = form
return data
homepage/views.py:
from accounts.views import signup
def game_start(request):
games = Game.objects.all().order_by('date')
data = {'msg': ''}
response = signup(request)
if response['user_created']:
# you can redirect user here to somewhere else when they have been registered.
data['msg'] = 'Thanks for being the part of our beautiful community!'
return render(request, 'game/game_start.html', {
'games':games,
'form': response['form'],
'msg': data['msg']
})
game_start.html:
<p>{{msg}}</p>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Sign Up</button>
</form>
Do both apps have to be separate?
Well, you can have both of them under one app but that is not recommended because of the following reasons:
You won't take advantage of App Reusability.
All of your code would look messy.
Debugging would be hard.
If you are having difficult understanding what apps in django are, then you can simply take a look at my answer here
You could include the form in your "game_start.html" template:
{% if not user.is_authenticated %}
<form role="form"
action="{% url 'player_login' %}"
method="post">
{% csrf_token %}
<p>Please login.</p>
{{ form.as_p }}
<button type="submit">Sign in</button>
</form>
{% endif %}
This assumes you have a named url pattern player_login.

Django: forms not visible on the webpage

I am trying to create a simple Django webpage that uses forms, but my forms are not visible. I have read all of the Django docs and read multiple questions related to this issue, but I have found no solution that fixes my problem.
Here are the relevant files:
views.py
from django.shortcuts import render
from .forms import FileForm
with open('calendar.txt') as f:
file_content = f.read()
def home(request):
return render(request, 'main/index.html',{'file_content':file_content})
def form_get(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 = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'index.html', {'form': FileForm.form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from main import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
]
index.py
{% extends "base.html" %}
{% block content %}
<h1>Welcome to the calendar!</h1>
<form action="/#" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{{form}}
{% endblock content %}
Link to program
From what I have read, I suspect there may be an issue in the urls.py file, but I've been looking over it many times and I haven't found anything wrong. Any thoughts?
Try
def form_get(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 = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'main/index.html', {'form': form})
See how I changed the context for the render from {'form': FileForm.form} to {'form': form}. The path to the index.html file was also wrong.
After fixing the view, you need to add an actual URL to go to it. Your current URL has
url(r'^$', views.index, name='home'),
Note how is using views.index and not views.form_get. Change the URL to use form_get and it will work.
url(r'^$', views.form_get, name='home'),
Don't know if you want to have / go to the form, or if you would rather have / still go to home, where you have a link to the form. But in that case, you do not want to share the same index.html file.
But seems like you may be trying to merge those two, but in that case, you need a single view, which can both show the content of the file, and ask for the file. But will be easier if you have two views, and leave the form to just take the input, and then redirect to the second view to show the results.

TemplateDoesNotExist at /test2/ the app is in python and django

views.py
name.html cannot be found
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'name.html',{'from':form})
name.html:why python is not able to find my template? my template dir structure is test2/templates/test2/name.html
<form action="/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class Get_name(forms.Form):
user_name = forms.CharField(label='username',max_length='50')
test2/urls.py
from django.conf.urls import url
from .import views
urlpatterns=[
url(r'^$',views.index,name='index'),
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
I think this will solve the problem.
Modify your views such that.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'test2/name.html',{'from':form})
prepend template name with test2 such that return render(request,'test2/name.html',{'from':form})

Logout Page not working in Django

I'm trying to create a logout page for django.
This is the views.py file:
def index(request):
if not request.user.is_authenticated():
return redirect('webapp/login.html')
else:
result = Hello_World.delay()
somethingDownByCelery = result.get(timeout=2)
context = {'somethingDownByCelery': somethingDownByCelery, 'userName': request.user.username}
return render(request, 'webapp/index.html', context)
def loginUser(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('webapp/index.html')
else:
return redirect('webapp/disabled.html')
else:
condition = "Invalid Login"
context = {'condition', condition}
return render(request, 'webapp/index.html', context)
def logoutUser(request):
logout(request)
return redirect('webapp/index.html')
This is the index page after the logout is initiated.
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/style.css' %}"/>
Hello World, this will call celery!
<html>
<br>
</html>
{{ somethingDownByCelery }}
<html>
<br>
<br>
</html>
Hello! {{ userName }}
<html>
<br>
<br>
</html>
<form action="{% url 'WebApp:logout'%}" method="post">
{% csrf_token %}
<p> Logout </p>
<input type="submit" value="Submit">
</form>
What should happen is that the user would logout, and get redirected to the index page, whereas since the user is not logged in, it will redirect the user to a login page.
However, it only shows me: The view django.contrib.auth.logout didn't return an HttpResponse object.
This is the project root urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
from StripCal import views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Dashboard_Web.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('WebApp.urls', namespace="WebApp")),
)
This is the app's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.login, name='login'),
url(r'^logout', views.logout, name='logout'),
)
try this:
from django.shortcuts import HttpResponseRedirect
def logoutUser(request):
logout(request)
return HttpResponseRedirect('/loginpage/')
instead of webapp/index.html, you should give the URL of your login page like /loginpage/ inside HttpResponseRedirect
Instead of writing your own, use Djangos builtin logout view for this.
#urls.py
from django.contrib.auth.views import logout
url(r'^sign-out/$', logout, {'template_name': 'index.html', 'next_page': '/'}, name='sign-out'),
Docs are found here and now you can link to this without the use of a form and Django will take care of doing the redirection for you.
I know that this is a old post, but no answer addressed what went wrong in the code so here it is.
In the webapp urls.py file view must be pointing to logoutUser view and not logout view.
and similarly with the login view
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.loginUser, name='login'),
url(r'^logout', views.logoutUser, name='logout'),
)
Now the url function is taking the intended view method as an argument
First things first.
Your function should look similar to this one:
def logout_view(request):
logout(request)
return redirect('/login')
To use logout, you have to import logout like this:
from django.contrib.auth import logout
If you are redirecting user on the basis of User.is_authenticated, it would never redirect because if the user is not logged in, an anonymous user it created.
You can do something like ths:
def home(request):
if request.user.is_anonymous == True:
return redirect('/login')
else:
return render(request,"index.html",{'nav':request.user})

Categories