I'm getting a NoReverseMatch error:
NoReverseMatch at /
Reverse for 'post-detail' with arguments '(22, '')' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/$']
not sure how to fix this, here is some of the code :
urls.py
urlpatterns=[
path('', PostListView.as_view(), name='home'),
path('post/new/<slug:slug>/', views.create_post, name='post-create'),
path('post/<int:pk>/<slug:slug>/', views.post_detail, name='post-detail'),
path('like/<slug:slug>/', views.like, name='post-like'),
path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/<slug:slug>/delete/', views.post_delete, name='post-delete'),
path('search_posts/', views.search_posts, name='search_posts'),
feed models
models.py
class Post(models.Model):
description = models.TextField(max_length=255)
pic = models.ImageField(upload_to='path/to/img', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk, 'slug': self.user_name.profile.slug})
users models
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return "/users/{}".format(self.slug)
views.py
#login_required
def post_detail(request, pk, slug):
post = get_object_or_404(Post, pk=pk)
user = request.user
is_liked = Like.objects.filter(user=user, post=post)
if request.method == 'POST':
form = NewCommentForm(request.POST)
if form.is_valid():
data = form.save(commit=False)
data.post = post
data.username = user
data.save()
return redirect('post-detail', pk=pk, slug=slug)
else:
form = NewCommentForm()
return render(request, 'feed/post_detail.html', {'post':post, 'is_liked':is_liked, 'form':form})
home.html
{% extends "feed/layout.html" %}
{% load static %}
{% block cssfiles %}
{% endblock cssfiles %}
{% block searchform %}
<div class="container2">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<form class="searchbar" action="{% url 'search_posts' %}" method="get"">
<input class="postquery" name="p" type="text" autocomplete="off"/ placeholder="Search posts..">
<button id="search_btn" type="submit">
<i class="fa fa-search"></i>
</button>
</form>
</div>
{% endblock searchform %}
{% block content %}
<div class="container mt-7">
<div class="row">
<div class="col-xl-9 col-md-10 m-auto order-xl-2 mb-5 mb-xl-0">
{% for post in posts %}
<div class="card card-signin my-5">
<div class="card-body">
<img src="{{ post.user_name.profile.image.url }}" class="rounded-circle" width="30" height="30" alt="">
<a class="text-dark" href="{{ post.user_name.profile.get_absolute_url }}"><b>{{ post.user_name }}</b></a>
<br><small class="text-muted">Posted on {{ post.date_posted }}</small>
<br><br>
<p class="card-text text-dark">{{ post.description }}</p>
</div>
{% if post.pic %}
<img class="card-img-top" src="{{ post.pic.url }}" alt="">
{% endif %}
{% if post.tags %}
<br>
<p class="text-danger ml-3"><b>Tags: <i>{{ post.tags }}</i></b></p>
{% endif %}
<div class="card-footer">
<button class="btn btn-white mr-3 like" id="{{ post.id }}">
{% if post in liked_post %}
Unlike | {{post.likes.count}}
{% else %}
Like | {{post.likes.count}}
{% endif %}
</button>
<a class="btn btn-outline-info" href="{% url 'post-detail' post.id user.profile.slug %}">Comments | {{ post.details.count }}</a>
{% if post.user_name == user %}
<a class="btn btn-outline-info mr-0 float-right" href="{% url 'post-update' post.id user.profile.slug %}">Edit Post</a>
<a class="post_delete" href="{% url 'post-delete' post.id user.profile.slug %}">delete</a>
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock content %}
When i click on the home page link I get the error mentioned above , not sure what in this template is causing it ? any ideas ?
Related
how to create pagination in search.html ?
i want show 4 posts per page
what must I do now ?
any help please and thanks
this is my views.py :
class SearchView(ListView):
template_name = 'website_primary_html_pages/search.html'
paginate_by = 20
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
android_results = Android.objects.search(query)
linux_results = Linux.objects.search(query)
tech_results = Tech.objects.search(query)
mobile_results = Mobile.objects.search(query)
windows_results = Windows.objects.search(query)
# combine querysets
queryset_chain = chain(
android_results,
linux_results,
tech_results,
mobile_results,
windows_results
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Android.objects.none() # just an empty queryset as default
and here is my search.html :
{% for object in object_list %}
{% with object|class_name as klass %}
{% if klass == 'Mobile' %}
<div class="card-deck">
<div class="card mb-3" style="max-width: 800px;">
<div class="row no-gutters">
<div class="col-md-4">
</div>
<div class="col-md-8">
<div class="card-body">
<b>{{ object.name }}</b></h5>
<p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p>
</div>
<div class="card-footer">
<small class="text-muted" id="date_post_control">{{ object.post_date}}</small>
<small class="firstsmall"><a class="bg-orange" href="{% url 'mobile' %}" id="tag_name_control">هواتف</a></small>
</div>
</div>
</div>
</div>
</div>
<hr>
{% elif klass == 'Linux' %}
<div class="card-deck">
<div class="card mb-3" style="max-width: 800px;">
<div class="row no-gutters">
<div class="col-md-4">
</div>
<div class="col-md-8">
<div class="card-body">
<b>{{ object.name }}</b></h5>
<p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p>
</div>
<div class="card-footer">
<small class="text-muted" id="date_post_control">{{ object.post_date}}</small>
<small class="firstsmall"><a class="bg-orange" href="{% url 'linux' %}" id="tag_name_control">لينكس</a></small>
</div>
</div>
</div>
</div>
</div>
<hr>
{% else %}
{% endif %}
{% endwith %}
{% empty %}
<div class='row'>
<div class='col-12 col-md-6 mx-auto my-5 py-5'>
<form method='GET' class='' action="{% url 'search' %}">
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
{% endfor %}
what i must add in html page and views.py ?
i want This display for example , like this example :
Page 2 of 3. next back
how to do this and thanks :)
Change object_list in your template to page_obj:
{% for object in page_obj %}
Correct field paginate_by in your SearchView:
class SearchView(ListView):
template_name = 'website_primary_html_pages/search.html'
paginate_by = 4
Add paginator at the bottom of your template, all the pages of such "search paginator" should have all the queries that you search had, for example:
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">Last</a>
{% endif %}
{% endif %}
I need some help when I create a user and user profile accordingly and when I try to access to any user by another user the request turns me on the request I work on not the real user, although, I'm using the slug to specify what the user I click on it maybe I can not explain what happens to me exactly for more explanation, please click on that video to show what I mean: https://www.youtube.com/watch?v=MzSo0ay2_Xk&feature=youtu.be
accounts app
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.template.defaultfilters import slugify
CHOICE = [('male', 'male'), ('female', 'female')]
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
slug = models.SlugField(max_length=100, unique=True, blank=True)
overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
city = models.CharField(max_length=20, blank=False)
phone = models.IntegerField(default=0, blank=True)
sex = models.CharField(max_length=10, default='male', choices=CHOICE)
skill = models.CharField(max_length=100, default='You have no skills yet')
logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super().save(*args, **kwargs)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(receiver=create_profile, sender=User)
view.py
class ViewProfile(UpdateView):
queryset = UserProfile.objects.all()
template_name = 'accounts/profile.html'
form_class = UpdateInfoForm
slug_field = 'slug'
slug_url_kwarg = 'user_slug'
def get_success_url(self):
return reverse_lazy('accounts:view_profile', kwargs={'user_slug': self.request.user.userprofile.slug})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user_prof = UserProfile.objects.get(user=self.request.user)
context['user_prof'] = user_prof
context['get_favourite'] = User.objects.get(username=self.request.user.username).favorite.all()
return context
def form_valid(self, form):
form.instance.user_slug = self.request.user.userprofile.slug
self.object = form.save()
return super().form_valid(form)
profile.html
{% extends 'base.html' %}
{% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %}
{% block body %}
<!-- User Profile Section -->
{% if user.is_authenticated %}
<div class="profile">
<div class="container-fluid">
<div class="col-md-1">
<div class="thumbnail">
<div class="row">
<div class="col-xs-12">
<!-- Profile View Section -->
<div class="logo-image text-center">
{% if user.userprofile.logo %}
<div class="my-image">
{% if request.user.username == user.userprofile.slug %}
<a href="{% url 'accounts:user_image' user.userprofile.slug %}">
<img class="img-responsive" src="{{ user.userprofile.logo.url }}">
</a>
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
{% endif %}
</div>
{% else %}
{% load static %}
<div class="my-image">
<img class="img-responsive img-thumbnail" src="{% static 'index/images/default-logo.jpg' %}">
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
</div>
{% endif %}
<h4>{{ user.first_name }} {{ user.last_name }}</h4>
</div>
</div>
<div class="col-xs-12">
<div class="caption">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Overview</li>
<li role="presentation" class="">Personal Information</li>
<li role="presentation" class="">Skills</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Information Sections -->
<div class="col-md-8 col-md-offset-3 information">
<div class="overview show" id="overview">
<h2 class="line">Overview</h2>
<p class="lead">{{ user.userprofile.overview }}</p>
<a data-placement="bottom" title="update overview" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".overview_info"></a>
</div>
<div class="personal-info" id="personal-information">
<h2 class="line">Personal Information</h2>
<p class="lead">City: {{ user.userprofile.city }}</p>
<p class="lead">Phone Number: 0{{ user.userprofile.phone }}</p>
<p class="lead">Sex: {{ user.userprofile.sex }}</p>
<a data-placement="bottom" title="update personal information" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".personal_info"></a>
</div>
<div class="skill" id="my-skills">
<h2 class="line">Skills:</h2>
<p class="lead">{{ user.userprofile.skill }}</p>
<a data-placement="bottom" title="update skills" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".skills"></a>
</div>
</div>
<!-- get all questions -->
{% if user_prof.userasking_set.all %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">All Questions You Asked</h2>
{% for questions in user_prof.userasking_set.all %}
<p>{{ questions.title }}</p>
{% endfor %}
</div>
{% endif %}
<!-- get favourites -->
{% if get_favourite %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">Favourites</h2>
{% for fav in get_favourite %}
<p>{{ fav.title }}</p>
{% endfor %}
</div>
{% endif %}
</div>
{% include 'accounts/information_form.html' %}
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}
self.request.user refers to the currently logged in user. That is why you are getting the same result for all users.
To get what you want, you need to make the following change in your views:
user_prof = UserProfile.objects.get(pk=self.kwargs['pk'])
But also, I'm not sure why you are using an UpdateView when you simply want to display objects? You should use TemplateView instead.
Right, am struggling with my blog app when trying to render some logic through the template view. So the idea is to render a one time only button for the newly authenticated users that do not have a post published and after the user has published its first post the button will be rendered within a for loop so he/she'll be able to create/delete a new one from there.
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
context = {'title': 'Blog', 'posts': posts}
return render(request, 'app_blog/blog.html', context)
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=100, null=True)
content = models.TextField(null=True)
date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
blog.html
{% block content %}
{% if request.user not in posts|last %}
<div class="container" style="float: left;">
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' user.id %}"><h5>C'mon {{ request.user.username }}, don't be shy! Create Your First Blog Post!</h5></a>
</div>
{% endif %}
<br>
<br>
{% for post in posts %}
<br>
<div class="container">
<article class="media content-section">
<img class="rounded-circle account-img" src="{{ post.author.profile.image.url }}" alt="Image could not be uploaded!">
<div class="card-body media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'app_blog:blog_user_detail' post.id %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"d F Y" }}</small>
</div>
<div class="article-metadata">
{% if post.author == request.user %}
<div>
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' post.id %}">Create New Post</a>
<a class="btn btn-primary btn-danger btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_delete' post.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2><a class="article-title" href="{% url 'app_blog:blog_detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content|safe }}</p>
</div>
</article>
</div>
<br>
{% endfor %}
{% endblock %}
So, again, end question would be about what sort of conditionals to use here:
{% if request.user not in posts|last %}
Thanks.
Not quite sure I fully understand but I will suggest something. A user who was a saved post should not see that button? If so, maybe something like this would work:
{% if request.user not in posts.authors.all %}
EDIT original solution won't work. posts is a queryset object
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
new_user = len(posts.filter(author=request.user)) == 0
context = {'title': 'Blog', 'posts': posts, 'new_user': new_user}
return render(request, 'app_blog/blog.html', context)
blog.html (just the condition)
{% if new_user %}
I think this is very easy problem but I don't know what's wrong.
I reserved the error.
It says :
Exception Type: NoReverseMatch
Exception Value: Reverse for 'post_publish' with keyword arguments
'{'pk': ''}' not found. 1 pattern(s) tried:
['\^post/\(\?P(?P[^/]+)\\d\+\)/publish/\$$']
Exception
Location: C:\Users\umts\lib\site-packages\django\urls\resolvers.py in
_reverse_with_prefix, line 622
can you guys help me to solve these problems?
urls.py
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
path(r'^drafts/$', views.post_draft_list, name='post_draft_list'),
path(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'),
path(r'^post/(?P<pk>\d+)/remove/$', views.post_remove, name='post_remove'),
path(r'^post/(?P<pk>\d+)/comment/$', views.comment_add, name='comment_add'),
path(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'),
path(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'),
]
I'll show only 'comment add' code
views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
# comment 더하기
def comment_add(request, pk):
post=get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form=CommentForm()
return render(request, 'blog/post_detail.html') #, {'form':form})
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% else %}
<!--버튼은 디폴트값, 기능은 post_publish-->
<a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}">
Publish
</a>
<!--버튼은 디폴트값, 기능은 post_edit-->
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}">
<span class="glyphicon glyphicon-pencil">
</span>
</a>
<!--버튼은 디폴트값, 기능은 post_remove-->
<a class='btn btn-default' href="{% url 'post_remove' pk=post.pk %}">
<span class="glyphicon glyphicon-remove">
</span>
</a>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
<!--Comment 입력창-->
<hr>
<form action="{% url 'comment_add' pk=post.pk %}" method="POST" class="comment-form">
{% csrf_token %}
<input type="text" name="text" placeholder="댓글 달기...">
</form>
<!--
<form class="post-form" method="POST">
{% csrf_token %}
<!--{{ form.as_p }}
<button type="submit" class="save btn btn-default">
Add comment
</button>
<input type="text" name="content" value="Add Comment">
</form>-->
<!-- 코멘트 보기 -->
<hr>
{% for comment in post.comments.all %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="comment">
<div class="date">
{{ comment.created_date }}
{% if not comment.approved_comment %}
<a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
<a class="btn btn-default" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a>
{% endif %}
</div>
{{ comment.author }}
<p>{{ comment.text|linebreaks}}</p>
</div>
{% endif %}
{% empty %}
<p>No Comments here yet</p>
{% endfor %}
{% endblock %}
You can ignore the Korean words. However, what I want to make is add comment.
I am trying to implement a typical url in my django project however i keep getting the error meassage. I have checked my urls, views and html code where i have passed in the KWARGS. I have no clue what went wrong here please help?
The home.html uses user_profile_detail in the template
userprofile/home.html
<div class="sidebar-fixed position-fixed side_nav_bar ">
<a class="logo-wrapper waves-effect">
<img src="/" class="img-fluid" alt="">
</a>
<div class="list-group list-group-flush">
**<a href="{% url 'userprofile:dashboard' user_profile_detail.slug %}" class="list-group-item {% if request.path == dashboard %}active{% endif %} waves-effect">
<i class="fa fa-pie-chart mr-3"></i>Dashboard
</a>**
<a href="{% url 'userprofile:profile' user_profile_detail.slug %}" class="list-group-item {% if request.path == profile %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-user mr-3"></i>Profile</a>
<a href="{% url 'userprofile:watchlist' user_profile_detail.slug %}" class="list-group-item {% if request.path == watchlist %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-eye mr-3" aria-hidden="true"></i>WatchList</a>
<a href="{% url 'userprofile:blog' user_profile_detail.slug %}" class="list-group-item {% if request.path == blog %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-book mr-3" aria-hidden="true"></i>My Blogs</a>
<a href="{% url 'userprofile:history' user_profile_detail.slug %}" class="list-group-item {% if request.path == history %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-history mr-3" aria-hidden="true"></i>My Browsing History</a>
</div>
</div>
MODELS.PY
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
VIEWS.PY
def dashboard_view(request, slug):
userprofile = Profile.objects.get(slug=slug)
user_viewed_object = userprofile.objectviewed_set.first()
user_blog = userprofile.userblog_set.first()
user_watchlist = userprofile.watchlist_set.first()
context = {
'user_profile_detail': userprofile,
'user_blog': user_blog,
'user_watchlist': user_watchlist,
'user_viewed_object': user_viewed_object,
'page_name': "Dashboard"
}
print(userprofile.slug)
return render(request, 'userprofile/home.html', context)
def profile_view(request, slug):
user_profile_detail = Profile.objects.get(slug=slug)
if request.method == 'POST':
form = ProfileForm(request.POST or None, request.FILES, instance=user_profile_detail)
if form.is_valid():
print(form)
form.save(commit=False)
user_profile_detail = request.user
form.save()
return HttpResponseRedirect('/')
context = {
'profile': user_profile_detail,
'page_name': 'Profile',
'form': form
}
return render(request, 'userprofile/profile.html', context)
URLS.PY
app_name = 'userprofile'
urlpatterns = [
path('<slug:slug>', dashboard_view, name="dashboard"),
path('<slug:slug>/user_profile/', profile_view, name='profile'),
path('<slug:slug>/watchlist/', watchlist_view, name='watchlist'),
path('<slug:slug>/blog/', userblog_view, name="blog"),
path('<slug:slug>/history/', user_history, name="history"),
]
ERROR MESSAGE:
NoReverseMatch at /profile/jacklit/user_profile/
Reverse for 'dashboard' with arguments '('',)' not found. 1 pattern(s) tried: ['profile\\/(?P<slug>[-a-zA-Z0-9_]+)$']
profile.html
{% extends 'userprofile/dashboard.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container-fluid mt-5">
{% include 'userprofile/dashboard_head.html' %}
{% include 'userprofile/large_center_modal.html' %}
<div class="card">
<h2 class="my-3 mx-3"><i class="fa fa-user mr-3" aria-hidden="true"></i>My Profile</h2>
<hr >
<div class="row my-5 mx-1">
<div class="col-3 text-center pl-3">
{% if profile.profile_picture %}
<img src="{{ profile.profile_picture.url }}" alt=""
class="img-fluid z-depth-1-half rounded-circle">
{% endif %}
<div style="height: 10px"></div>
<p class="title mb-0">{{ profile.first_name }} {{ profile.last_name }}</p><br>
<p class="title mb-0" style="font-size: 13px">{{ profile.role }}</p><br>
<p class="title mb-0"><b>Joined: </b>{{ profile.joined }}</p><br><br>
{% if request.user == profile.user %}
Edit Profile
{% endif %}
</div>
<div class="col-9">
<h3><u>Biography</u></h3>
<h6>{{ profile.biography }}</h6>
<hr>
<h6><i class="fa fa-envelope mr-3" aria-hidden="true"></i>Email Address: {{ profile.email }}</h6>
<h6><i class="fa fa-phone mr-3" aria-hidden="true"></i>Office Number:{{ profile.office_number }}</h6>
<h6><i class="fa fa-mobile-phone mr-3" aria-hidden="true"></i>Phone Number: {{ profile.phone_number }}</h6>
<br><br>
<h3><u>Contact Information</u></h3>
<h6>Email: {{ profile.email }}</h6>
<h6>Office: {{ profile.office_number }}</h6>
<h6>Phone: {{ profile.phone_number }}</h6><br><br>
<h3><u>Social Medias</u></h3>
<h6><i class="fa fa-google-plus mr-3"></i>Google Plus:</h6>
<h6><i class="fa fa-facebook mr-3"></i>Facebook: </h6>
<h6><i class="fa fa-twitter mr-3"></i>Twitter: </h6>
<h6><i class="fa fa-linkedin mr-3"></i>LinkedIn: </h6>
</div>
</div>
</div>
</div>
{% endblock %}
Large_center_Modal.html
<form action="{% url 'userprofile:profile' user_profile_detail.slug %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Update my Profie</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body">
<div class="">
<div class="col-10">{{ form | crispy }}</div>
</div>
</div>
<!--Footer-->
<div class="modal-footer">
<button type="submit" class="btn btn-outline-info waves-effect">Update</button>
</div>
</div>
<!--/.Content-->
</div>
</div>
</form>
Your context dict has profile key: 'profile': user_profile_detail,. So in template you should use profile instead of user_profile_detail:
"{% url 'userprofile:dashboard' profile.slug %}"