Good day,
I am making a Django application,
I want to call my data that the user signs up with and to display the information they submitted as:
Name
Email
Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it
What am I doing wrong?
My code below:
views.py
from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages, auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from contacts.models import Contact
def register(request):
if request.method == 'POST':
# Get form values
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
# Check if passwords match
if password == password2:
# Check username
if User.objects.filter(username=username).exists():
messages.error(request, 'That username is taken')
return redirect('register')
else:
if User.objects.filter(email=email).exists():
messages.error(request, 'That email is being used')
return redirect('register')
else:
# Looks good
user = User.objects.create_user(
username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa
# Login after register
auth.login(request, user)
messages.success(request, 'You are now logged in')
return redirect('index')
# user.save()
# messages.success(
# request, 'You are now registered and can log in')
# return redirect('login')
else:
messages.error(request, 'Passwords do not match')
return redirect('register')
else:
return render(request, 'accounts/register.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
def logout(request):
if request.method == 'POST':
auth.logout(request)
messages.success(request, 'You are now logged out')
return redirect('index')
#login_required(login_url='login')
def dashboard(request):
user_contacts = Contact.objects.order_by(
'-contact_date').filter(user_id=request.user.id)
context = {
'contacts': user_contacts
}
return render(request, 'accounts/dashboard.html', context)
#login_required(login_url='login')
def edit_profile(request, pk):
user = User.objects.get(id=pk)
if request.method == 'POST':
...
user.name = request.GET['name']
user.email_address = request.GET['email_address']
user.save()
return redirect('dashboard')
context = {
'user': user
}
return render(request, 'accounts/dashboard.html', context)
#login_required(login_url='login')
def delete_profile(request, pk):
user = User.objects.get(id=pk)
if request.method == 'POST':
...
user.name = request.GET['name']
user.email_address = request.GET['email_address']
user.delete()
return redirect('index')
context = {
'user': user
}
return render(request, 'index.html', context)
Then my urls
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('register', views.register, name='register'),
path('login', views.login, name='login'),
path('logout', views.logout, name='logout'),
path('dashboard', views.dashboard, name='dashboard'),
path('edit_profile/<int:pk>/', views.edit_profile, name='edit_profile'),
]
Lastly My edit_profile.html
{% extends 'base.html' %}
{% block title %} | Edit Profile {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">User Dashboard</h1>
<p class="lead">Manage your BT Real Estate account</p>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Dashboard</li>
</ol>
</nav>
</div>
</section>
{% comment %} Alerts {% endcomment %}
{% include 'partials/__alerts.html' %}
<section id="dashboard" class="py-4">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Welcome {{ user.first_name }}
<a class="btn btn-info" href="{% url 'dashboard' %}">
Save Profile
</a>
<a class="btn btn-da nger" href="{% url 'dashboard' %}">
Del;ete Profile
</a>
</h2>
<h3>Account Details: </h3>
<form action="{% url 'contact' %}" method="POST">
{% csrf_token %}
{% if user.is_authenticated %}
<input type="hidden" name="user_id" value="{{ user.id }}">
{% else %}
<input type="hidden" name="user_id" value="0">
{% endif %}
<input type="hidden" name="realtor_email" value="{{ listing.realtor.email }}">
<input type="hidden" name="listing_id" value="{{ listing.id }}">
<div class="form-group">
<label for="property_name" class="col-form-label">Property:</label>
<input type="text" name="listing" class="form-control" value="{{ listing.title }}" >
</div>
<div class="form-group">
<label for="name" class="col-form-label">Name:</label>
<input type="text" name="name" class="form-control" {% if user.is_authenticated %} value="{{ user.first_name }} {{ user.last_name }}" {% endif %} required>
</div>
<div class="form-group">
<label for="email" class="col-form-label">Email:</label>
<input type="email" name="email" class="form-control" {% if user.is_authenticated %} value="{{ user.email }}" {% endif %} required>
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone:</label>
<input type="phone" name="phone" class="form-control" {% if user.is_authenticated %} value="{{ user.phone }}" {% endif %} >
</div>
<input type="submit" value="Send" class="btn btn-block btn-secondary">
</form>
</div>
</div>
</div>
</section>
{% endblock %}
PLEASE HELP!
Related
I am trying to submit a Message form for my Django Project but I keep receiving an error:
AttributeError at /
'MessageForm' object has no attribute 'cleaned_data'
I am not sure what is the reason for getting this error although I revised the https://docs.djangoproject.com/en/3.1/topics/forms/
Here is my views.py
def home(request):
if request.method == 'POST': #Check Post
form = MessageForm(request.POST)
if form.is_valid():
data = MessageForm() #Create Relationship with Model
data.name= form.cleaned_data['name']
data.email= form.cleaned_data['email']
data.message= form.cleaned_data['message']
data.ip = request.META.get('REMOTE_ADDR')
data.save()
messages.success(request,'Your Message has been sent, Thank you!')
return HttpResponseRedirect('base:home')
template_name = 'base/home.html'
form = MessageForm()
----------------------other unrelated contexts--------------------
context = {
'form': form,
}
return render(request, template_name, context)
Here is the urls.py
urlpatterns = [
path('', views.home,name='home')
]
Here is the template.html
<form class="form" id="form" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="name" id="form-name" type="text" placeholder="Your Name" class="form-control input" autocomplete="off"/>
<div id="name-error"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input name="email" id="form-email" type="email" class="form-control input" placeholder="Your E-Mail" autocomplete="off">
<div id="email-error"></div>
</div>
</div>
</div>
<div class="form-group">
<textarea name="message" id="form-message" class="form-control input" rows="7" placeholder="Your Message here ..." autocomplete="off"></textarea>
<div id="message-error"></div>
</div>
<!-- Messages -->
{% if messages %}
{% for message in messages %}
<div class="container">
<div class=" alert alert-{{ message.tags }}">
{{ message }}
</div>
</div>
{% endfor %}
{% endif %}
<!-- Messages -->
<input id="form-submit" type="submit">
<div class="send-message" >
Send <i class="ni ni-send"></i>
</div>
</form>
You are constructing a new form, but that does not make much sense. Once your orignal form is validated, you can save that form, so:
def home(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.instance.ip = request.META.get('REMOTE_ADDR')
form.save()
messages.success(request,'Your Message has been sent, Thank you!')
return redirect('base:home')
# …
I have a SignUp form that interacts with Django's user model to create new users. If password fields match, the user is successfully created and logged in. If password fields do not match, the user is not created, so I guess validation is working. But somehow, a validation error message is not shown, the form page is just rendered again. When I go to Django's admin page, the error messages pop up there! Why is it not popping in my template?!
This is my form:
class SignUpForm(forms.ModelForm):
password = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}),)
password2 = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Confirm Password', 'class':'form-control', 'type':'password'}),)
class Meta:
model = User
widgets = {'first_name': forms.TextInput(attrs={'placeholder':'First Name', 'class':'form-control'}),
'last_name': forms.TextInput(attrs={'placeholder':'Last Name', 'class':'form-control'}),
'email': forms.TextInput(attrs={'placeholder':'Email', 'class':'form-control', 'type':'email'}),
'username': forms.TextInput(attrs={'placeholder':'Username', 'class':'form-control'}),
'password': forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'})
}
fields = {'first_name', 'last_name', 'email', 'username', 'password'}
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
password = cleaned_data.get('password')
password2 = cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError('Passwords do not match!')
And this is my view:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
form.save()
user = authenticate(username=username, password=password)
login(request, user)
messages.add_message(request, messages.SUCCESS, 'Account created successfully!')
return HttpResponseRedirect('/')
else:
messages.add_message(request, messages.ERROR, "There's an error in the form! Please fill it again.")
return render(request, 'form/register.html', {'form': form})
else:
form = SignUpForm()
return render(request, 'form/register.html', {'form': form})
And this is my template:
<div class="login-box-body">
{% block login_form %}
<form method="POST">
{% csrf_token %}
{% if form.errors %}
{% for error in field.errors %}
<p class="login-box-msg" style="color: red;">{{ error }}</p>
{% endfor %}
{% endif %}
<div class="form-group has-feedback">
{{form.first_name}}
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{{form.last_name}}
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{{form.email}}
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{{form.username}}
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{{form.password}}
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{{form.password2}}
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<button type="button" class="btn btn-default" onclick="window.location.href='{% url 'manager:login' %}'">Voltar</button>
</div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Criar Conta</button>
</div>
</div>
</form>
{% endblock login_form %}
What am I doing wrong?
Okay, I managed to work it out, at least as a temporary solution! Daniel was right, there was a typo in my template, but it was showing "_ all _" as the error message, not sure why.
Since the password fields were the only ones I was using raise forms.ValidationError function, then the error message was only to be shown in case the passwords wasn't matching.
So I just wrote the error message I wanted directly in my template! Like this:
<form method="POST">
{% csrf_token %}
{% if form.errors %}
<p class="login-box-msg" style="color: red; font-weight: bold;">Passwords do not match!</p>
{% endif %}
It doesn't work the way I wanted, but it does the job!
I have a login function, however when I try to login with a user that is not admin Django's authenticate function returns None even though the user exists in the database and the function receives the right username and password.
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
user = authenticate(username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
login template:
{% extends "orders/layout.html" %}
{% block title %}
Login
{% endblock %}
{% block body %}
<div class="forms">
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Username</label>
<input class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
{% if message %}
<small id="emailHelp" class="form-text text-muted">{{ message }}</small>
{% endif %}
</div>
<button type="submit" class="btn button" id="button1" >Log In</button>
<a class="btn button" href="{% url 'register' %}" role="button" id="button2">Register</a>
</form>
</div>
{% endblock %}
url.py :
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("menu/<product>/", views.menu, name="menu"),
path("register", views.register, name="register"),
path("add_to_cart", views.addToCart, name="add_to_cart"),
path("cart", views.cart, name="cart"),
path("confirm", views.confirm, name="confirm"),
path("login", views.login_user, name="login"),
path("logout", views.logout_user, name="logout")
]
Try this :
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
if username and password:
user = authenticate(username=username, password=password)
if user is not None:
If user.is_active:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"User does not exist."})
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
Here is my code. Everything is working fine but when I tried to log in and hit on login button nothing happens. My login page didn't redirect me on any page.
Login page code:
{% extends 'authenticate/base.html' %}
{% block content%}
<h1 class="text-center">Login </h1>
<div class="col-md-6 offset-md-3"
<form method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter UserName"
name="username">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password"
name="password">
</div>
<button type="submit" class="btn btn-secondary">Login</button>
</form>
</div>
{% endblock %}`
Views.py page code:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
def home(request):
return render(request, 'authenticate/home.html',{})
def login_user(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return redirect('login')
else:
return render(request, 'authenticate/login.html', {})
Base.py page code:
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{%url 'login'%}">Login</a>
</li>
</ul>
</div>
def login_user(request):
form = LoginForm(request.POST)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
return render(request, 'authenticate/login.html', {'form':form})
I'm making a webpage where I login and add people to an address book. Once I login and click on the "add address" button, I'm redirected back to the login page with the following url:
http://localhost:8000/xcard/login/?next=/xcard/add_address/
If I login again I can get to account page, address book, and then add_address book page without being caught in the login loop. I can logout and login and add addresses without relogin in twice. But the first time I ever login I have to do it twice. Not sure if it's a problem with the login or the add address code.
Views.py
class LoginView(View):
def get(self, request):
''' if user is authenticated '''
if request.user.is_authenticated():
return render(request, 'xcard/account.html')
else:
return render(request, 'xcard/login.html')
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "The email or password is incorrect"
if user is not None:
login(request, user)
return HttpResponseRedirect('/xcard/account/')
else:
return render(request, 'xcard/login.html', {'state':state})
class AddAddressView(View):
def get(self,request):
address_form = AddressForm()
friend_form = FriendForm()
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
def post(self,request):
address_form = AddressForm(request.POST)
friend_form = FriendForm(request.POST)
if address_form.is_valid() and friend_form.is_valid():
new_address = address_form.save()
new_friend = friend_form.save(commit=False)
new_friend.address = new_address
new_friend.save()
return HttpResponseRedirect('/xcard/address_book')
else:
return render(request, 'xcard/add_address.html', {'state' : "Failed", 'friend_form':friend_form, 'address_form':address_form})
Templates:
address_book.html
{% include "xcard/header.html" %}
{% block main %}
<div class="container">
<h3 class="text-info"><u>Your Account</u></h3>
Add
Import
</div>
{% endblock %}
Templates:
login.html
{% extends "xcard/base.html" %}
{% block main %}
<div class="container">
<div class="row space">
<p class="text-center lead text-warning">
Login page</p>
<p class="text-center text-info">Trusted worldwide!</p>
</div>
<div class="row">
<div class="span offset4">
<form class="well" action="/xcard/login/" method="post">
{% csrf_token %}
<p class="lead">Sign In</p>
<fieldset class="login_page">
<p class="text-error"><strong>{{ state }}</strong></p>
<label class="control-label" for ="inputIcon">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="span3" id="ernainputIcon" required name="username" placeholder="Username...."/><br/><br/>
</div>
</div>
<label>Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" class="span3" id="inputIcon" required name="password" placeholder="Password...."/><br/><br/><br />
</div>
</div>
<button class="btn btn-primary">Sign In</button>
Not a user?
Sign up
</fieldset>
</form>
</div>
</div>
</div>
{% endblock %}
I just found this in my urls.py
url(r'^add_address/$', login_required(AddAddressView.as_view(), login_url='/xcard/login/')),
Maybe this is causing the problem? But why doesn't it register that I'm already logged in?
first do the correction in AddAddressView function. update line
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
it will work
This was my solution - logout before you try to authenticate.
This issue happened to me when users were logging in and logging back in with a different username.
import django.contrib.auth as djangoAuth
djangoAuth.logout(request) # logout
user = djangoAuth.authenticate(username=username, password=password) # login