Here are the two views :
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
class sectionOfficer_home(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/index.html', {})
class sectionOfficer_main(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/404.html', {})
Here is my urls.py of the app sectionOfficer:
from django.urls import path
from .views import (sectionOfficer_home, sectionOfficer_main)
app_name= 'sectionofficer'
urlpatterns = [
path('', sectionOfficer_home.as_view(), name = "sectionofc"),
path('secmain', sectionOfficer_main.as_view(), name = "secmain")
]
And here is the global urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('sectionoffc', include('sectionofficer.urls')),
path('secmain', include('sectionofficer.urls')),
]
But it showing always the first view template for any different url. What is wrong here ? Help please.
Related
I think i tired everything in trying to solve this problem.
I'm getting a NoReverseMatch i understand its from my "urls" but that's basically it, I was using url() instead of path().at the end of it all i just made a mess of my code.
view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Topic as TopicModel
from .forms import TopicForms
# Create your views here.
def index(request):
""""the home page for learning app"""
return render(request,'learning_logs/index.html')
def topics(request):
topics = TopicModel.objects.order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html',context)
def topic(request, topic_id):
"""show a single topic ans all its entries"""
topic = TopicModel.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic':topic, 'entries': entries}
return render(request,'learning_logs/topic.html',context)
def new_topic(request):
"""add a new topic"""
if request.method != 'POST':
#no data submitted ; create a black form
form = TopicForms
else:
#POST data submited ; process data
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_log:topics'))
context = {'form': form }
return render(request,'learning_log/new_topic.html', context)
urls.py
#defins URL patterns for learning log
from django.conf.urls import url
from . import views
from django.urls import path
app_name = 'learning_log'
urlpatterns = [
#home page
path('', views.index, name ='index'),
#url(r'^$', views.index, name='index.html'),
#show topics
path('topics/',views.topics, name ='topics'),
# url(r'^topics/$',views.topics, name='topics.html'),
path('topics/<topic_id>',views.topic, name = 'topic'),
#url(r'^topics/(?P<topic_id>\d+)\$',views.topic,name='topic.html'),
path('topics/',views.new_topic, name = 'new_topic'),
#url(r'^topics/$',views.new_topic, name='new_topic.html'),
]
main urls.py
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls')),
path('admin/',admin.site.urls),
]
please anything I'm doing wrong plus any books or tutorials i can read because i think the book im using is outdated
Your app_name inside the urls file is "learning_log" but it seems your html folders are in learning_logs. Maybe something to do with that? Also can you make sure the app_name exists in your INSTALLED_APPS?
I've done a Udemy course for Django which was good for me but they are not free if you want to learn more.
just add the include param called namespace in your main urls.py for the app.
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls', namespace="learning_log")),
path('admin/',admin.site.urls),
]
here you have the documentation of URLs namespaces: https://docs.djangoproject.com/en/3.2/topics/http/urls/#url-namespaces
If you don't want to set the namespace you must call the url like this: reverse('topics')
I want to upload image with the name (which is given by user) at Django server through rest API,but i am not be able to find out the solution for this.Please tell me how to upload image with given name.
here is my code(mainly):
IN API TASK ->URLS:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from django.conf import settings
from myapi import views
from django.conf.urls.static import static
#Define API Routes
router = routers.DefaultRouter()
router.register(r'myimage', views.myimageViewSet) #we have only on viewset
urlpatterns = [
url(r'^',include(router.urls)),
url(r'^admin/',admin.site.urls),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN My API
1. MODEL
from django.db import models
# Create your models here.
class myimage(models.Model):
my_name=models.CharField(max_length=50)
my_image=models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg')
def __str__(self):
return self.my_name
2.SERIALIZERS
from rest_framework import serializers
from .models import myimage
class myimageserializer(serializers.ModelSerializer):
class Meta:
model =myimage
fields=('id','my_name','my_image')
3. VIEWS
from django.shortcuts import render
from .models import myimage
from rest_framework import viewsets
from .serializers import myimageserializer
from rest_framework import filters
import django_filters.rest_framework
class myimageViewSet(viewsets.ModelViewSet):
queryset = myimage.objects.all() #We use Filters for Ordering so remove order_by part
serializer_class = myimageserializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,)
ordering = ('id','my_name',)
4.ADMIN
from django.contrib import admin
from .models import myimage
admin.site.register(myimage)
You need to use FileParser to be able to get your image details in the request data object. I recommend you to follow the example in DRF's FileParser Example
I changed my code as mentioned below and now its working for me if you have any better solution please suggest here #happycoding
1. views.py
from django.shortcuts import render
from .models import myimage
from rest_framework import views
from .serializers import myimageserializer
import django_filters.rest_framework
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class myimageView(APIView):
def get(self, request):
myimagelocal= myimage.objects.all()
serializer = myimageserializer(myimagelocal, many=True)
return Response(serializer.data)
def post(self, request):
myname=request.data['my_image'].name
myformat=""
for c in reversed(myname):
myformat+=c
if c=='.' :
break
myformat=myformat[: : -1]
request.FILES['my_image'].name=request.data['my_name']+myformat
serializer = myimageserializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
IN API_TASK->URLS:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls,name='admin'),
path('',include('myapi.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN API_Task->myapi->url
from django.urls import path
from .views import myimagedetailsView, myimageView
urlpatterns = [
path('myimage/', myimageView.as_view(),name='myimageView'),
]
Rest files unchanged
When starting the server, an error crashes, which file and piece of code should I pay attention to? Other answers given on this site did not help.
Terminal:
File "/home/lab/ProjectsDjango/env_bookmarks/dj-bookmarks/bookmarks/account/urls.py", line 7, in <module>
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/conf/urls/__init__.py", line 22, in url
return re_path(regex, view, kwargs, name)
File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
Next is my application code.
Main urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/', include('account.urls')),
]
App views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
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})
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
App urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^login/$', views.user_login, name='login'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
url(r'^$', views.dashboard, name='dashboard'),
]
Maybe I'm looking in the wrong place and trying to find a bug where it isn't?
I am assuming you are using django>1.9: You cannot use strings as views. So you need to do something like this with all views:
from django.contrib.auth import login, logout
urlpatterns = [
url(r'^login/$', login, name='login'),
url(r'^logout/$', logout, name='logout'),
......
]
The problem with my code is that I keep getting a "page not found (404) error, the path 'post/...' does not match" when I try to click on a hyperlink on my posts page. I made 3 posts. Could it be the regex? Because I'm currently not good at regex.
How can I match the views.py to the correct path in urlpatterns?
My urls.py is:
from django.contrib import admin
from django.urls import path, re_path
from blog import views as blog_views
urlpatterns = [
path('post/', blog_views.post),
re_path(r'^post(.*)/$', blog_views.post),
path('about/'. blog_views.about),
path('', blog_views.index),
path('admin/', admin.site.urls)
]
My views.py is:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Post
def index(request):
posts = Post.objects.all()
return render(request,'index.html', {'posts': posts})
def post(request, slug):
print(slug)
return render ('post.html',{'post': get_object_or_404(Post, slug=slug)})
def about(request):
return render(request, 'about.html', {})
You could use something like:
re_path(r'post/(?P<slug>[\w-]+)/$', blog_views.posts),
Do you really need to use re_path here? It would be simpler to use path:
path('post/<slug:slug>/', blog_views.post),
from myapp import views
File "C:\Users\User\job\mysite\myvenv\myproject\myapp\views.py", line 151
class MarketingBusinessDetailView(generic.DetailView):
SyntaxError: invalid syntax
At models.py,
class MarketingBusiness(models.Model):
title = models.CharField(max_length=128)
description = models.TextField(max_length=200, help_text="Enter a brief description of the Marketing business.")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('myapp:marketingbusiness-detail', args=[str(self.id)])
And it's working perfectly in my admin.
At myapp urls.py,
from myapp import views
app_name = 'myapp'
urlpatterns = [
path('marketingbusinesses/', views.MarketingBusinessListView.as_view(), name='marketingbusiness'),
path('marketingbusiness/<int:pk>/', views.MarketingBusinessDetailView.as_view(), name='marketingbusiness-detail'),
At views.py,
from django.shortcuts import render
from django.views import View
from django.views import generic
from myapp.models import MarketingBusiness
class MarketingBusinessDetailView(generic.DetailView):
model = MarketingBusiness
def marketingbusiness_detail(request, pk):
marketingbusiness_id = get_object_or_404(MarketingBusiness, pk=pk)
return render(
request,
'myapp/marketingbusiness-detail.html', context={'marketingbusiness_id':marketingbusiness}
)
How could I resolve this error, please?...