I send a html email to the users using the EmailMultiAlternatives and it worked, but the problem is in the email message the link is not working.
But when I tried doing <a href="http://127.0.0.1{% url 'add_your_details' user.username %}"> then it worked perfectly as I wanted.
template
<a href="{{ request.scheme }}://{{ request.get_host }}{% url 'add_your_details' user.username %}"
target="_blank">Add your details </a>
settings
ALLOWED_HOSTS = ['127.0.0.1']
I solved this by using the get_current_site method.
In views:
from django.contrib.sites.shortcuts import get_current_site
my_current_domain = get_current_site(request)
return {'domain':my_current_domain}
then in template
<a href="{{ request.scheme }}://{{ domain }}{% url 'add_your_details' user.username %}"
target="_blank">Add your details </a>
Related
Whenever i tried to view other people profile, it always return my own profile again, i don't really know what's wrong and i have tried calling request.user but it seems not to work
views.py
def UserProfile(request, username):
user = get_object_or_404(User, username=username)
profile = Profile.objects.get(user=user)
url_name = resolve(request.path).url_name
context = {
'profile':profile,
'url_name':url_name,
}
return render(request, 'userauths/profile.html', context)
urls.py main project
from userauths.views import UserProfile
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('userauths.urls')),
path('<username>/', UserProfile, name='profile'),
]
index.html
{% for creator in creators %}
<img class="avatar-img rounded-circle" src="{{creator.user.profile.image.url}}" alt="creators image" ></div>
<h5 class="card-title"><a href="{% url 'profile' creator.user %}">
{{creator.user.profile.first_name}} {{creator.user.profile.last_name}} {% if creator.verified %} <i class="bi bi-patch-check-fill text-info smsall" ></i> {% else %}{% endif %} </a></h5>
<p class="mb-2">{{creator.user.profile.bio}}</p></div>
{% endfor %}
I just fixed it now, in my profile.html, i am using {{request.user.profile.first_name}} to display the informations. I was supposed to use {{profile.first_name}} etc, and that was it.
Instead of this:
<a href="{% url 'profile' creator.user %}">
you should try:
<a href="{% url 'profile' creator.user.username %}">
From the presumably working statement get_object_or_404(User, username=username) I assume that username is a field (hopefully, unique) of the User. So you should pass it onto the URL, not the entire User model.
I am new to django and I am trying to build web site for my friend how makes handmade lamps.
My problem is that I have 3 different models that contains different types of lamps, and I want to get access to certain picture in any of this 3 models and display a picture and description on the other page,but it shows only some pictures from first model and for others throws an error.
this is my html and views.py codes.
{% for q in project1.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' q.pk%}">
<img src="{{q.image.url }}">
</a>
</div>
{%endfor%}
{% for e in project2.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' e.pk %}">
<img src="{{e.image.url}}">
</a>
</div>
{%endfor%}
{% for s in project3.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' s.pk %}">
<img src="{{s.image.url}}">
</a>
</div>
{%endfor%}
enter image description here
def project_detail(request, pk):
project = (LampType1.objects.get(pk=pk), LampType2.objects.get(pk=pk), LampType3.objects.get(pk=pk))
context = {
'project': project,
}
return render(request, 'project_detail.html', context)
Edward this might be happening because you are passing the same id/pk to all the models and you got a picture from the first model and not from the other because an object with that id/pk does not exit in the other models.
To check, register your models in the admin and check weather an object with that particular id exit or not.
check if these steps have been done
model
class LampType1(models.Model):
title = models.CharField(max_length=40)
description = models.TextField()
image = models.ImageField(upload_to='media')
#not
#image = ImageField(upload_to='media')
settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR,'media')
urls.py
from django.conf.urls.static import static
from django.conf import setting
urlpatterns = [.....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.contrib import admin
html
{% for p in project %}
<img src="{{ p.image.url }}">
{% endfor %}
I am working with Django 1.11.5 and logging-in and validating users via Social Auth.
The user authentication, log-in and logoff are working as expected in 12/13 of my templates. All my templates extend my navbar and footer base.html template.
In 'base.html' I have the following code for the navbar:
{% if user.is_authenticated %}
<li class="nav-item">
<span class="nav-link" id="user-name">{{ request.user.username }}</span>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Logoff</a>
</li>
{% else %}
<li class="nav-item log-in-link">
<a class="btn btn-primary nav-link log-in" href="{% url 'social:begin' 'google-oauth2' %}"><span>Log-In <i class="fa fa-google-plus" aria-hidden="true"></i></span></a>
</li>
{% endif %}
Now, this navbar code works properly in 12/13 of my templates. It is only for 1 template/view/URL where the user is not authenticated.
I have tried debugging by printing out the user name and information in the template giving me errors but it looks like the user is getting logged out when reaching that template via its URL and view.
I am totally lost.
Could someone point out things I can check/do to debug and locate the source of this logoff error? I can provide the relevant code if needed.
views.py code
def details_request(request, request_data_ID):
data_request_object = DatasetRequest.objects.get(pk=request_data_ID)
user_ID = data_request_object.user.username
has_attributes = False
request_data_attrs = []
if len(data_request_object.attr_names) > 0:
if len(data_request_object.attr_names['names']) > 0:
has_attributes = True
for idx, attr_names in enumerate(data_request_object.attr_names['names']):
request_data_attrs.append([attr_names,
data_request_object.attr_names['descriptions'][idx],
data_request_object.attr_names['types'][idx]])
data_request_detail_template = {
'dataset_request_title': data_request_object.dataset_title,
'dataset_request_description': data_request_object.dataset_description,
'dataset_votes': data_request_object.dataset_votes,
'dataset_date': data_request_object.created_date.strftime("%Y-%m-%d"),
'request_data_ID': request_data_ID,
'has_attributes': has_attributes,
'request_attrs': request_data_attrs,
'user': user_ID,
'is_completed': data_request_object.is_completed
}
data_comment_object = Comments.objects.filter(request_dataset_FK=data_request_object).order_by("-comment_votes")
if len(data_comment_object) > 0:
comment_list = []
for comment_object in data_comment_object:
if comment_object.isComment:
comment_list.append([comment_object.comment, comment_object.created_date.strftime("%Y-%m-%d"), comment_object.comment_votes, comment_object.pk, comment_object.user.username])
data_request_detail_template['comments'] = comment_list
return render(request, "detail_requests.html", data_request_detail_template)
You are specifying:
user_ID = data_request_object.user.username
and put it into context under user key.
In template you have {% if user.is_authenticated %} which means that you are trying to access missing attribute is_authenticated of user.username which always evaluates to False.
Just started learning Django and creating my first site. Everything is working correctly, users can be created, logged in, and logged out, but an unusual issue is occurring and I'm not sure where to start troubleshooting.
After logging in, the url redirects to /home/%username%/. This works. However, I am able to remove the %username% of the current user, input any combination of strings, and still be directed to the user's homepage.
Can someone explain why this is and how to ensure the URL throws a 404 error if it is not /home/%currentlyloggedinusername%/ or another site in urls.py? Here is my code:
urls.py
from django.conf.urls import url
from . import views
from . import views_accounts
urlpatterns = [
url(r'^index/', views.index, name='index'),
url(r'^home/share/(?P<event_id>[0-9]+)', views.share, name='share'),
url(r'^home/(?P<username>[-\w]+)', views.home, name='home'),
url(r'^accounts/logout', views_accounts.logout_view, name='logout_view'),
url(r'^accounts/create_account', views_accounts.create_account, name='create_account'),
url(r'^accounts/login', views_accounts.user_login, name='login'), ]
views.py
#csrf_exempt
def index(request):
return render(request, 'index.html')
#csrf_exempt
#login_required(login_url='/accounts/login/')
def home(request, username):
# GET Meetup Event Info from all meetups the user
# has RSVP'd to and load JSON data into variable
# user = User.objects.get(username=username)
user = request.user.username
meetup_data = get_meetup_events(user)
# Load HTML template with Meetup data
context = {'meetup_data': meetup_data}
return render(request, 'home.html', context)
user_login.py
#csrf_exempt
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('/home/%s/' % username)
else:
return render(request, 'login.html')
Thanks!!
EDIT:
home.html:
{% extends 'base.html' %}
{% block main %}
<main class="container">
<!-- Create account navigation buttons to logout, log in to Facebook and Twitter, and Sync Meetup Data -->
<div class="social-buttons">
<a class="btn" href="#!">Import Meetup Events</a>
<a class="btn" href="{% url 'logout_view' %}">Logout</a>
<a class="btn" href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Facebook</a>
<a class="btn" href="{% url 'social:begin' 'twitter' %}?next={{ request.path }}">Twitter</a>
</div>
<!-- Create a card for each Meetup the user has RSVP'd to that displays the Meetup Group Name, the Event Name, a link to the event, and a link to post the event to Twitter -->
{% for items in meetup_data %}
<div class="card">
<div class="card-content">
<span class="card-title"> {{ items.group_name }} </span>
<img class="right" src="{{items.thumb_link}}" alt="">
<p>{{ items.event_name }}<br><br>
Event Details
</p>
</div>
<div class="card-action">
<a class="twitter-post" href="{%url 'share' items.event_id %}">
<span >Post To Twitter</span>
</a>
</div>
</div>
{% endfor %}
</main>
{% endblock %}
Because you're ignoring the username passed in the URL - you commented out the line where it uses it in the query - and you're getting it directly from request.user instead.
Note that this is the correct thing to do, because you don't want people accessing other users' home pages; so you should remove the username from the URL.
I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work.
What I have done is create a new application called nav and built some templatetags, like so,
from django import template
register = template.Library()
URL_PATTERNS = {
'home': (r'^/$',),
}
#register.tag
def nav_selection(parser, token):
try:
tag_name, nav_item = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return NavSelectionNode(nav_item[1:-1])
class NavSelectionNode(template.Node):
def __init__(self, nav_item):
self.nav_item = nav_item
def render(self, context):
if not 'request' in context:
return ""
import re
try:
regs = URL_PATTERNS[self.nav_item]
except KeyError:
return ''
for reg in regs:
if re.match(reg, context['request'].get_full_path()):
return "active"
return ''
In my template I do this
<ul id="navigation">{% load nav %}
<li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
<li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal & wolf</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
<li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
<li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
<li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
<li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
<li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal & wolf professional</a></li>
</ul>
yet the markup I get out in firebug is this in this example I am browsing the index page
<a class="" href="/home/">
So something is obviously failing but I cannot see where, can anyone help me please?
Some things to check:
Is the request object actually in your context? Are you passing it in specifically, or are you using a RequestContext?
Why are you defining regexes in your templatetags, rather than using the built-in reverse function to look them up in the urlconf?
Do the regexes here actually match the ones in the urlconf?
Have you included your home urlconf under the 'home' url somehow?