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.
Related
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.)
models.py
I write this code for creating a form which has two fileds named Title and Desc
from django.db import models.Here is models.py code.
class Post(models.Model):
title = models.CharField(max_length=200)
desc = models.TextField()
And Here is forms.py Code
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm,UsernameField
from django.contrib.auth.models import User
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','desc']
# label = {'title':'Title','desc':'Description'}
widgets={'title':forms.TextInput(attrs={'class':'form-control'}),
'desc':forms.Textarea(attrs={'class':'form-control'})}
Here is the views.py code
views.py
from django.shortcuts import render,HttpResponseRedirect
from .forms import SignUpForm,LoginForm,PostForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from .models import Post
def add_post(request):
if request.user.is_authenticated:
if request.method == "POST":
form = PostForm(request.method)
if form.is_valid():
title1 = form.cleaned_data['title']
description = form.cleaned_data['desc']
pst = Post(title=title1,desc=description)
pst.save()
form = PostForm()
else:
form = PostForm()
return render(request,'blog_app/addpost.html',{'form':form})
else:
return HttpResponseRedirect('/login/')
Here is the addpost.html
addpost.html
{% extends 'blog_app/base.html' %}
{% load static %}
{% block content %}
<div class="col-sm-10">
<h3 class="text-black my-5 alert alert-success">Add Post</h3>
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Add" class="btn btn-primary">
Cancel
</form>
</div>
{% endblock content %}
But When I click on Add Button I got this errorenter image description here
What is the solution of it
Here is Url.py code
urls.py
from django.contrib import admin
from django.urls import path
from blog_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
path('dashboard/', views.dashboard,name='dashboard'),
path('signup/', views.signup,name='signup'),
path('login/', views.user_login,name='login'),
path('logout/', views.user_logout,name='logout'),
path('add/', views.add_post,name='addpost'),
path('update/<int:id>/', views.update_post,name='updatepost'),
path('delete/<int:id>/', views.delete_post,name='deletepost'),
]
And This is the error Shows in my terminal
terminal img
This line in your view
form = PostForm(request.method)
should be
form = PostForm(request.POST)
When i'm submitting a jpg image then it refreshes and shows 'This field required'validation error,so in views i tried to print(request.POST),it shows csrfmiddlewaretoken and pic in console but field validation is getting violated. Please correct me.
models.py
from django.db import models
class picture(models.Model):
pic = models.ImageField(upload_to='documents/')
forms.py
from django import forms
from .models import picture
class pictureForm(forms.ModelForm):
class Meta:
model = picture
fields = ['pic',]
views.py
from django.shortcuts import render,redirect
from .models import picture
from .forms import pictureForm
# Create your views here.
def pictureView(request):
if request.method == 'POST':
print(request.POST)
form = pictureForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = pictureForm()
return render(request,'home.html',{'form':form})
urls.py(APP level urls)
from django.urls import path
from . import views
urlpatterns = [
path('',views.pictureView, name = 'home')
]
urls.py(Directory level urls)
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Media files
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
template
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
based on the doc: uploaded-files-with-a-model
you should initialize your form:
form = pictureForm(request.POST, request.FILES)
and in the template you need add enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
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})
Goal/tl;dr I want to call my added method from views.py when you submit the forum and use the stuff from the textfield to make a new post object.
I am new to django, and I have looked through other stack posts, but most of these errors seem to be for cookies or users. I have also looked at the python documentation as most people have suggested, but I haven't seen all the pieces together and I am not sure how to get the textfield from the forum. Correct code and/or and explanation of what I am doing wrong and how to do it would be much appreciated.
models.py
from django.db import models
class Post(models.Model):
text = models.TextField(max_length=250)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
views.py
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect
from blog.models import Post
from django.core.context_processors import csrf
def home(request):
try:
p = Post.objects.all()
except Post.DoesNotExist:
raise Http404
return render_to_response('index.html',
{'post':p})
def post(request, uID):
try:
p = Post.objects.get(pk=uID)
except:
raise Http404
return render_to_response('post.html',
{'post':p})
def delete(request, uID):
try:
p = Post.objects.get(pk=uID).delete()
except:
raise Http404
return render_to_response('delete.html',
{'post':p})
def new(request):
context = {}
context.update(csrf(request))
return render_to_response('new.html', context)
def added(request):
if request.method == 'POST':
context = {}
context.update(csrf(request))
p = Post.objects.create(text=request.text)
p.save()
return render_to_response("index.html", context)
else:
raise Http404
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'blog.views.home', name='home'),
url(r'^(?P<uID>\d+)/$', 'blog.views.post', name='Post Id'),
url(r'^(?P<uID>\d+)/delete/$', 'blog.views.delete', name='del'),
url(r'^new/$', 'blog.views.new'),
url(r'^created/$', 'blog.views.added'),
# url(r'^myApp/', include('myApp.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
new.html
<html>
<body>
<h2> Create a new Post </h2>
<form method="post" action="/created/">
{% csrf_token %}
Body: <input type="textarea" name="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
You mean request.POST['text'].
You should probably investigate the forms framework though.