Instead of directing me to the page django is simply returning the following error:
“C:\Users\RodrigoPinto\Desktop\Insider\users\register” does not exist
This is my url;
from django.urls import path
from users import employee_views
from users import views as auth_views
from django.contrib.auth.views import LoginView, LogoutView
app_name = 'users'
urlpatterns = [
path('login/', LoginView.as_view(template_name='users/login.html')),
path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('register/', auth_views.Register.as_view, name='register'),
path('profile/', auth_views.Profile.as_view, name='profile'),
path('listView/', employee_views.AccountsListView.as_view, name='listView'),
path('update/<pk>/', employee_views.AccountsUpdate.as_view, name='updateView'),
path('password_update/<pk>/', employee_views.update_password, name='password_update'),
path('delete/<pk>/', employee_views.AccountsDelete.as_view, name='deleteView'),
]
and on the main app i have this inside the URL;
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import urls as user_urls
app_name = "inside"
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('inside.urls')),
path('users/', include(user_urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've been over this code for the last two hours and I cant understand what I'm doing wrong. Maybe someone can see something that I'm missing.
Also my template directory in settings is configured like this;
template_dir = [
os.path.join(BASE_DIR, 'users', 'templates'),
os.path.join(BASE_DIR, 'forums', 'templates'),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': template_dir,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
views.py;
from django.urls import reverse_lazy
from .forms import UserCreateForm
from django.views.generic import CreateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
class Register(SuccessMessageMixin, CreateView):
form_class = UserCreateForm
success_url = reverse_lazy('users:login')
template_name = 'users/register.html'
success_message = 'Your Account has been created!'
class Profile(LoginRequiredMixin, TemplateView):
template_name = 'users/profile.html'
separate file to keep code cleaner employee_views.py;
from django.views.generic import TemplateView, ListView, UpdateView, DeleteView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages import error, success
from django.shortcuts import redirect, reverse
from django.urls import reverse_lazy
from django.shortcuts import render
from .models import User
#login_required()
def update_password(request, pk):
if request.method == "POST":
form_data = request.POST
if form_data['password1'] == form_data['password2'] and len(form_data['password1']) > 7:
u = User.objects.get(pk=pk)
u.set_password(form_data['password1'])
success(request, "Your Password has been updated!")
u.save()
return redirect(reverse('users:listView'))
else:
error(request, "Please check your passwords!")
return render(request, "users/users/change_password.html", context={'pk': pk})
return render(request, "users/users/change_password.html", context={'pk': pk})
class Profile(LoginRequiredMixin, TemplateView):
template_name = 'users/profile.html'
class AccountsListView(LoginRequiredMixin, ListView):
model = User
paginate_by = 15
template_name = "users/profile.html"
class AccountsUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = User
fields = ('username',
'first_name',
'last_name',
'email',
'image',
'is_admin',
'is_supervisor',
)
template_name = 'user_update_form.html'
success_url = reverse_lazy('users:listView')
class AccountsDelete(LoginRequiredMixin, DeleteView):
model = User
success_url = reverse_lazy('users:listView')
template_name = 'users/user_confirm_delete.html'
the problem is 99% sure in this statement:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess in your settings.py you have something like
MEDIA_URL = '/users/register/'
MEDIA_ROOT = 'C:/....../register'
You access "127.0.0.1:8000/users/register/ and the static(...) catches the request and produces exactly the error message you get.
That is also the reason why you do not get the usual detailed Django Error trace.
If your using generic class based views you need to have the structure like this
app_name
|
|--templates
|
| -- app_name
|
|--register.html
If the error is occuring the login url, its looking in the specifed template for register.html.
Related
I'm not able to import my views in the app folder to the URLS of project folder. I've tried every possible methods like 'from . import views' or 'from newapp import views as newapp_views' and 2-3 more alternatives that I searched on the internet. My app name is newapp and project name is newproject. Please help me.
This is my models file:
from django.db import models
class User(models.Model):
first_name=models.CharField(max_length=128)
last_name=models.CharField(max_length=128)
email=models.EmailField(max_length=256, unique=True)
This is my URLS of newapp folder:
from django.conf.urls import url
from django.urls.resolvers import URLPattern
from .models import views
urlpatterns= [url(r'^$', views.users, name='users'),
]
This is my views of newapp folder:
from django.shortcuts import render
from .models import User
def index(request):
return render(request, 'newapp/index.html')
def users(request):
user_list=User.objects.order_by('first_name')
user_dict={'users': user_list}
return render(request, 'newapp/users.html', context=user_dict)
This is my URLS of newproect folder:
from django.contrib import admin
from django.urls import path,include
from newapp import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls),
]
This is my settings file:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'newapp'
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
You can't import your file like this: from newapp import views.
And from . import views will work only if your urls.py file is in your app folder, while Django by default put it inside your project folder.
If you choose to have separated urls.py files per app (which is a good practice, as your project could grow into many apps), you could do the following:
newapp/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls)
]
newproject/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('newapp.urls'))
]
This way you just include the app urls in the project url file, and you can use a path to prefix all the app urls (instead of a blank string as above).
I seem to find the following error despite making a number of changes in my app.urls file and in my project.urls file. I can't seem to put my finger on it, here is the code:
app.urls file
from django.urls import path
from . import views
urlpatterns = [
path('', views.home_page, name = 'home_page'),
]
project.urls file
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Success.urls')),
]
views.py file
from django.shortcuts import render
from django.http import HttpResponse
enter code here
Create your views here.
def home_page(request):
hello = 'hello world'
return HttpResponse (hello)
Have you added your app in the settings.py file?
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Success',
]
i imported render and used it instead i can't figure out though why it worked
views.py file
from django.shortcuts import render
def hello_world(request):
return render(request, 'hello_world.html')
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.hello_world, name = 'hello_world')
]
project/urls.py
from django.contribs import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls'))
]
So I recently was trying to deploy my website and I was able to get everything working. However, the images are broken for some reason. I can actually add images to the database fine (easily able to add and change the image itself). However, when I click on the link I go nowhere instead of seeing the image and just see the part of my site that pops up whenever the URL entered isn't part of the API (no error, instead nothing basically shows up). The strange part is that the uploaded images actually get added to my images folder in my project but it seems like Django can't find them afterwards (you can see the image is in the database in my images folder). Here is how my project is laid out and: Here is some of my code:
SETTINGS.PY
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'build/static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
REST_FRAMEWORK = {
'DEFAULT_AUTHETICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
]
}
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'EZtrade')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
URLS.PY
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
path('api/', include('articles.api.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
re_path('.*',TemplateView.as_view(template_name='index.html')),
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,})
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
API URLS
router = DefaultRouter()
router.register(r'articles', ArticleViewSet, basename='articles')
router.register(r'trade', TradeViewSet, basename='trade')
router.register(r'users', UserDataViewSet, basename='users')
urlpatterns = router.urls + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MODEL
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
image = models.ImageField(upload_to = 'images', blank=True)
createdBy = models.CharField(max_length=120)
traded = models.BooleanField(default=False)
city = models.CharField(max_length=120)
def __str__(self):
return self.title
VIEWS.PY
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
filter_backends = [DjangoFilterBackend,filters.SearchFilter]
filterset_fields = ['createdBy','traded']
search_fields = ['title']
authentication_classes = (TokenAuthentication,) # Add this line
permission_classes = (IsAuthenticated,)
def get_permissions(self):
if self.action == 'list' or self.action == 'retrieve':
return [AllowAny(), ]
return super(ArticleViewSet, self).get_permissions()
def patch(self, request, pk):
testmodel_object = self.get_object(pk)
serializer = TestModelSerializer(testmodel_object, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(code=201, data=serializer.data)
return JsonResponse(code=400, data="wrong parameters")
SERIALIZERS.PY
class ArticleSerializer(PatchModelSerializer):
class Meta:
model = Article
fields = ('id','title','content','image','createdBy','traded','city')
I have tried many different things and have not been able to find anything else like this on the internet since I dont even get an error when trying to access the image. Im pretty stuck with this so if anyone could help that would be awsome!
you have to make an another serializer using method and pass image url on that like this
class ArticleSerializer(PatchModelSerializer):
image_url = serializers.SerializerMethodField('get_image_url')
class Meta:
model = Article
fields = ('id','title','content','image','image_url','createdBy','traded','city')
def get_image_url(self, obj):
return obj.image.url
I figured out that I had to put the re_path at the end since it was overriding my image url.
i just figured out that the problem is in the urls.py file
it's missing some code
here is mine before
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls'))
]
and here is after i saw this article
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I have a problem when trying to redirect a user after login to the base.html which is in main template folder. Django can't find this template.
I get the error:
Django tried these URL patterns, in this order:
1. admin/
2.
The current path, base.html, didn't match any of these.
How do I properly set up django to make the redirection work?
Django structure:
accounts
main_folder
settings.py
urls.py
staticfiles
templates
base.html
Short app structure
accounts
templates
accounts
login.html
urls.py
views.py
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
accounts urls.py
from django.urls import path
from .views import*
urlpatterns = [
path('', login_view),
]
accounts view.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
# get posted data
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
# handle user authentication
if user is not None and user.is_active and user.is_authenticated:
login(request, user)
# move user to main page
return redirect('base.html')
return render(request, 'accounts/login.html')
Your redirection is not to a template but to a url. So in your current code on successful login you would be redirected to http://localhost/base.html.
You will need to change the redirect to a path:
return redirect('/some-url/')
Or better still make use of named urls.
return redirect('some-named-url')
# this would turn a named url into a url string such as '/auth-url/'
You urls file would look something like:
from django.urls import path
from .views import*
urlpatterns = [
path('', login_view),
path('auth-url/', <some_view>, name='some-named-url'),
]
The better more django way.
If you are not doing anything too extreme you really should look at making use of djangos built-in authentication. Not only is it tried and tested but it also will get patched if a vulnerability was ever discovered.
To do this you would change the urls to be something like:
from django.urls import path
from django.contrib.auth.views import (
LoginView,
LogoutView,
)
urlpatterns = [
path(
'login/',
LoginView.as_view(template_name='account/login.html'),
name='login',
),
path(
'logged-in/',
<Your LoginView>,
name='logged_in',
),
path(
'logout/',
LogoutView.as_view(),
name='logout',
),
]
And in your settings file:
LOGIN_URL = 'login' # this is the name of the url
LOGOUT_REDIRECT_URL = 'login' # this is the name of the url
LOGIN_REDIRECT_URL = 'logged_in' # this is the name of the url
I have found a solution:
modify view.py
return redirect(home)
add in view.py
def home(request):
return render(request, 'base.html')
and in urls.py
path('home/', home, name='home')
im trying to set up media file path / images for DRF but its not working and i cant figure out why.
i get this error:
serve() got an unexpected keyword argument 'documuent_root'
I am on mac runing django 1.11 DRF w/ python 3.6.
I have moved the settings urls to top level by why way of this link so i am one step closer although i still cant figure out why my links show 404 when i click on them.
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'src')
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
CORS_ORIGIN_WHITELIST = 'localhost:3000', #whitelists the localhost to run
views.py
from accounts.api.permissions import IsOwnerOrReadOnly
from rest_framework import generics, mixins, permissions, viewsets
from books.models import Books
from books.api.serializers import BooksSerializer
class BookViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] # authentication_classes = []
serializer_class = BooksSerializer # necessary
queryset = Books.objects.all()
lookup_field = 'id'
search_fields = ('user__username', 'content', 'user__email')
ordering_fields = ('user__username', 'timestamp')
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from . import views
from django.conf.urls.static import static
from django.conf import settings
from rest_framework import routers
from books.api.views import (
BookViewSet)
router = routers.SimpleRouter()
router.register(r'books', BookViewSet) # --> http://127.0.0.1:8000/api/books/api/books/
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
] + static(settings.MEDIA_URL, documuent_root=settings.MEDIA_ROOT)
Its a typo actually. You were using documuent_root , but it should be document_root.
So, change to urlpatterns = [
.... other patters,
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)