I am trying to create a very basic form that allows the user to upload a txt file. the function form.is_valid() always fails and I don't know what to do. This is my code: (very similar to the example in the django documentation):
views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render
class UploadFileForm(forms.Form):
# title = forms.CharField(max_length=50)
file = forms.FileField()
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def home(request):
if request.method == 'POST':
print(1)
form = UploadFileForm(request.POST, request.FILES)
print(form.errors)
print(2)
if form.is_valid():
print(3)
handle_uploaded_file(request.FILES['file'])
return HttpResponse('thanks')
else:
form = UploadFileForm()
return render(request, 'home.html', {'form': form})
home.html
{% extends "base.html" %}
{% block content %}
<div>
<div class="'chooseFile'">
<h3>Choose file to attach</h3>
</div>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.file }}
<button type="submit" class="save btn btn-default" value="Submit"></button>
</form>
</div>
{% endblock %}
url.py
from django.urls import path
from django.contrib import admin
from django.conf.urls import url
from adoptions import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^$', views.home, name='/success/url/'),
]
Related
So the django file is not showing the form and at first, I got angry at that so I just used HTML code to create a form but I realized that when I submit it on the form it does not send it to where I want it to send. I was just wondering if you could help. I think the problem with the file is between the relationship between util.py file and the index.html file but I can't see it for some reason.
Thank you!!
util.py file
class Form(forms.Form):
searched = forms.CharField(max_length=128, help_text="Please enter the category name.")
def get_name(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
searched = form.cleaned_data['searched']
return searched
else:
form = Form
return render(request, "wiki/index.html", {
"form" : form
})
wiki.urls.py - main urls file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('wiki/', include("encyclopedia.wurls"))
]
encyclopedia.urls file
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
views.py file
from django.shortcuts import render
from . import util
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"lookUp": util.get_name(request)
})
def title(request, name):
return render(request, "encyclopedia/titlePage.html", {
"entries": util.list_entries(),
"name": name,
"entry": util.get_entry(name)
})
index.html file
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block formsearch %}
<form action="/wiki/{{lookUp}}" method="post">
{% csrf_token %}
{{ lookUp }}
<input type="submit" value="Submit">
</form>
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li> <a href= "/wiki/{{entry}}" > {{ entry }} </a> </li>
{% endfor %}
</ul>
{% endblock %}
Take away this from util.py:
def get_name(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
searched = form.cleaned_data['searched']
return searched
else:
form = Form
return render(request, "wiki/index.html", {
"form" : form
})
and instead add this to views.py:
def index(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
searched = form.cleaned_data['searched']
return searched
else:
form = Form
return render(request, "wiki/index.html", {
"form" : form
})
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"lookUp": util.get_name(request)
})
I am trying to build a user login/signup page using Django. Everything works fine except when I try to register new users by clicking on the register button, the newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin. Please help.
Here's my code:
urls.py-login
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls'))
]
urls.py-accounts
from django.urls import path
from . import views
urlpatterns = [
path('', views.indexView, name = "home"),
path('dashboard/', views.dashboardView, name = "dashboard"),
# path('login/',),
path('register/',views.registerView, name = "register_url"),
# path('logout,'),
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def indexView(request):
return render(request, 'index.html')
def dashboardView(request):
return render(request, 'dashboard.html')
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login_url')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form':form})
index.html
<!DOCTYPE html>
<html>
<head>
<title>Petrol Pump Management System</title>
</head>
<body>
{% block content %}
<h1>User Authentication</h1>
{% endblock %}
</body>
</html>
register.html
{% extends 'index.html'%}
{% block content %}
<h1>Create new account</h1>
<form method = "POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Register</button>
</form>
{% endblock %}
Login cannot be done in my app.I wrote in views.py
from django.shortcuts import render,redirect
from django.urls import reverse
from app.forms import RegisterForm,LoginForm
from app.models import Data
from app.forms import DataForm
from django.db.models import Q
def index(request):
data = Data.objects.order_by('-created_at')
form = RegisterForm()
loginform = LoginForm()
dataform = DataForm()
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
in index.html
<section id="top">
{% if user and not user.is_anonymous %}
<p>Hello</p>
<h3>{{ user.username }}</h3>
{% else %}
<form action="{% url 'app:index' %}" method="POST">
{{ loginform.non_field_errors }}
{% for field in loginform %}
{{ field }}
{{ field.errors }}
{% endfor %}
<button type="submit">LOGIN</button>
{% csrf_token %}
</form>
{% endif %}
</section>
in forms.py
from django import forms
from django.contrib.auth.forms import (
AuthenticationForm
)
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label
in child's app's urls.py
from django.urls import include, path
from . import views
from django.contrib.auth.views import login
app_name = 'app'
urlpatterns = [
path('index', views.index,name='index'),
]
in parent's app's urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('app.urls') ),
]
When I login from loginform,if statement of {% if user and not user.is_anonymous %} did not become true.But when I login in admin site, the statement become true.When I put LOGIN button, no error happens.I really cannot understand what is wrong.How should I fix this?
Your index view doesn't do anything when a POST request is submitted. It just initialises empty forms and returns them. You need to actually process the data that is submitted, authenticate the user and call the login method:
def index(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid(): # this authenticates the user
user = loginform.get_user()
# redirect to success view or just render index.html
return render(request, 'index.html', {'user': user})
# else not needed, we go to the end and return the form with errors
else: # request method is 'GET'
loginform = LoginForm()
dataform = ...
...
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
I'm new to DJango and I have some doubts about forms. Here is the code, I would appreciate your help :D
This is the error that appears to me:
enter image description here
directories and files:
blog
|--_pycachce_
|--migrations
|--static
|--templates
|--blog
|--base.html
|--forms.py
|--post_bio.html
|--post_detail.html
|--post_edit.html
|--post_list.html
|--models.py
|--tests.py
|--urls.py
|--views.py
|--_init_.py
|--admin-py
templates/post_edit.html code:
{% extends 'blog/base.html' %}
{% block content %}
<h1>New post</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
urls.py code:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
url(r'^post/new/$', views.post_new, name='post_new'),
]
views.py code:
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .models import Post
from .forms import PostForm
from .models import Post
from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts' : posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
It looks as if your forms.py is in your templates/blog directory. It should be in the main blog directory alongside models.py.
I'm receiving no errors and everything seems fine but the fields to my form will not show up.
My form:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=False, max_length=100, help_text='100 characters max')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
My view:
from .forms import ContactForm
def contact(request):
form = ContactForm(request.POST or None)
if form.is_valid():
print(request.POST)
context = {'form': form}
return render(request, 'contact.html', context)
contact.html template:
<form method="POST" action=""> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" class="btn btn-default" />
</form>
base.html template:
{% block content %}
{% endblock content %}
{% include "contact.html" %}
</div>
What am I missing? The template housing the form is not surrounded by any block tags because the template is being {% include[d] %} into my base.html.
Additional details: The form and view are in their own separate 'contact' app, and I haven't configured any urls for the contact app as I planned on simply including the template into base.html
Edit--adding urls config:
main urls.py for the project:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include("projects.urls", namespace='projects')),
]
urls.py for my 'project' app:
urlpatterns = [
url(r'^$', projects_home, name='home'),
url(r'^(?P<slug>[\w-]+)/$', project_detail, name='detail'),
]
As for the 'contact' app, I have not configured any urls--would this be wrong? I thought I'd be able to simply make the views/form(as displayed in original post) for the 'contact' app and bring the form into my templates.