i've got register form
forms
class RegisterForm(UserCreationForm):
name = forms.CharField(max_length=255, label='Username', widget=forms.TextInput(attrs={'class': 'form-group'}))
email = forms.EmailField(max_length=255, label='Email', widget=forms.EmailInput(attrs={'class': 'form-group'}))
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-group'}))
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput(attrs={'class': 'form-group'}))
class Meta:
model = User
fields = ('name', 'email', 'password1', 'password2')
views
class RegisterFormView(FormView):
form_class = UserCreationForm
success_url = '/login/'
template_name = 'blog/signup.html'
def form_valid(self, form):
form.save()
return super(RegisterFormView, self).form_valid(form)
def form_invalid(self, form):
return super(RegisterFormView, self).form_invalid(form)
html
<form method="POST" class="register-form" id="register-form" action="">
{% csrf_token %}
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
<div class="form-group form-button">
<input type="submit" name="signup" id="signup" class="form-submit"
value="Register"/>
</div>
</form>
i tried {{form.as_p}} and for field . in both cases email field doesn't shows and labels too. register is working
Okay, so I think I have achieved what you were asking. First of all, actually, it is no need to override the fields in RegisterForm which is located in your forms.py file. And you can simply write it like that (User is a class that is defined by Django a class that we actually use for creating a superuser) :
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms import fields
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username"
, "email"
, "password1"
, "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
In views.py as you have written:
from django.shortcuts import render
from django.views.generic import FormView
from .forms import *
from django.urls import reverse_lazy
class RegisterFormView(FormView):
form_class = NewUserForm
success_url = reverse_lazy('boldRichard:login')
template_name = "register.html"
def form_valid(self, form):
form.save()
return super(RegisterFormView, self).form_valid(form)
def form_invalid(self, form):
return super(RegisterFormView, self).form_invalid(form)
class LoginFormView(FormView):
pass
And finally in register.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
</head>
<body>
<form method="POST" class="register-form" id="register-form" action="">
{% csrf_token %}
{{form.as_p}}
<div class="form-group form-button">
<input type="submit" name="signup" id="signup" class="form-submit" value="Register" />
</div>
</form>
</body>
</html>
Please feel free to comment if more help is needed.
Related
My Form action is not redirecting to the passed view. I am calling simple_upload view method from login_form.html form action. Instead, upon clicking the login button, it stays on the same page. Below is my code:
urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from uploads.core import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', views.login_form, name='login_form'),
url(r'^upload/', views.simple_upload, name='simple_upload'),
url(r'^drop_down/$', views.drop_down, name='drop_down'),
url(r'^visualize_view/$', views.visualize_view, name='visualize_view'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT)
login_form.html:
{% block content %}
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button>
<div id="id01" class="modal">
<form class="modal-content animate" action="{% url 'simple_upload' %}" method="get">
{% csrf_token %}
<div class="imgcontainer">
<span class="close" title="Close Modal">×</span>
<img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
{% endblock %}
views.py:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .models import Document
from .forms import ExpenseForm
def login_form(request):
return render(request, 'core/login_form.html')
def simple_upload(request):
return HttpResponse("Hello World")
Project hierarchy:
Your home URL pattern is not terminated, so it matches every path. It should be:
url(r'^$', views.login_form, name='login_form'),
It's not good form logic. Forms have valid and invalid actions. If your form is valid you redirect to new (success) page your user, but if not you render same (login) page. But firstly you should give a name your login page like below or use Django's inherit auth urls:
url(r'^login', views.login_form, name='login_form'),
It's my url paths:
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = "user"
urlpatterns = [
path('sign_up/', views.sign_up, name="sign_up"),
path('account_activation_sent/', views.account_activation_sent, name='account_activation_sent'),
path('activate/<uidb64>/<token>/', views.activate, name="activate"),
path('login/', views.login_user, name="login"),
path('logout/', views.logout_user, name="logout"),
path('password_reset/', views.password_reset, name="password_reset"),
path('password_reset/done/', views.password_reset_done, name="password_reset_done"),
path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name="password_reset_confirm"),
path('password_reset/complete/', views.password_reset_complete, name="password_reset_complete"),
path('profile/<slug:slug>/', views.profile, name="profile"),
]
I wanna show you my simple login function and you will understand:
def login_user(request):
if request.user.is_authenticated:
return redirect("index")
else:
form = LoginForm(request.POST or None)
context = {
"form": form
}
go_to = request.POST.get('next', '/')
print(go_to)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if user is None:
messages.error(request, "Username or password is incorrect! Try again.")
return render(request, "auths/login.html", context)
messages.success(request, "Login successful! Welcome bro.")
login(request, user)
go_to = request.POST.get('next', '/')
if go_to:
go_to = request.POST.get(
'next')
return redirect(go_to)
else:
return redirect("index")
return render(request, "auths/login.html", context)
I use Django's form and It's easy but you can use your custom form in your template. My form is like this:
class LoginForm(forms.Form):
username = forms.CharField(label="Username")
password = forms.CharField(label="Password", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].label = ''
self.fields['password'].label = ''
class Meta:
model = User
fields = ('username', 'password' )
I hope It will help you.
Working on a problem in Flask/ Python. Had a few of these errors pop up and I've been able to squash them as they arise; however, this one I cannot seem to get to the bottom of.
I have a simple form which allows users to login.
But each time I load the page I am greeted with this error:
jinja2.exceptions.UndefinedError: 'shop.forms.LoginForm object' has no attribute 'submit'
Below is the code that I am working with, thanks in advance.
p.s. I have seen similar posts regarding the hidden_tag() attribute, but the fixes suggested are not working for this scenario.
routes.py
import os
from flask import render_template, url_for, request, redirect, flash
from shop import app, db
from shop.models import Author, Book, User
from shop.forms import RegistrationForm, LoginForm
from flask_login import login_user, current_user, logout_user, login_required
#app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST':
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user)
return redirect(url_for('home'))
return render_template('login.html', title='Login', form=form)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
sumbit = SubmitField('Login')
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
{% extends "layout.html" %}
{% block content %}
<form method="POST" action="">
{{ form.csrf_token }}
<div class="">
{{ form.email.label }} {{ form.email}}
</div>
<div class="">
{{ form.password.label }} {{ form.password}}
</div>
<div class="">
{{ form.submit() }}
</div>
</form>
{% endblock content %}
</body>
</html>
EDIT: Removing the () from submit doesn't solve the issue. Just removes the instance of the button entirely from the template. See below:
Change form.submit() to form.submit and it will show the submit button in template.
Here is an example of using flask_wtf for a login form.
Example of using Flask wtform:
app.py:
from flask import render_template, url_for, request, redirect, flash, Flask
from forms import LoginForm
app = Flask(__name__)
app.secret_key = 'secret key'
#app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST':
user_email = form.email.data
user_password = form.password.data
if user_email and user_password:
return "{} - {}".format(user_email, user_password)
return render_template('login.html', title='Login', form=form)
if __name__ == '__main__':
app.run(debug=True)
forms.py:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="">
{{ form.csrf_token }}
<div class="">
{{ form.email.label }} {{ form.email }}
</div>
<div class="">
{{ form.password.label }} {{ form.password }}
</div>
<div class="">
{{ form.submit }}
</div>
</form>
</body>
</html>
Output:
Get request of login route:
Post request of login route:
Updates:
requirements.txt:
Click==7.0
Flask==1.0.2
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.1
Werkzeug==0.15.0
WTForms==2.2.1
I successfully run this code both in my machine and in c9.io.
Get request for /login route (before submitting the form):
After submitting the form:
Issue solved!
I didn't spell submit correctly in forms.py
Simple clerical error that cost me 2 hours.
I am having trouble uploading the image in Django Form.
The following form fails to validate due to some issue in the image uploading
Here is the code :
forms.py
from django import forms
from .models import Description, Bill
class DForm(forms.ModelForm):
class Meta:
model = Description
fields = ('desc', 'billing', 'length', 'quality', 'rate')
class BForm(forms.ModelForm):
party = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Party'}))
inovice = forms.FloatField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Invoice#'}))
amount = forms.FloatField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Bill-Amount'}))
image = forms.ImageField()
image_caption = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Description for bill'}))
class Meta:
model = Bill
fields = ('party', 'inovice', 'amount','image','image_caption')
models.py
from __future__ import unicode_literals
#from django.utils.encoding import python_2_unicode_compatible
from django.db import models
##python_2_unicode_compatible
class Description(models.Model):
desc = models.CharField(max_length = 200,default = "Suits")
billing = models.FloatField(max_length = 200)
length = models.FloatField(max_length = 200)
quality = models.CharField( max_length=200,default = "custom")
rate = models.FloatField(max_length = 200)
def __str__(self):
return self.desc
class Bill(models.Model):
party = models.CharField(max_length = 200)
inovice = models.FloatField(max_length = 200)
amount = models.FloatField(max_length = 200)
image = models.ImageField(upload_to='images/products/main',null=True, blank=True)
image_caption = models.CharField(max_length=200,default = "null")
def __str__(self):
return self.party+','+str(self.inovice)+','+str(self.amount)
def bill_id(self):
return self.id;
index.html
{% load staticfiles %}
<!-- test -->
<html>
<head>
<title></title>
<link href="{%static "./styles/bootstrap.min.css" %}" rel="stylesheet" />
</head>
<body>
<h1 style="text-align: center;">Rahul's Shop</h1>
<h2 style="text-align: center;">Inventory</h2>
<form enctype="multipart/form-data" id="bill" action ="{% url 'front:commitbill' %}" method = "post" class="form-horizontal">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="party" class="control-label col-md-3">{{ field.name }}</label>
<div class="col-md-4">
{{ field }}
</div>
<div class="col-md-5">
<span id="one" style="position:relative; top:5px; color:red "></span>
</div>
</div>
{% endfor %}
<div class="container">
<div class="row">
<input type="button" id="add_items" class="col-md-offset-5 col-md-2 btn btn-success" value="Add items" \>
</div>
</div>
</form>
and views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Description, Bill
from django.http import Http404
from .forms import DForm
from .forms import BForm
import pprint
def bill(request):
try:
billinfo = Description.objects.all()
context = {'billinfo': billinfo}
except Description.DoesNotExist:
raise Http404("No Bills")
return render(request, 'front/bill.html', context)
def commitvalues(request):
if request.method == "POST":
form = DForm(request.POST)
if form.is_valid():
Description = form.save()
print Description
return HttpResponse("Hello;You're at the front index.Commit's done!")
print form.errors
return HttpResponse("Fail")
def commitbill(request):
form = BForm()
if request.method == "POST":
form = BForm(request.POST,request.FILES)
if form.is_valid():
Bill = form.save()
return HttpResponse(str(Bill.bill_id()))
else:
print form.errors
form = BForm()
return render(request, 'front/index.html', {
'form': form
})
The print form.errrs returns the following two errors :
<ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
The forms starts working fine when i remove the image = forms.ImageField() from my forms.py, just the image doesn't uploads, otherwise when i include image = forms.ImageField(), the form never saves due to the above Error
The form field (text area) is not showing in my django template. I can figure out where the problem is.
Views.py
class Profile(View):
"""User Profile page reachable from /user/<username> URL"""
def get(self, request, username):
params = dict()
user = User.objects.get(username=username)
tweets = Tweet.objects.filter(user=user)
params["tweets"] = tweets
params["user"] = user
return render(request, 'profile.html', params)
class PostTweet(View):
"""Tweet Post form available on page /user/<username> URL"""
def post(self, request, username):
if request.method == 'GET':
form = TweettForm()
else:
form = TweetForm(self.request.POST)
if form.is_valid():
user = User.objects.get(username=username)
tweet = Tweet(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country'])
tweet.save()
words = form.cleaned_data['text'].split(" ")
for word in words:
if word[0] == "#":
hashtag, created = HashTag.objects.get_or_create(name=word[1:])
hashtag.tweet.add(tweet)
return HttpResponseRedirect('/user/'+username)
return render(request, 'profile.html', {'form': form})
forms.py
from django import forms
class TweetForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1, 'cols':85}), max_length=160)
country = forms.CharField(widget=forms.HiddenInput())
profile.html
{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
<div class="col-md-12 column">
<form method="post" action="post/">{% csrf_token %}
<div class="col-md-8 col-md-offset-2 fieldWrapper">
{{ form.text.errors }}
{{ form.text }}
</div>
{{ form.country.as_hidden }}
<div>
<input type="submit" value="post">
</div>
</form>
</div>
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', Index.as_view()),
url(r'^user/(\w+)/$', Profile.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/post/$', PostTweet.as_view())
)
Only the submit (post) button shows on the on when rendered in the browser. The text are is not there
You get nothing since you are not passing the form to the template. Write get function in PostTweet view and include form = TweetForm() in it as a param passed to the template.
I have been hacking away at this project for many hours now and just cannot figure out how to create a simple file upload app. I have looked at all the tutorials but none quite apply to my situation and i just cant get the code right. I know the code I have at this point wont run but I was hoping somone might be able to push me in the right direction with what I have. I know its not great but Im getting frustrated and I hope someone could help especially with my views.py Thank you so much. Thank you in advance!
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class WorkSheet(models.Model):
worksheet_name = models.CharField(max_length= 150, default = True)
creator = models.ForeignKey(User, default = True)
worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
number_of_stars = models.PositiveIntegerField(default = True)
category = models.CharField(max_length = 100, default = 0)
class UploadWorkSheetForm(ModelForm):
class Meta:
model = WorkSheet
Views.py
from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.conf import settings
from django import http
from models import WorkSheet
from forms import UploadWorkSheetForm
def upload(request):
template = 'upload.html'
if request.method == 'POST':
if 'file' in request.FILES:
file = request.FILES['file']
filename = file['filename']
fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()
return http.HttpResponseRedirect('upload_success.html')
else:
form = UploadWorkSheetForm()
return render_to_response(template, {'form': form})
return render(request, 'upload.html', {'form': form})
Upload.html
<!DOCTYPE html>
<html>
<head>
<title>WSD Upload</title>
</head>
<body>
<h1>Upload WorkSheet</h1>
{% block body %}
<form action="." method="post" enctype="multipart/form-data"> {{ form }}
<type="submit" value = "Upload"/>
</form>
{% endblock %}
</body>
</html>
If there is anything else you need please tell me. Thank you thank you thank you!
views.py
def upload(request):
template = 'upload.html'
if request.method == 'POST':
form = UploadWorkSheetForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('upload_success.html') <---change this to your valid url not template name
else:
form = UploadWorkSheetForm()
return render(request, 'upload.html', {'form': form})
template
...................
{% block body %}
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value = "Upload"/>
</form>
{% endblock %}
....................