I'm getting a NoReverseMatch error at login/ , when it redirects to profile.html , if i login through other pages where it redirects to another page, then it works fine , but when I click on the login button which redirects to the profile.html page , I get the NoReverseMatch error. Do you know what is wrong in this code ? , I can't seem to find the fault.
NoReverseMatch Error
profile.html
<div class="main-content">
<div class="container mt-2">
<div class="row">
<div class="col-xl-8 col-md-10 m-auto order-xl-2 mb-5 mb-xl-0">
<div class="card card-profile shadow">
<div class="row justify-content-center">
<div class="col-lg-3 order-lg-2">
<div class="card-profile-image">
<img
src="{{ u.profile.image.url }}"
class="rounded-circle"
width="160px"
height="160px"
/>
</a>
</div>
</div>
</div>
<div
class="card-header text-center border-0 pt-8 pt-md-4 pb-0 pb-md-4"
></div>
<div class="card-body pt-0 pt-md-4">
<div class="row">
<div class="col">
<div class="card-profile-stats d-flex justify-content-center mt-md-5"
>
<div>
<span class="heading">{{ u.profile.friends.count }}</span>
{% if request.user == u %}
<span class="description"
>Friends</span
>
{% else %}
<span class="description">Friends</span>
{% endif %}
<span class="heading">{{ post_count }}</span>
<span class="description"
><a href="{% url 'user-posts' u.username %}"
>Posts</a
></span
>
</div>
</div>
</div>
</div>
<div class="text-center">
<h3 class="user_link">{{ u }}</h3>
<p>{{ u.profile.bio }}</p>
<hr class="my-2" />
{% if request.user == u %}
<a class="btn btn-info edit_btn" href="{% url 'edit_profile' %}"
>Edit Profile</a
>
{% else %} {% if button_status == 'not_friend' %}
<small
><a
class="btn btn-secondary"
href="/users/friend-request/send/{{ u.username }}"
>Add Friend</a
></small
>
{% elif button_status == 'friend_request_sent' %}
<small
><a
class="btn btn-warning"
href="/users/friend-request/cancel/{{ u.username }}"
>Cancel Request</a
></small
>
{% elif button_status == 'friend_request_received' %}
<small
><a
class="btn btn-secondary mr-2"
href="/users/friend-request/accept/{{ u.username }}"
>Accept Request</a
></small
>
<small
><a
class="btn btn-danger"
href="/users/friend-request/delete/{{ u.username }}"
>Reject Request</a
></small
>
{% else %}
<small
><a
class="btn btn-danger"
href="/users/friend/delete/{{ u.username }}"
>UnFriend</a
></small
>
{% endif %} {% endif %}
</div>
</div>
</div>
</div>
</div>
views.py
#login_required
def my_profile(request, slug):
p = request.user.profile
you = p.user
sent_friend_requests = FriendRequest.objects.filter(from_user=you)
rec_friend_requests = FriendRequest.objects.filter(to_user=you)
user_posts = Post.objects.filter(user_name=you)
friends = p.friends.all()
artwork = Music.objects.all().order_by('-date_posted')
tracks = Music.objects.all()
# is this user our friend
button_status = 'none'
if p not in request.user.profile.friends.all():
button_status = 'not_friend'
# if we have sent him a friend request
if len(FriendRequest.objects.filter(
from_user=request.user).filter(to_user=you)) == 1:
button_status = 'friend_request_sent'
if len(FriendRequest.objects.filter(
from_user=p.user).filter(to_user=request.user)) == 1:
button_status = 'friend_request_received'
data = {
'music' : json.loads(serializers.serialize('json', Music.objects.all()))
}
context = {
'u': you,
'button_status': button_status,
'friends_list': friends,
'sent_friend_requests': sent_friend_requests,
'rec_friend_requests': rec_friend_requests,
'post_count': user_posts.count,
'artwork': artwork,
'tracks': tracks,
'data': json.dumps(data)
}
return render(request, 'users/profile.html', context)
Related
Trying to create an app that saves sales in different sateges for my team(similar to an ecommerce)
however the form to add the account info is not saving the data...
I review different options and use formset as well no changes.
model.py
TYPE=(
('delegated','Delegated'),
('not_delegated','Not Delegated')
)
class Account(models.Model):
agent_profile=models.ForeignKey(AgentProfile, on_delete= CASCADE)
account_name=models.CharField(max_length=120)
opp_type=models.CharField(max_length=20, choices=TYPE, default='not_delegated')
bp_id=models.IntegerField()
mdm_id=models.CharField(max_length=50, null=True,blank=True)
AM=models.CharField(max_length=50,null=True,blank=True)
def __str__(self):
return str(self.agent_profile)
forms.py
from django.forms import ModelForm
from .models import Account
class AccountForm(ModelForm):
class Meta:
model=Account
fields=[
#'agent_profile',
'account_name',
'opp_type',
'bp_id',
'mdm_id',
'AM'
]
views.py
def confirm_account_create_view(request):
form=AccountForm(request.POST or None)
context = {
"form": form
}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
instance=form.save(commit=False)
agent_profile, agent_profile_created = AgentProfile.objects.new_or_get(request)
if agent_profile is not None:
opp_type = request.POST.get('delegate_opp', 'not_delegated_opp')
instance.agent_profile = agent_profile
instance.opp_type = opp_type
instance.save()
request.session[opp_type + "_opp_id"] = instance.id
print(opp_type + "_opp_id")
else:
print("Please verify Form")
return redirect("opps:confirm")
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
return redirect("opps:confirm")
urls.py (main app)
path('orders/confirm/account', confirm_account_create_view, name='create_account'),
form page(HTML)
{% csrf_token %}
{% if next_url %}
{% endif %}
{% if opp_type %}
<input type='hidden' name='opp_type' value='{{ opp_type }}' />
{% endif %}
{{ form.as_p }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
confirm page(HTML)
{% extends "base.html" %}
{% load static %}
{% block content %}
{{ object.order_id }} --{{object.opp}}
<div class="pb-9 mb-7 text-center border-b border-black border-opacity-5">
<h2 class="mb-7 lg:mt-6 text-3xl font-heading font-medium">Confirm Info</h2>
</div>
<h2 class="mb-7 lg:mt-6 text-3xl font-heading font-medium">Account</h2>
<div class='row'>
<div class="flex items-center justify-between py-4 px-10 mb-3 leading-8 bg-white bg-opacity-50 font-heading font-medium rounded-3xl">
{% if not object.delegated_opp %}
{% url "create_account" as confirm_account_create_view%}
{% include 'accounts/form.html' with form=delegated_form ext_url=request.build_absolute_uri action_url=confirm_account_create_view opp_type='not_delegated_opp' %}
</div>
<div class="flex items-center justify-between py-4 px-10 mb-3 leading-8 bg-white bg-opacity-50 font-heading font-medium rounded-3xl">
{% elif not object.not_delegated_opp %}
{% url "create_account" as confirm_account_create_view%}
{% include 'accounts/form.html' with form=delegated_form ext_url=request.build_absolute_uri action_url=confirm_account_create_view opp_type='not_delegated_opp' %}
</div>
</div>
{%else%}
<div>
<h2 class="mb-7 lg:mt-6 text-3xl font-heading font-medium">Order summary</h2>
<div class="flex items-center justify-between py-4 px-10 mb-3 leading-8 bg-white bg-opacity-50 font-heading font-medium rounded-3xl">
<span>Subtotal</span>
<span class="flex items-center text-xl">
<span class="mr-2 text-base">$</span>
<span>{{object.opp.subtotal}}</span>
</span>
</div>
<div class="flex items-center justify-between py-4 px-10 mb-3 leading-8 bg-white bg-opacity-50 font-heading font-medium rounded-3xl">
<span>Discount</span>
<span class="flex items-center text-xl">
<span class="mr-2 text-base">$</span>
<span>{{object.discount}}</span>
</span>
</div>
<div class="flex items-center justify-between py-4 px-10 mb-14 leading-8 bg-white font-heading font-medium rounded-3xl">
<span>Total</span>
<span class="flex items-center text-xl text-blue-500">
<span class="mr-2 text-base">$</span>
<span>{{object.total}}</span>
</span>
</div>
<a class="inline-block w-full py-5 lg:py-3 px-10 text-lg leading-6 lg:leading-7 text-white font-medium tracking-tighter font-heading text-center bg-blue-500 hover:bg-blue-600 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 rounded-xl" href="#">Save Opp</a>
</div>
</div>
</div>
<div class="md:w-96"><a class="block py-5 px-10 w-full text-xl leading-6 font-medium tracking-tighter font-heading text-center bg-white hover:bg-gray-50 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 rounded-xl" href="#">Back to top</a></div>
</div>
</section>
{% endif %}
{% endblock content %}
I type AM by mistake instead of am at a model level and form level.
Once I changed it to :
am=models.CharField(max_length=50,null=True,blank=True)
It began to work properly
I'm trying to filter out the friends of a user and also the current logged in user from a "search_users" function, I've tried using exclude() but keep getting an error I'm not sure whats wrong. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html.
Error
views.py
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
context ={
'users': object_list
}
return render(request, "users/search_users.html", context)
search_users.html
{% extends "feed/layout.html" %} {% load static %}
{% block searchform %}
<form
class="form-inline my-2 my-lg-0 ml-5"
action="{% url 'search_users' %}"
method="get"
>
<input name="q" type="text" placeholder="Search users.." />
<button class="btn btn-success my-2 my-sm-0 ml-10" type="submit">
Search
</button>
</form>
{% endblock searchform %} {% block content %}
<div class="container">
<div class="row">
<div class="col-md-8">
{% if not users %}
<br /><br />
<h2><i>No such users found!</i></h2>
{% else %}
<div class="card card-signin my-5">
<div class="card-body">
{% for user_p in users %}
<a href="{{ user_p.profile.get_absolute_url }}"
><img
src="{{ user_p.profile.image.url }}"
class="rounded mr-2"
width="40"
height="40"
alt=""
/></a>
<a class="text-dark" href="{{ user_p.profile.get_absolute_url }}"
><b>{{ user_p }}</b></a
>
<small class="float-right">
<a
class="btn btn-primary mr-2"
href="/users/friend-request/send/{{ user_p.username }}"
>Add Friend</a>
</small>
<br/><br />
{% endfor %}
</div>
</div>
{% endif %}
</div>
<div class="col-md-4">
<div class="card card-signin my-5">
<a href="{{ request.user.profile.get_absolute_url }}"
><img
class="card-img-top"
src="{{ request.user.profile.image.url }}"
alt=""
/></a>
<div class="card-body">
<h5 class="card-title text-center">{{ request.user }}</h5>
<h6 class="text-center">
{{ request.user.profile.friends.count }}
<p class="text-muted">Friends</p>
</h6>
<p class="card-text text-center">{{ request.user.profile.bio }}</p>
</div>
</div>
</div>
</div>
{% endblock content %}
</div>
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)
I would have done like this :
object_list = User.objects\
.filter(username__icontains=query)\
.exclude(profile__friends__in=request.user.profile.friends.all())\
.exclude(id=request.user.id)
It should be
User.profile.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
You were getting an error earlier because you referred to the user object earlier and not the profile itself. User.profile gives the one to one related model profile instead.
You can read more about one to one relationships here. https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/
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've create a simple form to create and update the blogposts. After the creation of the update view happen something strange that I can't solve.
views.py
def createPost(request):
if request.method == "POST":
form = BlogPostForm(request.POST or None)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug_post = slugify(new_post.title)
new_post.save()
return redirect('post_list')
else:
form = BlogPostForm()
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
def updatePost(request, slug_post=None):
update_post = get_object_or_404(BlogPost, slug_post=slug_post)
form = BlogPostForm(request.POST or None, instance=update_post)
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
return redirect('post_list')
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
urls.py
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
]
post_list.html
<div class="row">
{% for post in post_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mb-3 shadow" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-4">
<img src="{{ post.header_image_link }}" class="card-img" alt="{{ post.title }}" style="height: 250px;">
</div>
<div class="col-md-8">
<div class="card-body">
<h4 class="card-title">{{ post.title }}</h4>
<p class="card-text">{{ post.description }}</p>
<p class="card-text my-0 py-0"><small class="text-muted"><strong>Published: </strong>{{ post.publishing_date|date }}</small></p>
</div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:"4" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"4" and not forloop.last %}<div class="card-deck">{% endif %}
{% empty %}
<div class="row justify-content-md-center my-3 mx-1 py-2 shadow bg-danger rounded">
<div class="col-md-auto">
<h1 class="text-center px-2 py-2" id="text-shadow">Empty list!</h1>
</div>
</div>
{% endfor %}
</div>
create_post.html
<form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group mb-4">
<div>{{ form.title }}</div>
<label for="id_title">
<span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.title.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.description }}</div>
<label for="id_description">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.description.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.contents }}</div>
<label for="id_contents">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.contents.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.header_image_link }}</div>
<label for="id_highlighted">
<span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.header_image_link.errors }}</small>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="form-inline mb-4 py-0">
<div class="input-group mx-1">
<label for="id_highlighted">{{ form.highlighted.label }}</label>
<div class="ml-1">{{ form.highlighted }}</div>
</div>
<div class="input-group mx-1">
<label for="id_draft">{{ form.draft.label }}</label>
<div class="ml-1">{{ form.draft }}</div>
</div>
</div>
<div class="form-group mb-4">
<label for="publishing_date_field">
{{ form.publishing_date.label }}
<small class="text-danger">{{ form.publishing_date.errors }}</small>
</label>
<div class="input-group date" data-target-input="nearest">
{{ form.publishing_date }}
<div class="input-group-append" data-target="#publishing_date_field" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<script>
$(function () {
$("#publishing_date_field").datetimepicker({
format: 'DD/MM/YYYY HH:mm',
});
});
</script>
</div>
<div class="form-group mb-4">
<div class="row justify-content-md-center py-4 border border-warning rounded">
<h5 class="text-justify px-3">Clicca sul tasto che segue per vedere l'elenco delle immagini. Potrai copiare il link all'immagine che ti interessa ed usarlo per creare l'immagine di testata o migliorare i contenuti del post.</h5>
<button type="button" class="btn btn-primary mt-2 mx-2" data-toggle="modal" data-target=".bd-example-modal-xl">Image list</button>
</div>
<div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-body">
{% for image in images_url_list %}
{% if forloop.first %}<div class="card-deck">{% endif %}
<div class="card mx-1 my-1" style="height: 100%; width: 300px;">
<img src="{{ image.file.url }}" class="card-img-top h-100" alt="{{ image.file.url }}" id="{{ image.id }}">
<div class="card-body">
<button class="btn btn-outline-primary btn-sm" type="button" onclick="CopyToClipboard('{{ image.id }}')">Copy URL</button>
</div>
</div>
{% if forloop.counter|divisibleby:"3" or forloop.last %}</div>{% endif %}
{% if forloop.counter|divisibleby:"3" and not forloop.last %}<div class="card-deck">{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<input type="submit" class="btn btn-info" value="Pubblica">
</div>
</div>
</div>
</form>
I have this error message if I try to create a new post with my form:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/blog/create-post/ Raised by:
blog.views.singlePost
As I said this happen after the creation of updatePost. If I comment the path of the single post path("blog/<str:slug_post>/", views.singlePost, name='single_post'), I can create a post whitout problems.
What I've wrong?
Move path("blog/<str:slug_post>/", views.singlePost, name='single_post') to the bottom of your list, below the update and delete paths.
urlpatterns = [
path("blog/", views.listPost, name='post_list'),
path("blog/create-post/", views.createPost, name='create_post'),
path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'),
path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'),
path("blog/<str:slug_post>/", views.singlePost, name='single_post'),
]
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 %}"