I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! also if anyone knows a easier way please tell me. i can update my question again if anyone needs more details.
Views.py
from django.forms import ModelForm
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def myview(request,id):
data= userdetails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
def register(request ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
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('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
quantity = request.POST['quantity']
location = request.POST['location']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, )
ins.save()
return render(request,'donate.html')
Error:
File "C:\Users\jbtai\coding\GoodDeedWeb\home\views.py", line 30
def register(request ):
^
You need a view that handle that:
def myview(request):
id = request.user.id
data= userderails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
Then in your template 'dashboard.html' you could show details:
{{data.donations}}
{{data.points}}
use this url for that view instead of the old one
path('dashboard/',views.myview, name = 'dashboard' ),
Related
I create models,forms and views for registrarion and i want to create a login view so that after registration user can login.
models.py
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
g_CHOICES = (('male','male'),('female','female'))
class User(AbstractUser):
gender = models.CharField(max_length=100,choices=g_CHOICES,default="male")
country = CountryField()
location = models.CharField(max_length=30, blank=True)
forms.py
g_CHOICES = (('male','male'),('female','female'))
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.ChoiceField(choices=g_CHOICES)
country = CountryField().formfield()
location = forms.CharField(max_length=30,)
class Meta:
model = User
fields = ['first_name','last_name','username','email',
'password1','password2','gender',
'country','location']
views.py
def register(request):
if request.method == 'POST':
rform = UserRegisterForm(request.POST)
if rform.is_valid():
rform.save()
username = rform.cleaned_data.get('username')
messages.success(request,('Account created for '+str(username)))
return redirect('/')
else:
rform = UserRegisterForm()
return render(request,'reg.html',{'rform':rform})
Now i want to create a view for login please someone help
You need a view that takes the user's username and password from the POST request, then authenticates them and logs them in using 'authenticate' and 'login' from django.contrib.auth package.
from django.contrib.auth import login, authenticate
from django.views import View
class HandleLogin(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
username= request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
# Do something for succesfull logged in
else:
# Do something else because user is not active
else:
# Do something about user not existing
For more information: https://docs.djangoproject.com/en/2.2/topics/auth/default/
You can use something like below one:
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')
Or if you are using a django form you can do this way too and this is more preferred way:
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
Please help me implement these features so that another user cannot delete or edit my ads. So far, only unregistered users can not edit and delete.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
listing.delete()
return redirect('index')
#login_required
def listing_edit(request, listing_id):
form = ListingForm(instance = Listing.objects.get(id = listing_id))
if request.method == "POST":
form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id))
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
#login_required
def listing_add(request):
form = ListingForm()
if request.method == "POST":
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
listing = form.save(commit=False)
listing.realtor = request.user.realtor
listing.save()
return redirect('dashboard')
return render(request, 'listings/listing_add.html', {'form': form})
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')
...
class Realtor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')
You just need to check that the user making the POST request is the author (realtor) of the listing:
#login_required
def listing_edit(request, listing_id):
listing = Listing.objects.get(id=listing_id) # avoid multiple database calls
form = ListingForm(instance=listing)
if request.method == "POST" and request.user == listing.realtor.user:
form = ListingForm(request.POST, request.FILES, instance=listing)
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
The same applies for the delete view.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
if request.user == listing.realtor.user:
listing.delete()
return redirect('index')
I just started with Python and Django and want to redirect a user to a home page after successful form-registration with a head-massage changed to "You have successfully registered".
My code without changing a massage after redirection is:
urls.py:
urlpatterns = [
path('', IndexView.as_view(), name = 'index'),
path('register/', views.register, name = 'register'),
]
views.py:
class IndexView(TemplateView):
template_name = 'first_ap/index.html'
def get_context_data(self, *args, **kwargs):
t_user = 'Hello my friend'
context = {
'viva':t_user
}
return context
def register(request):
if request.method == "POST":
form = RegForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.set_password(form.cleaned_data['password'])
new_user.save()
return redirect('index')
else:
form = RegForm()
return render(request, 'first_ap/register.html', {'form': form})
In html file I put:
<h1>{{ viva }}!</h1>
How should I modify a code to change a context after redirection from "Hello my friend" to "You have successfully registered"? I tried several options but they all failed.
Why dont you just save the message in an object variable:
class IndexView(TemplateView):
template_name = 'first_ap/index.html'
text='Hello my friend'
def get_context_data(self, *args, **kwargs):
context = {
'viva':self.text
}
return context
def register(request):
if request.method == "POST":
form = RegForm(request.POST)
if form.is_valid():
IndexView.text='You have registered'
new_user = form.save(commit=False)
new_user.set_password(form.cleaned_data['password'])
new_user.save()
return redirect('index')
else:
form = RegForm()
return render(request, 'first_ap/register.html', {'form': form})
Solution:
from django.urls import reverse
class IndexView(TemplateView):
template_name = 'first_ap/index.html'
def get_context_data(self, *args, **kwargs):
# request.GET contains the query parameters, check if `first_visit` is 1 or not
is_first_visit = self.request.GET.get('first_visit', 0) == "1"
if is_first_visit is False:
t_user = 'Hello my friend'
else:
t_user = 'You have successfully registered'
context = {
'viva': t_user
}
return context
def register(request):
if request.method == "POST":
form = RegForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.set_password(form.cleaned_data['password'])
new_user.save()
# add a query parameter to indicate user's first visit
return redirect(reverse('index') + "?first_visit=1")
else:
form = RegForm()
return render(request, 'first_ap/register.html', {'form': form})
Add a query parameter first_visit as 1 (random value) in the redirect call after successful registration.
Access the query parameter using self.request.GET dict
Change the context value based on the value of first_visit
So I am working on user authentication, login, logout. I am getting the error when I am opening the registration portal.
AttributeError at /profile/
'User' object has no attribute 'get_profile'
Following is my views.py
def Registration(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password'])
user.save()
UserProfile= UserProfile(user=user, birth_date=form.cleaned_data['birth_date',])
UserProfile.save()
return HttpResponseRedirect('/profile/')
else:
return render('visit/registration/register.html', {'form': form},)
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/register.html', context )
#login_required
def Profile(request):
if not request.user.is_authenticated:
return HttpResponseRedirect('/login/')
UserProfile = request.user.get_profile()
context ={'UserProfile': UserProfile}
return render(request,'visit/profile.html', context)
def LoginRequest(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = LoginRequest(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
UserProfile = authenticate(username=username, password=password)
if UserProfile is not None:
login(request, UserProfile)
return HttpResponseRedirect('/profile/')
else:
return render(request,'visit/registration/login.html',{'form':form})
else:
return render(request, 'visit/registration/login.html', {'form': form})
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/login.html', context, )
def logoutRequest(request):
logout(request)
return render(request, 'visit/login.html')
def index(request):
return render(request, 'visit/index.html', context=None)
I am not sure what/where the error is. I am using the Django 2.0.2.
I know there are similar questions but I am not getting the proper solution.
Help would be appricated. Following is my settings.py
#provides our get_profile
AUTH_PROFILE_MODULE = 'visit.model.UserProfile'
# URL for #login required
LOGIN_URL = '/login/'
#redirect authenticated user
LOGIN_REDIRECT_URL = '/profile/'
As per #neverwalker comment, this method is deprecated 1.7. please refer below code
user_profile = UserProfile.objects.get(activation_key='some_key')
user = user_profile.user
my ModelForm definition looks like this:
class UserForm(ModelForm):
password = forms.CharField(required=True, label="Password", widget=forms.PasswordInput)
So password is required when I'm creating a new user. However I'd like to NOT require it when editing the user. My edit/add is handled in views.py in the following way
#user_passes_test(lambda u: u.is_superuser)
def add(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
new_user.save()
messages.success(request, "User '%s' created" % new_user.username)
return HttpResponseRedirect('/user')
else:
form = UserForm()
return render(request, 'user/add.html', {"form": form})
#user_passes_test(lambda u: u.is_superuser)
def edit(request, id):
user = User.objects.get(id=id)
if request.method == 'POST':
f = UserForm(request.POST, instance=user)
if f.is_valid():
f.save()
messages.success(request, "User '%s' altered" % user.username)
return HttpResponseRedirect('/user')
else:
form = UserForm(instance=user)
return render(request, 'user/edit.html', {"form": form, "user": user})
Thanks for the answer.
Michal
This is what I would do:
class UserForm(ModelForm):
def __init__(self, *args, **kwargs):
is_edit = kwargs.get('is_edit', False)
if 'is_edit' in kwargs:
del kwargs['is_edit']
super(UserForm, self).__init__(*args, **kwargs)
if is_edit:
self.fields['password'].required = False
Then, in your edit() function:
f = UserForm(request.POST, instance=user, is_edit=True)
I use this type of thing fairly regularly in our codebase.