I am trying to display my users information but I am getting anonymous user as my output;
Anonymous User
My code in my views.py is as follows;
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = RegistrationForm()
args = {'form' : form}
return render(request, 'accounts/register.html', args)
def view_profile(request):
args = {'user': request.user}
return render (request, 'accounts/profile.html',args)
I am over-riding the UserCreationForm, my code in forms.py is;
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = {
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
}
def save(self,commit=True):
user = super(RegistrationForm,self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
My profile.html where I want my profile information to be displayed is;
{% block head %}
<title> User Profile </title>
{% endblock %}
{% block body %}
<div class="container">
<p>
<h1> {{user}}</h1>
<h3>First Name: {{user.first_name}}</h3>
<h3>Last Name: {{user.last_name}}</h3>
<h3>Email: {{user.email}}</h3>
</p>
</div>
{% endblock %}
Really not sure where I am going wrong any help is greatly appreciated.
you must decorate your def view_profile(request): with #login_required, otherwise Django will serve this request also to Anonymous users.
Also note that if you have (or add) django.core.context_processors.request to your settings.TEMPLATE_CONTEXT_PROCESSORS
(or settings.TEMPLATES['OPTIONS']['context_processors'] depending your django version) you can use {{request.user}} in your template without create specific entry in context.
Related
I want to create a signup system with django .
and I create a user with a class that is on forms.py and extends UserCreationForm .
and I run server and fill the form and user is created but I cannot login with this user on the login page of django and it says me the user is not a staff user
how to make my user staff ???
forms.py :
class ModelNameForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username' ,
'first_name' ,
'last_name' ,
'email' ,
'password1' ,
'password2'
)
def save(self, commit=True):
user = super (ModelNameForm , self ).save(commit=False)
user.first_name = self.cleaned_data ['first_name']
user.last_name = self.cleaned_data ['last_name']
user.email = self.cleaned_data ['email']
if commit :
user.save()
return user
views.py :
def register (request):
form = ModelNameForm (request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks')
else:
form = ModelNameForm()
args = {'form' : form }
return render(request , 'signup.html' , args)
you can do that by adding
user.is_staff = True in your the model form save method
You can add user.is_staff = True in your ModelForm save method. But this is not safe because all new users will became staff users and they will have access to your admin page.
More safe way is create superuser and give access to another users manually in your admin. You can create superuser by this:
python manage.py createsuperuser
And after this you can to login with your superuser credentials to your django admin page. If need to give staff rights to users you have to open your admin page with superuser account, then click Users and find user. Open this user and click checkbox is staff.
I added user.is_staff = True in a separate form for creating staff users and I used another form for creating regular users. So that I am able to prevent all new users from becoming staff users.
I am using custom user model.
Following is the code for creating staff users:
forms.py
class StaffCreationForm(forms.ModelForm):
"""
A Custom form for creating new staffs.
"""
class Meta:
model = get_user_model()
fields = ['name','phone']
views.py
def register_staff(request):
if request.user.is_superuser: # giving access to superuser only.
form = StaffCreationForm()
if request.method == 'POST':
form = StaffCreationForm(request.POST)
if form.is_valid():
phone = form.cleaned_data.get('phone') # obtaining data from fields.
name = form.cleaned_data.get('name')
user = User.objects.create_user(phone = phone, name = name) # assigning obtained data to model variables and save user as staff.
user.is_staff=True
user.save()
message = ('%(name)s is added as a staff.') % {'name': name} # flash message for successful registration.
messages.success(request, message)
return redirect('staff')
context = {'form':form}
return render(request, 'registration/add_staff.html', context)
else:
return render(request, 'error-404.html')
urls.py
urlpatterns = [
path('add_staff', register_staff, name = 'staff'),
]
add_staff.html
<form method="POST">
{% csrf_token %}
{% for message in messages %}
{% if message.tags %}
<div class="alert alert-{{message.tags}}">
{{message}}
</div>
{% endif %}
{% endfor %}
{{ form|crispy }}
<input type="submit" class="btn btn-primary" value="Add Staff">
</form>
Okay I'm confused.
I'm trying to build a login page, but whenever I try to login, django gives the error that the username already exists. I haven't used save() anywhere.
I'm using authenticate(), I referred the Django docs for that:
https://docs.djangoproject.com/en/1.10/topics/auth/default/#how-to-log-a-user-in
Here is my code, please tell me where I'm going wrong:
forms.py
class LoginForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
class Meta:
model = User
fields = ['username', 'password']
views.py
class LoginFormView(View):
form_class = LoginForm
template_name = 'login.html'
# display a blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# authenticate user
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('slrtcebook:home')
return render(request, self.template_name, {'form': form})
login.html
<div class="form-container">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
{{ field }}
{{ field.errors }}
{% endfor %}
<input id="submit" type="submit" value="Log in" />
</form>
</div>
<p>Don't have an account? Register here</p>
Don't use a ModelForm for this; it will assume you're trying to create a user, and validate that you can do so with the data you've entered. Just use a standard form - inherit from forms.Form and remove the Meta class.
For those of you who want the code here is what I did to fix it:
inside of views.py:
class UserLoginView(View):
form_class = LoginForm
template_name = 'music/login_form.html'
#display a blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#proces form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
# user = form.save(commit=False)
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# user.set_password(password) #this is the only way to change a password because of hashing
#returns the User obejects if credintials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('music:index')
return render(request, self.template_name,{'form': form})
inside of froms.py:
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
fields = ['username', 'password']
don't forget to also import LoginForm at the top of views.py, where you import UserForm:
from .forms import UserForm, LoginForm
I am new to Django and was following a tutorial on how to build a register view. I did exactly the same but my form does not pass form.is_valid().
Here is what I did:
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
views.py
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponseRedirect('/accounts/register_success')
form = MyRegistrationForm()
return render(request, 'register.html', {'form':form})
def register_success(request):
return render(request, 'register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Register" />
</form>
{% endblock %}
When I tried to register new users on the webpage, none of them passed. Even when I used username: testuser email: testuser#example.com password:testuser123, it failed. So what is wrong?
Thanks in advance!
You should follow the correct view pattern. Put the line form = MyRegistrationForm() inside an else block, then the page itself will tell you why the form is not valid.
i want this functionality. User enters email address, and somehow it has to be passed to my views.py file, so i could then email the user that he has succesfully registered.
This is my template file:
{% extends "base.html" %}
{% block content %}
<section>
<h2 style="text-align: center">Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" value="Register" onclick="validateForm()"/>
</form>
</section>
{% endblock %}
this is my forms.py file:
class MyRegistrationForm(UserCreationForm):
#kokie fields bus displayed html form
email = forms.EmailField(required=True)
firstname = forms.CharField(required=True)
lastname = forms.CharField(required=True)
whoinvitedyou = forms.CharField(required=True)
phone = forms.CharField(required=True)
workplace = forms.CharField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', 'firstname', 'lastname', 'whoinvitedyou', 'phone', 'workplace')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data["password1"])
#more fields for name last name
user.firstname = self.cleaned_data['firstname']
user.lastname = self.cleaned_data['lastname']
user.whoinvitedyou = self.cleaned_data['whoinvitedyou']
user.phone = self.cleaned_data['phone']
user.workplace = self.cleaned_data['workplace']
if commit:
user.save()
return user
this is my views.py:
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
return render_to_response('invalid_reg.html')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render_to_response('register.html', args)
how do i pass the value so later i can use it? maybe somebody can help me with this...
In your view, after the form.is_valid() call, the email address will be available in form.cleaned_data['email']. You can use that to send the email after form.save().
Additionally, you might want to look into existing 3rd party libraries like django-registration as it already does the functionality (emailing the just registered user) that you want.
In order to send an e-mail you don't necessarily need to send the value to a view in views.py.
You can use a post_save signal to send an email. You can put the code anywhere, although I usually put it in models.py.
Info on signals: https://docs.djangoproject.com/en/1.7/topics/signals/
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
#receiver(post_save, sender=User)
def my_handler(sender, instance, *args, **kwargs):
send_mail('Subject of email', 'Message body.', 'from#example.com', [instance.email], fail_silently=False)
note that instance.email is the email address of the user which you just saved, you can access instance to retreive more information e.g. the name, so that you can put "dear "+instance.name at the beginning of the body for example
I am getting a valid response back when requesting my form, but I am getting no form fields with the response. It is loading the Submit button only, but no form fields.
Goal: get form fields to load and be able to submit form.
I have a views.py:
def Registration(request):
form = NewUserRegistrationForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponseRedirect("/Login/")
else:
form = NewUserRegistrationForm()
return render(request, 'VA/reuse/register.html', {
'form': form
})
forms.py
class NewUserRegistrationForm(UserCreationForm):
username = forms.CharField(required=True,max_length=30,validators=[RegexValidator('^[A-Za-z0-9]{1,30}$','e.g. must be 30 characters or less','Invalid Entry')])
email = forms.EmailField(required=True, max_length=75)
password = forms.PasswordInput()
class Meta:
model = User
fields = ("username", "email", "password1","password2")
def save(self, commit=True):
user = super(NewUserRegistrationForm, self).save(commit=False)
user.username = self.cleaned_data["username"]
user.email = self.cleaned_data["email"]
user.password = self.cleaned_data["password1"]
if commit:
user.save()
return user
a template
<div id="register_bubble">
<form method="post" id="userRegistration">
{% csrf_token %}
{{ NewUserRegForm.as_p }}
<input type="submit" value="Submit" />
</form> <!-- /RegistrationForm (FORM) -->
</div>
What am I doing wrong here? I'm getting no error while in debug mode locally either.
Thank you!
You have two mistakes.
Firstly, you're passing the form class into the template context, not the form instance: the class is NewUserRegistrationForm, but you've instantiated it as NewUserRegForm, and that's what you should be passing as the value in the form context.
To make it more complicated, the key name you've given to that value is also NewUserRegistrationForm - but you're still referring to NewUserRegForm in the template, even though that doesn't exist there.
This would be much more obvious if you used PEP8 compliant names. Instances should be lower case with underscore: eg new_user_registration_form. However, in this case you could just call it form, since there's only one.
return render(request, 'mysite/reuse/register.html', {
'NewUserRegForm': NewUserRegForm
})
or, better:
form = NewUserRegistrationForm(request.POST or None)
...
return render(request, 'mysite/reuse/register.html', {
'form': form
})
You're passing the form instance to the context as 'form', but calling it in the template as {{ NewUserRegForm.as_p }}.
You should use {{ form.as_p }} instead.