i want to user when click profile pass user to profile.html but problem i don't solve hem
--------- path
path('home', views.home, name="home"),
path('profile/<int:id>', views.profile_views, name="profile_views")
-------- models
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
music = models.CharField(max_length=50)
skils = models.CharField(max_length=50)
search = models.CharField(max_length=50)
posts = models.CharField(max_length=50)
boi = models.TextField()
img = models.ImageField(upload_to="profile-img")
def __str__(self):
#return self.user or 'User'
return str(self.id)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
------- views
def home(request, id):
pro_id = profile.objects.get(id=id)
context = {'pro_id' : pro_id}
return render(request, 'main-frond.html')
def profile_views(request, id):
ff = profile.objects.get(id=id)
context = {'ff' : ff}
return render(request, 'profile.html', context)
------ html
<br>
profile
<br>
<hr>
{{request.user}}
<hr>
Login
Register
where's the problem
i want to user when click profile pass user to profile.html but problem i don't solve hem
If this is your path:
path('home', views.home, name="home"),
path('profile/<int:id>', views.profile_views, name="profile_views")
views.py:
def home(request):
return render(request, 'main-frond.html')
Related
i want create url when user click pass to profile page
++++ models
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
music = models.CharField(max_length=50)
skils = models.CharField(max_length=50)
search = models.CharField(max_length=50)
posts = models.CharField(max_length=50)
boi = models.TextField()
img = models.ImageField(upload_to="profile-img")
def __str__(self):
#return self.user or 'User'
return str(self.id)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
+++ views
def home(request):
return render(request, 'main-frond.html')
def profile_edit(request, id):
pro_edit = profile.objects.get(id=id)
if request.method == 'POST':
user_form = User_Form(request.POST, request.FILES, instance=pro_edit)
if user_form.is_valid():
user_form.save()
return redirect('profile_views')
else:
user_form = User_Form(instance=pro_edit)
context = {'user_form' : user_form}
return render(request, 'profile_edit.html', context)
+++url
path('home', views.home, name="home"),
path('profile/<int:id>/edit', views.profile_edit, name="profile_edit")
+++ html
profile
django give me problem
Reverse for 'profile_views' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<id>[0-9]+)\\Z']
i want create url when user click pass to profile page
As a newbie to Django, all things are still not clear to me. I'm having some issues while working on my project. Whenever I register as a new student, it lets me to login. But I cannot upload profile picture. It throws me an error:
ValueError at /account_settings/
The 'profile_pic' attribute has no file associated with it.
When I login as an admin and want to see the new student, I just see a blank space, not the new student. Here is the screenshot of my admin view:
If I see from admin page, there is also a blank space. Here is admin page view:
I have to manually create a student and an user from admin page, and make relationship between them. Please anyone explain me what actually happens behind the scenario. I'm a noob, I'll be grateful if anyone kindly makes it clear for me. Thanks in advance.
Here is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.name)
class Tag(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Books(models.Model):
CATEGORY = (
('Physics', 'Physics'),
('Chemistry', 'Chemistry'),
('Mathematics', 'Mathematics'),
)
name = models.CharField(max_length=200)
author = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Issue(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
student = models.ForeignKey(Student, null=True, on_delete= models.SET_NULL)
book = models.ForeignKey(Books, null=True, on_delete= models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return self.book.name
Here is my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms import ModelForm
from .models import Issue
from .models import Student
class IssueForm(ModelForm):
class Meta:
model = Issue
fields = '__all__'
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class StudentForm(ModelForm):
class Meta:
model = Student
fields = '__all__'
exclude = ['user']
It's my decorators.py file:
from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(func):
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
else:
return func(request, *args, **kwargs)
return wrapper
def allowed_user(allowed_roles=[]):
def decorator(func):
def wrapper(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page.')
return wrapper
return decorator
def admin_only(func):
def wrapper(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'Student':
return redirect ('user_page')
else:
return func(request, *args, **kwargs)
return wrapper
It's my registration, login and account_setting method in views.py file:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.urls import reverse
from .models import *
from .forms import IssueForm, CreateUserForm, StudentForm
from .filters import IssueFilter
from .decorators import unauthenticated_user, allowed_user, admin_only
#unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
user =form.save()
username = form.cleaned_data.get('username')
group = Group.objects.get(name = 'Student')
user.groups.add(group)
Student.objects.create(
user = user
)
messages.success(request, 'Account successfully created for ' + username)
return redirect ('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
#unauthenticated_user
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
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 ('home')
else:
messages.info(request, 'Username or Password is incorrect')
return render(request, 'accounts/login.html')
#login_required(login_url='login')
#allowed_user(allowed_roles=['Student'])
def accountSettings(request):
user = request.user.student
form = StudentForm(instance=user)
if request.method == 'POST':
form = StudentForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'accounts/account_settings.html', context)
And my account_seetings.html template:
{% extends 'accounts/main.html' %}
{% load static %}
{% block content%}
<style>
.profile-pic{
max-width: 300px;
max-height: 300px;
margin: 0 auto;
border-radius: 70%;
}
</style>
<br>
<div class="row">
<div class="col-md-3">
<div class="card card-body">
<a class="btn btn-warning" href="{% url 'home' %}"> ← Back to Profile</a>
<hr>
<img class="profile-pic" src="{{request.user.student.profile_pic.url}}">
</div>
</div>
<div class="col-md-9">
<div class="card card-body">
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input class="btn btn-primary" type="submit" name="Update Information">
</form>
</div>
</div>
</div>
{% endblock %}
It should be noted that I have two groups in admin page. These are Student and Admin.
I started learning Django about a month ago and just finished Django for Beginners by William Vincent. The book ends with Ch.15: Comments and shows how the admin can add comments to posts.
Q: Can someone, please, show me or point me in the right direction as to how I can let registered users also add comments to posts? Is there perhaps a 3rd party app for that?
What I have so far:
Models:
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/', null=True, blank=True, height_field=None, width_field=None)
upload = models.FileField(upload_to='files/', null=True, blank=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comment')
comment = models.CharField(max_length=140)
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(), on_delete=models.CASCADE,
)
def __str__(self):
return self.comment
def get_absolute_url(self):
return reverse('article_list')
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Article
fields = ('title', 'body', 'image', 'upload')
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('comment', 'author')
Views:
class ArticleListView(LoginRequiredMixin, ListView):
model = Article
template_name = 'article_list.html'
comment_form = CommentForm
login_url = 'login'
class ArticleDetailView(LoginRequiredMixin, DetailView):
model = Article
template_name = 'article_detail.html'
login_url = 'login'
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
model = Article
fields = ('title', 'body', 'image', 'upload')
template_name = 'article_edit.html'
login_url = 'login'
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
if obj.author != self.request.user:
raise PermissionDenied
return super().dispatch (request, *args, **kwargs)
class ArticleDeleteView(LoginRequiredMixin, DeleteView):
model = Article
template_name = 'article_delete.html'
success_url = reverse_lazy('article_list')
login_url = 'login'
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
if obj.author != self.request.user:
raise PermissionDenied
return super().dispatch (request, *args, **kwargs)
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = Article
form_class = PostForm
template_name = 'article_new.html'
login_url = 'login'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
URLs:
urlpatterns = [
path('<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_edit'),
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
path('<int:pk>/delete/', ArticleDeleteView.as_view(), name='article_delete'),
path('', ArticleListView.as_view(), name='article_list'),
path('new/', ArticleCreateView.as_view(), name='article_new'),]
Thank you for your attention.
Solved. In my views.py I added the following function:
def add_comment(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.article = article
comment.save()
return redirect('article_detail', pk=article.pk)
else:
form = CommentForm()
return render(request, 'add_comment.html', {'form': form})
Then the following .html file was added to templates:
add_comment.html
{% extends 'base.html' %}
{% block content %}
<h4>Add a Comment</h4>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock content %}
P.S.: Initially I was getting an ImportError: cannot import name 'add_comment' from 'articles.views'.
I thought it was a circular import problem and what worked for me was just getting the def add_comment indentation right.
I have trouble with protection against editing another user's profile and I don't have any idea how to solve this issue.
Ofcourse I know that I can do sth like this:
<a class="nav-item nav-link" href="{% url 'profile_change' user.pk %}">
or something similar.
But I don't know what i can do in situation when user write him/herself webadress. I mean situation when user with pk = 2, would write adress: "website address/profile/change/1"
Here is my models, views and urls:
#urls.py
urlpatterns = [
path('profile/', views.profile, name='profile'),
path('profile/list/', views.ProfileListView.as_view(), name='profile_changelist'),
path('profile/add/', views.ProfileCreateView.as_view(), name='profile_add'),
path('profile/change/<int:pk>/', views.ProfileUpdateView.as_view(), name='profile_change')
]
#views.py
class ProfileCreateView(CreateView):
model = Profile
form_class = ProfileForm
success_url = reverse_lazy('profile_changelist')
def form_valid(self, form, **kwargs):
form.instance.user = self.request.user
return super().form_valid(form)
class ProfileUpdateView(UpdateView):
model = Profile
fields = ('first_name', 'last_name', 'year')
success_url = reverse_lazy('profile_changelist')
#login_required
def profile(request):
if Profile.objects.filter(user=request.user.id).count() == 1:
return render(request, 'profiles/profile.html')
else:
return HttpResponseRedirect('add')
#models.py
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=100, null=True)
last_name = models.CharField(max_length=100, null=True)
year = models.IntegerField(choices=YEARS, default=1)
You must check what the user from request object is a editable user from parameters:
from django.http import Http404
class ProfileUpdateView(UpdateView):
model = Profile
fields = ('first_name', 'last_name', 'year')
success_url = reverse_lazy('profile_changelist')
def get(self, request, *args, **kwargs):
if not request.user.id == self.kwargs.get('pk'):
raise Http404
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
if not request.user.id == self.kwargs.get('pk'):
raise Http404
return super().post(request, *args, **kwargs)
I am new to Django.I want to create app that would enable selected users to login and then upload files that would latter be processed.
models.py
class Profile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
password = models.TextField(max_length=80,blank=True)
company = models.TextField(max_length=80, blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
class Document(models.Model):
uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE)
date_uploaded = models.DateTimeField(auto_now_add=True)
forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
company = forms.CharField()
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
malex.urls(application urls)
from malex.views import list
from malex.views import login
urlpatterns = [
url(r'^list/$', list, name='list'),
url(r'^login/$', login, name='login'),
]
project/urls
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^newp/', include('malex.urls')),
]
views.py
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(user=cd['user'],password=cd['password'],company=cd['company'])
if user is not None:
if user is active:
login(request,user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form=LoginForm()
return render(request,'account/login.html',{'form': form})
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
Now the login and upload operations are separated.
How to change my views and urls to have login first and upload latter?
Do I need to use Class based views with decorators?
create a custom login form and view.
use your localhost:8000 address as login template
(app) urlpatterns = [path('',views.loginview,name = 'login')]
(project) urlpatterns = [path('', include('malex.urls')),)]
extend your login template using {% block content %}{% endblock %}
use pass restrictions {% if request.user.is_authenticated %} in template or view to let them access upload section.