How To Make User Profile in Django?
Hi I Want to Know How To Make User Profile when user signup in our django app i want create a profile page for the person
Here is my Views.py
def user_reg(request):
register = False
if request.method == 'POST':
form = user_register_form(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
register = True
if register == True:
return HttpResponseRedirect("/accounts/login")
else:
print(form.errors)
else:
form = user_register_form()
context = {'reg':form,}
return render(request,'signup.html',context)
Models.py
class user_register_model(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
join_date = models.DateTimeField(default=timezone.now)
I Want To Know How To Create Profile Page If User sign Up in our website Problem is How To Create His Profile Page
For Example:
If You Register on Stack overflow You Click on profile icon and you can go to your page
Stack overflow Make Your Page
I Need Some Thing Like That
When User Signup i need user page but how to make that?
i research on google and youtube i can't find any prefect answer
can you please help me?
Create a URL in urls.py like this:
path('profile/<username>', views.user_profile, name='user_profile'),
views.py (If you are using User model to save user data.)
def user_profile(request, username):
user = User.objects.get(username=username)
context = {
"user": user
}
return render(request, 'user_profile.html', context)
user_profile.html (use profile data as per requirement)
{{ user.username }}
{{ user.first_name }}
You can check this on link http://127.0.0.1:8000/profile/<username>/. replace username with user's username and page will show data of only that user.
-----------Edit-----------
If you want to create link, use this:
<a class="nav-link navaour" href="{% url 'profile' username=<username> %}">
replace user's username.
You can just create a view with a template see this. You can have editable forms or anything you like. This view will be shown only if the user is logged in and for unauthorized users redirect them to your login page.
Related
I am using #login required decorator in my most of views so what I want is to use message in my login page telling user if you want to open that page you have to login first so how I can achieve that I know I cannot achieve that on my views so anyone does that and know how to do please tell me how to achieve that if a user redirected to login because of #login required I want to show message please login to continue
I also looked on some of the same question I am looking for answer which got implemented on all the login required decorator so I don't have to change code everywhere it already got implemented in all of the login required decorator in my whole app
my login view
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
return redirect('accounts:login')
else:
return redirect('accounts:register')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
Solution 1:
In your view, check the query parameter "next", as if the user is redirected to the login view, it would come with the ?next=/whatever in the URL. You can do
if 'next' in request.GET:
messages.add_message(request, messages.INFO, 'Hello world.')
Solution 2 (not recommended, this makes it confusing to debug for others):
Python being a dynamic language, you can hijack the behaviour of login_required with your version.
in your manage.py and wsgi.py and maybe asgi.py you would need to "monkey patch" the login_required decorator.
from django.contrib.auth import decorators
def my_login_required(...):
# you can look at the implementation in the answer by LvanderRee mentioned in the comments
decorators.login_required = my_login_required
Now, because these files will be the first code to execute before Django even starts, this will replace the built-in login_required with your version.
Based on this Stack Overflow post, using multiple answers, to redirect to another page, either:
Set LOGIN_URL in settings.py. This is the URL that Django will redirect to if a user that's not yet logged in attempts to log in.
or Inline:
from django.contrib.auth.decorators import login_required
#login_required(login_url='/example url you want redirect/') #redirect when user is not logged in
def myview(request):
do something
return something #returns when user is logged in
Of course, you still need to have the login view setup.
If you want to check if the user is authenticated in the HTML, you can use the templating system: (For clarity this is something I just whipped up right now, it's not from the Stack Overflow post mentioned above)
{% if user.is_authenticated %}
// Display something if authenticated maybe
{% else %}
// Display something like "You are not logged in etc"
{% endif %}
I have an account page that lets users edit their accounts. When the save button is pressed, I run the following code:
request.user.first_name = request.POST['first_name']
request.user.last_name = request.POST['last_name']
request.user.save()
context['alert'] = {
'title': "Your information has been updated",
'color': 'primary',
}
As you can see, I pass in context that, in my template, renders as an alert. However, when I refresh the page, it says: Confirm Form Resubmission
How can I get rid of this error? Thanks!
A successful POST request normally results in a redirect, this is the so-called Post/Redirect/Get pattern [wiki].
In order to send messages to the user, you can make use of the messaging framework [Django-doc]. So you can add a message for a user, and then render it in the other view(s):
from django.shortcuts import redirect
from django.contrib import messages
def my_view(request):
request.user.first_name = request.POST['first_name']
request.user.last_name = request.POST['last_name']
request.user.save()
messages.success(request, 'Your information has been updated')
return redirect('name-of-some-view')
I have built a custom password reset in Django, however, after putting the information in 'PasswordResetForm' I get a 404 page not found error.
This is my code for reset_password:
def reset_password(request,username):
if request.method == 'POST':
form = PasswordResetForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
#added this to redirect user to custom url
username = request.user.username
return redirect(reverse('main:home', kwargs={'username': username}))
#return redirect(reverse('main:home'))
else:
return redirect(reverse('main:reset_password'))
else:
form = PasswordResetForm(user=request.user)
args = {'form': form}
return render(request, 'reset_password.html', args)
My urls at myapp/urls.py
urlpatterns=[
path('signup/',views.signup,name='signup'),
path('login',views.user_login,name='user_login'),
path('',views.main_page,name='main_page'),
path('<str:username>', views.home, name='home'),
#replace home/edit with below
path('<str:username>/edit', views.edit_profile, name='edit_profile'),
path('<str:username>/password-reset', views.reset_password, name='reset_password'),
]
and my form for password reset:
class PasswordResetForm(PasswordChangeForm):
class Meta:
model = Profile
fields = ('old_password','new_password1','new_password2')
What seems to be the problem here? I do not know why I am getting this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/main/test3-b/login.html?next=/main/test3-b/password-reset
This is my AbstractUser model in models.py (I do not have any other code in my models.py
class Profile(AbstractUser):
bio = models.TextField()
university = models.CharField(max_length=30)
def __str__(self):
return self.username
Your urls.py is not using the same path as the URL you are accessing. The URL example you have given is http://127.0.0.1:8000/main/test3-b/login.html but your password reset url is something like http://127.0.0.1:8000/example-user/password-reset where example-user is the username that you are trying to match inside your path.
Out of interest do you have the URL structure include a username? This is normally not wanted as you would be using request.user to access the current user. You also have the risk a users username could break your patterns as you are using str rather than slug which is safer in URL patterns as otherwise id a user was created with the username of "example/edit" then they would never be able to get to your homepage as it would match the edit_profile entry instead.
I saw that by the form rendered in HTML it does not reset the admin user password, however the others works. In my case, I just extended the user class and inserted the email field.
I have a django project I created. This django project is split into two apps, the user and common. I have a method in the user app that allows the user to submit a form which will create a new Django user. Once the form is submitted and process I want to redirect the user to the testing page in the common app and display a html template that says testing page. Everything is working, the form is being processed and the redirect is occuring. I know this because the url changed to the expected url which will display the html testing page. For some reason, even though the url is transfering to the correct one, the html template being displayed is actually the signup form html template not the correct template.
Here is the code from the common app:
views.py
# testing method
def test(request):
return render(request, 'common/test.html')
urls.py:
urlpatterns = [
url(r'^test/$', views.test, name='test'),
]
test.html:
{% extends "base.html" %}
{% block standard %}
<p>testing page</p>
{% endblock %}
here is the redirect from the users app:
this is in the signup def after the user has been created
return redirect('test')
here is the entire signup method:
# have a user signup and create his account
def Signup(request):
# check to see if form is submitted
if request.method == "POST":
# grab the form and information
form = SignupForm(request.POST)
# validating form
if form.is_valid():
# grab the form content
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
# check if passwords match
if password == verify:
# create safe passwords
secure_password = make_password(password)
# save username in sessions
# request.session['username'] = username
return redirect('test')
else:
# redirec to original forms
message = "Passwords did not match"
# users form
form = SignupForm()
# everything required for the template
parameters = {
'message':message,
'form':form,
}
# display html template
return render(request, 'user/Signup.html', parameters)
else:
# the signing up form
form = SignupForm()
message = "Please fill out the entire form"
# everything that needs to be passed to html template
parameters = {
'form':form,
'message':message,
}
# render the template
return render(request, 'user/Signup.html', parameters)
What would be the best implementation to redirect a user who is not signed in? Is there a better way then to use a #is_autenticated type decerator in every single view?
The alternative I have thought of is to have a base.html which checks for is_authenticated and every html will extend base. Ex:
base.html
{% if request.user.is_authenticated %}
{% block content %}
content here
{% endblock content %}
{% else %}
redirect
I feel though this way puts view logic into the template which really doesn't sit well but it would avoid a decorator on every function.
You could use some middleware. Personally, I think having the redirect in the template (I'm assuming in javascript code) is very ugly. Django-stronghold (https://github.com/mgrouchy/django-stronghold) is nice if most views require authentication.
Django has an in-built authentication model.Authentication logic should always be in the views and including view logic in the template is a bad practice.Once the user is authenticated, you can render a homepage from the views along with a welcome message.You can do the following:
from django.contrib.auth import authenticate
# login to home page -
def home(request):
try:
username = password = ''
if request.POST:
username = request.POST['username']
password = request.POST['password']
print username
print password
user = authenticate(username=username, password=password)
print "User value is",user
if user is not None:
if user.is_active:
login(request, user)
request.session['username'] = username
return render_to_response('home.html',{"message": "Welcome"})
# Redirect to a success page.
else:
return render_to_response('login.html',{"message": "User is Inactive"})
# Return a 'disabled account' error message
else:
return render_to_response('login.html',{"message": "Invalid Credential"})
else:
return render_to_response('home.html',{"user" : request.session['username']})
except:
return render_to_response('error.html',{"message": sys.exc_info()[0]})