trying to create a registration form, and I am facing an issue. so, below are my python pages:
form.py
from .models import User
from django import forms
from django.forms import ModelForm
class SignUpForm(ModelForm):
class Meta:
model = User
fields = ('username','password','email')
models.py
from django.db import models
#from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class Registration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
urls.py
urlpatterns = [
url(r'^register/$', views.SignUpFormView, name= 'register'),
]
test.html
{% extends 'user_info/base.html' %}
{% block body %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form }}
username:<br>
<input type="text" name="username"><br>
password:<br>
<input type="text" name="password"><br>
email:<br>
<input type="text" name="email"><br>
<input type="submit" value="Submit" />
</form>
{% endblock %}
{% endblock %}
views.py
def SignUpFormView(request):
template_name = 'test.html'
try:
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get('email')
return render(request, template_name, {'form':form})
except ValueError:
print("Oops! That was not a valid entry, try again...")
else:
SignUpForm()
return render(request, 'user_info/about.html')
The issue is, my "SignUpFormView" function in views.py is not entering the "if" statement, its directly going to "else". I seem to be lost here.
I have 'about.html'. I do not see any error as well. Which I find very weird. Please help.
Note: I am using Django's default in-built "User" model, and I do not wish to create any custom model.
Modified views.py
def SignUpFormView(request):
user_form = 'SignUpForm'
template_name = 'test.html'
if request.method == 'POST':
form = user_form(request.POST)
if form.is_valid():
form.save()
#username = form.cleaned_data.get('username')
#password = form.cleaned_data.get('password')
#email = form.cleaned_data.get('email')
#user.save()
return render(request, template_name, {'form':form})
else:
SignUpForm()
return render(request, 'user_info/about.html')
Modified forms.py
from .models import User
from django import forms
from django.forms import ModelForm
class SignUpForm(forms.ModelForm):
#password = forms.Charfield(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username','password','email')
modified test.html
{% extends 'user_info/base.html' %}
{% block body %}
{% block content %}
{% for error in form.errors %}
{{ form.errors | default_errors }}
{% endfor %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{% for field in form %}
<p>
username:<br>
<input type="text" name="username"><br>
password:<br>
<input type="text" name="password"><br>
email:<br>
<input type="text" name="email"><br>
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" value="Submit">sign up </button>
</form>
{% endblock %}
{% endblock %}
Related
I made in Django a login system and it's not working the {% if user.is_autenticated %} method in html files. It always work as "not logged in", also when I'm logged in, I dont understand the problem. Can someone help me pease? Thanks for any help support
This is my code:
Views.py
# Form Post
class EditView(ListView):
model = Article
form_class = ArticleForm
template_name = 'blog/form_post/index.html'
ordering = ['-data']
class AddPostView (CreateView): # Create new Post
model = Article
form_class = ArticleForm
template_name = 'blog/form_post/add_post.html'
class EditPostView(UpdateView): # Edit a post
model = Article
form_class = ArticleForm
template_name = 'blog/form_post/edit_post.html'
class DeletePostView(DeleteView):
model = Article
template_name = 'blog/form_post/delete.html'
success_url = reverse_lazy('EditHome')
# Login
def Slogin(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username = username, password = password)
if user is not None:
login(request, user)
return redirect('EditHome')
else:
messages.info(request, 'Error')
context = {}
return render(request,'blog/form_post/Slogin.html' )
...
Html login File
{% extends 'blog/form_post/layout.html' %}
{% block title %} LogIn{% endblock title %}
{% block content %}
<form method="POST" action="" class=" form__group">
<h3 id="form-title" class="m-3 violet ">LOGIN</h3>
{% csrf_token %}
<input type="text" name="username" placeholder="Username..." class="w-75 m-3 border-top-0 border-left-0 border-right-0 bg-white">
<input type="password" name="password" placeholder="Password..." class="w-75 m-3 border-top-0 border-left-0 border-right-0 bg-white"> <br>
<button class="edit__button btn w-25 m-3" >Login</button>
</form>
{% for message in messages %}
<h2 class="m-3 red">{{ message }}</h2>
{% endfor %}
{% endblock content %}
html "index" file
{% extends 'blog/form_post/layout.html' %}
{% block title %} DashBoard{% endblock title %}
{% block content %}
{% if user.is_autenticated %}
code...
{% else %}
<p>You're not Admin</p>
{% endif %}
{% endblock content %}
You have a typo. It should be user.is_authenticated.
I extend the django User model with a profile model. I want add update user's profile function. Because I make the num field a unique field, in my update view function, the update form's is_valid was always False. I also cannot update the photo png? Here is my code;
Models:
class Profile(models.model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
num =models.CharField('identity',max_length=254,unique=True)
photo = models.ImageField('image',upload_to = 'images/licences')
forms:
class ProfileForm(forms.ModelForm):
class Meta:
model= Profile
fields = ['num','photo']
views:
def modify_view(request):
user = request.user
if request.method=="POST":
form = ProfileForm(request.POST,request.FILES)
if form.is_valid()
user_profile = Profile.objects.get(user=user)
user_profile.image = form.clean_data['image']
user_profile.save()
else:
form = ProfileForm()
return render(request,"profile.html",{form:form})
template
{% extends 'account/home/index.html' %}
{% block content %}
<div class="row">
<div class="col-md-8 col-sm-8 col-8">
<form class="signup needs-validation" id="signup_form" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{{form.as_p}}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<div class="form-group">
<button type="submit" class="col-sm-8 offset-sm-4 btn btn-success btn-block">update</button>
</div>
</form>
</div>
</div>
{% endblock %}
Since num field is unique and will not be generated again on updating the profile image, you can ignore request.POST and pass the instance argument to the ProfileForm class.
Example:
def modify_view(request):
user = request.user
if request.method=="POST":
user_profile = Profile.objects.get(user=user)
form = ProfileForm(files=request.FILES, instance=user_profile)
if form.is_valid():
user_profile.image = form.clean_data['image']
user_profile.save()
else:
form = ProfileForm()
return render(request,"profile.html",{form:form}
I am new to Django and looking to build a quick form with a response.
I am trying to build a form which would ask the user to input his name when the user clicks submit the page should reload and just say "Hello .
urls.py
class Question1Form(forms.Form):
n = forms.CharField(max_length=100,
widget=forms.TextInput(
attrs={'placeholder': 'Number', 'class': 'form-control'}))
views.py
def home(request):
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = [Question1Form.ans()]
return HttpResponse(Question1Form.n)
else:
form = Question1Form()
return render(request, 'index.html', {'form': form})
index.html
<form action="" method="post" class="form">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="form-row form">
<div class="col-sm-4">
{{ form.n.errors }}
{{ form.n }}
</div>
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
So how the code s
You should call instance field, not class field and get value from validated(cleaned) data (see documentation):
return HttpResponse(form.cleaned_data['n'])
If you want to reload the same template with n value:
return render(request, 'index.html', {'form': form, 'n': form.cleaned_data['n']})
and at the template add:
{% if form.is_valid %}
<p> Hello {{ n }} </p>
{% endif %}
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = form.save()
return render(request, 'index.html', {'created': True})
Then in your HTML you can say
{% if created %}
<p> Hello </p>
{% endif %}
edit I see now you have no action in your form.
So you need to point to that view in your URLS.py.
for example.
from myapp import views as app_views
from django.conf.urls import url
urlpatterns =[
url(r'^my_form/$', app_views.home, name='save_form'),
]
And then add the action to your form.
<form action="{% url 'save_form' %}" method="post" class="form">
I am trying to display user profile information in the users profile (original, I know,) but I can't get it to work unless it's the form view of the profile. I call user and foo in my user profile edit form with {{form.instance.user}} and it works fine.
I've implemented {{ user.get_profile.foo }} in my static user profile template (loggedin.html) but nothing happens.
My static user profile (loggedin.html) template looks like this:
{% extends "base.html" %}
{% block content %}
<title>{% block title %} | {{ username }}{% endblock %}</title>
<h2>Hi, {{ username }}!</h2>
<h3>{{ user.get_profile.foo }}</h3>
Edit Profile
{% endblock content %}
The view for loggedin.html:
def loggedin(request):
return render_to_response('loggedin.html', {'username':request.user.username, 'user':request.user})
My user profile edit form(profile.html) template:
{% extends "base.html" %}
{% block content %}
<title>{% block title %} | Edit Profile{% endblock %}</title>
<h2>Edit {{ username }}</h2>
{% for field in form %}
{{ field.error }}
{% endfor %}
<form action="/accounts/profile/" method="post">{% csrf_token %}
<label for="id_user">Username:</label>
<br>
<input id="id_user" name="user" type="text" value="{{form.instance.user}}">
<br><br>
<label for="id_foo">Foo:</label>
<br>
<input id="id_foo" name="foo" type="text" value="{{form.instance.foo}}">
<br><br>
<input type="submit" value="Update">
</form>
{% endblock content %}
My user profile (form) model:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
foo = models.CharField(max_length=30)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
My user profile (form) view:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from userprofile.models import UserProfile
#login_required
def user_profile(request):
user = request.user
username = request.user.username
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
args['user'] = user
args['username'] = username
return render_to_response('profile.html', args)
I can get the username and foo value to display fine in the user profile form, but when I try to get the same information to display in the static profile, it doesn't work.
Full disclosure: my static profile is in an app called polls which is different than the userprofile app where my edit form model and template are located, but I'm not sure if that has anything to do with this issue.
If you need to see my urls, settings, or admin code, let me know; I figured it wasn't relevant, and would just add clutter, but I'm happy to add it if needed.
Your property is User.profile. Therefore you should try
{{ user.profile.foo }}
in your template, instead of {{ user.get_profile.foo }}.
Trying my first app in Django, and have some problem on form validation (following documentation)
This is part of file upload code. The form creates fine. But, the validation fails.
Even though, I provide Title, it gives This field is required.
views.py
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#TODO handle(request.FILES['file'])
return HttpResponseRedirect('/')
else:
form = UploadFileForm()
return render_to_response('setup.html', {'form': form},context_instance=RequestContext(request))
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField()
file = forms.FileField()
setup.html
<form action="/setup/" method="post">{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<input type="submit" value="Submit" />
</form>
Add required paremeter to your form field. If you don't provide it Django will assume it is required.
title = forms.CharField(required=False)