Django URLs Reverse working but not updating my URL - django

I'm new to Django 4.0.4.
I'm trying to use reverse in model to dynamically change the url without affecting other branch not affecting.
url.py:
urlpatterns = [
path('', home_view, name='home'),
path('products/', product_list, name='product_list'),
path('products/<int:myid>/', dynamic_lookup_view, name='product-detail'),
path('admin/', admin.site.urls),
]
models.py
def get_absolute_url(self):
return reverse("product-detail", kwargs={"myid": self.id})
html
<p>
{{instance.id}} {{instance.title}}
</p>
Output(working):
enter image description here
enter image description here
Problem:
when i change root url for dynamic_lookup_view from 'products/int:myid/' to 'ps/int:myid/' in url.py
path('products/', product_list, name='product_list'),
path('p/<int:myid>/', dynamic_lookup_view, name='product-detail'),
There is no update in my instance.get_absolute_url in my html!?

Related

linking to the index.html to other html page in Django

I am new to the Django project.
I have been trying to create a situation in which, when a user presses the "Call us now" button in my nav-bar, it links them to other html pages (here: contact.html). How can I adjust what I have to achieve this?
Here are my files:
index.html
code: </ul><button class="btn btn-primary" type="button">call us now!</button></div>
views.py
from django.shortcuts import render
def index(request):
return render(request, 'jobs/index.html')
def contacts(request):
return render(request, 'jobs/contact.html')
in the urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', jobs.views.index, name='index'),
path('contact/', jobs.views.contacts, name='contact'),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)**
Change
href="contact.html"
To :
href="{% url 'contact' %}"

url getting doubled when opening a link from the home page.(django)

On clicking the 2nd item in the list it opens the events.html page but the url shows:
http://127.0.0.1:8000/events/events/ instead of http://127.0.0.1:8000/events
Home page code:
<li>HOME</li>
<li>EVENTS</li>
<li>REGISTERED TEAMS</li>
<li>CONTACT US</li>
Urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home_page, name='home_page'),
path('hackathon_register/',views.hackathon_register,name='hackathon_register'),
path('events/',views.events,name='events')
]
views.py
def events(request):
return render(request,'testapp/events.html',{})
From here, it seems that your code in urls.py of project is:
.......
urlpatterns = [
....
path('events/', include("app.urls")),
]
So correct this mistake either by changing project.urls or app.urls.

NoReverseMatch: Reverse for 'detail' not found. (Django Tutorials)

I've been going through the Django 2 tutorials.
I got the following error:
#Error:
#django.urls.exceptions.NoReverseMatch
#django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern #name.
Did some googling and confirmed that I had named my view 'detail' and also had my app named.
Below are my codes.
Please tell what is wrong. I am following the tutorial by heart, but this came up. How can I fix it keeping in par with the tutorials? Thank you!
Files:
mysite/polls/templates/polls/index.html
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
mysite/polls/urls.py
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
# ex: /polls/
# path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
mysite/polls/views.py
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
Additional:
mysite/urls.py
urlpatterns = [
path('polls/', include('polls.urls', namespace='polls')),
path('admin/', admin.site.urls),
]
You haven't defined any function named as 'detail' in views.py file.
Add this code.
def detail(request, id):
context = dict()
return render(request, 'polls/index.html', context)
You have to add results and vote function as well.
Remove the commented lines from your index.html file. Syntax in these lines is not right and Django tries to parse commented lines as well before rendering.
Remove from mysite/urls.py the namespace as you already specified app's app_name
or you can just remove the app_name and keep the namespace (not sure if this works in Django 2.0 as there are some tweaks in app_name and namespace in this version).

Django LOGIN_REDIRECT_URL failing when redirecting to the users profile

I'm using django-registration-redux and have most of it working. I'm trying to redirect to the user profile after login. Currently the URL for user profile is:
url(r'^user/(\w+)/$', views.profile, name='profile'),
...and the view for the profile is:
def profile(request, username):
user = get_object_or_404(User, username=username)
products = Product.objects.filter(user=user)
if not request.user == user:
return render(request, 'no.html')
else:
return render(request, 'profile.html', {'user':user,'products': products})
I've added LOGIN_REDIRECT_URL = 'profile' to settings.py but am getting the error:
Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['user/(\\w+)/$']
I've gone around this so many times I'm totally confused. I could simply set LOGIN_REDIRECT_URL = 'home' and be done with it, but then I wouldn't have gotten past this error. Do I need to create a different view for this?
EDIT:
If I set LOGIN_REDIRECT_URL to 'home' or 'products' or any other URL it works - just not for 'profile'. Here's my urls.py:
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^designers/', views.DesignersView.as_view(), name='designers'),
url(r'^subscribe/$', views.subscribe, name='subscribe'),
url(r'^products/$', views.products, name = 'products'),
url(r'^product/$', ProductListView.as_view(), name='product_list'),
url(r'^user/(\w+)/$', views.profile, name='profile'),
url(r'post_url/', views.post_product, name='post_product'),
url(r'^([0-9]+)/$', views.detail, name = 'detail'),
url(r'^like_product/$', views.like_product, name='like_product' ),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='product-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='product-delete'),
]
I'm still searching - just not finding a solution, yet.
Finally found a way to do this. I created a login view in my views.py:
from django.contrib.auth.views import LoginView
class LoginView(LoginView):
def get_success_url(self):
return reverse('profile', args=[self.request.user.username])
Also added this to my urls.py to reflect the new view:
url(r'^accounts/login/$', LoginView.as_view(), name='login'),
Removed LOGIN_REDIRECT_URL from settings.py and it worked.
Your regex url isn't correct. Change:
url(r'^user/(\w+)/$', views.profile, name='profile'),
To
url(r'^user/(?P<username>[\w\-]+)/$', views.profile, name='profile'),

Django can't find redirect url when authenticating user

I am trying to login protect some of my pages, including my dashboard. Here is the view for my dashboard at the root of my site: sitename.com/
#login_required
def index(request):
print(request.session['user_email'])
context_dict = {}
return render(request, 'dashboard/index.html', context_dict)
My project url file:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^job/', include('job.urls')),
url(r'^welcome/', include('welcome.urls')), //the app for logging in
url(r'^$', include('dashboard.urls')), //main dashboard app
# s
]
My dashboard app url file:
urlpatterns = [
url(r'$', views.index, name='index'),
url(r'^signup/$', views.signup, name='signup'),
url(r'^login/$', views.auth_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
]
When I try and logout and then go to / I get a message saying that http://127.0.0.1:8000/welcome?next=/ doesn't match any urls in my project urls file. So the login check is working, it just can't figure out the url when the GET variable next is set.
As you are using django's default login from contrib.auth, try passing next as an extra_context dict.
url(r'^login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html', 'extra_context': {'next':'/'}})
Another solution is to specify login url in login_required decorator itself
#login_required(login_url='/login/')
def index(request):
print(request.session['user_email'])
context_dict = {}
return render(request, 'dashboard/index.html', context_dict)
Let know if this solve your issue. HTH :)
I finally got it to work. This is my routes:
Welcome app routes (app for logging in/out)
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup/$', views.signup, name='signup'),
url(r'^/login/$', views.auth_login, name='login'),
url(r'^/logout', views.user_logout, name='logout'),
]
Main routes for the entire project:
urlpatterns = [
url(r'^welcome', include('welcome.urls')),
url(r'^', include('dashboard.urls')),
]
Now I don't get any errors with the next variable in the url:
http://127.0.0.1:8000/welcome?next=/
I have a javascript file grabbing the value of next and redirecting to it if the user logs in successfully. *I use ajax to authenticate the user.