Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to run static files in pythonanywhere hosting?
I'm trying to upload my project via pythonanywhere but I always get failed to load static files I tried to download it by the static files section of web tab that exists into pythonanywhere and also I got failed you can see what I did here, I will show you all details that I did to help you to understand what could give me the help through it: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATIC_ROOT = "/home/abdelhamedabdin96/website/website/static/index" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # MAIN_DIR = os.path.dirname(os.path.dirname(__file__)) # STATICFILES_DIRS = ( # os.path.join(MAIN_DIR, 'static'), # ) and in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how to get DEFAULT_PAGINATION_CLASS in Django Rest Framework
I have the following ViewSet in Django Rest Framework: class FilterProductsViewSet(viewsets.ViewSet): permission_classes = (permissions.IsAuthenticated,) def post(self, request): pagination_class = settings.REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS'] paginator = pagination_class() queryset = self.get_queryset(request.data) page = paginator.paginate_queryset(queryset, request) page_to_return = serializers.StockSerializer(page, many=True).data return paginator.get_paginated_response(page_to_return) And I am getting the following error when sending a POST: File "/Users/hugovillalobos/Documents/Code/tcdigital/TCDigitalBackend/TCDigital/inventory/views.py", line 2176, in post paginator = pagination_class() TypeError: 'str' object is not callable The line that rises the exception is the one: pagination_class = settings.REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS']. How can I get the default pagination class from settings? -
Show all products from category parent
im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that. Here is my models: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True) title = models.CharField(max_length= 200, null = True) slug = models.SlugField(max_length=200, null = True) ordering = models.IntegerField(default = 0) class Meta: verbose_name_plural = 'Categories' ordering = ('ordering',) def __str__(self): return self.title class Product(models.Model): name = models.CharField(max_length = 255, null = True) slug = models.SlugField(max_length=200) category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE) parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True) brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE) description = models.TextField(blank = True, null = True) price = models.FloatField(null = True) disccount = models.BooleanField(default = False) disccount_price = models.FloatField(blank = True, null = True) image = models.ImageField(upload_to = 'images/',blank = True, null = True) thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) … -
ModuleNotFoundError: No module named 'app' after executing pycharm test
Good day, I have been having this issue where I have been running into this ModuleNotFoundError: No Module named 'app' error when I am trying to test models.py I am trying to utilize pycharm IDE in order unittest. Configurations which I have set using pycharm are: Script path:/MainFolder/MainProjects/project1-backend/tests/test_models.py Environment Variables: empty Python interpreter: Python 3.8 (MainFolder) ~/MainFolder/MainProjects/bin/python Working Directory:/Users/myname/MainFolder/MainProjects/project1-backend Add contentroots to PYTHONPATH: selected Add source roots to PYTHONPATH: selected Here is my project hierarchy. Note, I changed the name of the folders. Also I have included the __init__.py files as per below. Project hierarchy edit test file should be __init__.py not __inity__.py #import from Model class from django.test import SimpleTestCase from django.db import models #User model class User(models.Model): email = models.CharField(max_length=256, primary_key=True) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) def __str__(self): return self.email # this defaults to the email address from django.test import TestCase from app.models import User class TestModels(TestCase): def setUp(self): self.user1 = User.objects.create( email="m@gmail.com", first_name="misha", last_name="lee" ) def test_app_user(self): self.setUp() self.assertTrue(isinstance(self, User)) I also did a quick print out for sys.path: ['/Users/myname/MainFolder/MainProjects/project1-backend/tests', '/Users/myname/MainFolder', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'] Traceback (most recent call last): File "/Users/myname/MainFolder/MainProjects/project1-backend/tests/test_models.py", line 4, in <module> from recruiting.models import User ModuleNotFoundError: No module named … -
Scheduled Django management commands using Zappa & Lamda
I've got my Django site working on Lambda using Zappa. It was very simple. I'm now searching to find out how I set up scheduled Django management commands. From what I've read the work around is to create Python functions that execute the management commands and then schedule the functions to run using the Zappa settings file. Is this still the right method as the help manual doesn't say anything? -
How to update webpage data without refreshing webpage?
I have been using services like slack, discord and gmail and am wondering the type of software they use to recieve a message live, or display an incoming email without refreshing the page? Could this be implemented with a django rest backend and react frontend? -
Create multiple and different records with django
I'm using django and postgresql. I'm posting a json thread with postman. {"side": "BUY", "type": "MARKET", "symbol": "NEOUSDT"} After the data arrives, I filter the database as "side=NEOUSDT,status=True,side=BUY". The list I filtered has a json structure like above. Since the apiKey and secretKey information of each line information is different, I have to create "create_new_order" separately for each. So there can be 10 records, how can I do it in a series for each one separately? In other words, it needs to create "create_new_order" separately for each record, I want to provide it. Also, the program should run async in order not to crash. data(result) [ {"model": "cryptoinfo.cryptoinfo", "pk": 4, "fields": {"createdDate": "2020-10-08T20:49:16.622Z", "user": 2, "created_userKey": "25301ba6-1ba9-4b46-801e-32fc51cb0bdc", "customerKey": "61754ecf-39d3-47e0-a089-7109a07aca63", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "2200", "secretKey": "0022"}}, {"model": "cryptoinfo.cryptoinfo", "pk": 7, "fields": {"createdDate": "2020-10-08T20:51:16.860Z", "user": 1, "created_userKey": "2f35f875-7ef6-4f17-b41e-9c192ff8d5df", "customerKey": "b1c8cee3-c703-4d27-ae74-ad61854f3539", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "atalay42", "apiKey": "0011", "secretKey": "1100"}} … -
Django API push from external python function
I have a ReactJS app that has a Django backend with a Postgres Database. Currently my models.py file that calls several external functions from a receiver. I want one of these external functions to push data to the API so that the React App can access and display that data. models.py class Job(models.Model): name = models.CharField( max_length=100) job = models.IntField( max_length=50) ... @receiver(post_save, sender=Job, dispatch_uid="run function) def run_function(sender, instance, created, *args, **kwargs): #some logic ... id = instance.name externalData = externalFunction(id) #I don't know what to do from here My goal is to send the returned data (which is currently in a dictionary but can be parsed out) to a new model named Data. I know how to get that dictionary into a local variable but don't know how to send it to the api. -
How can I make a reservation system with Django rest framework?
I'm coding a rest API with Django rest. I have a Room model I want to users can reserve the rooms. the rooms have price, reserve days. I created two another models named "order" and "order-item" they are linked together with Stacked Inline in admin.py . with these two models I want to create a order and with a total price function I want to calculate the total price of the reservation ("room price" * "reserve days") . I used Model Serializer for serializing my models. I want to create a reservation system to registered users can book the rooms but I don't know how to do this. I'm beginner and this is a hard project. I need help to complete this project. I can't write views.py please help me write my view. from django.contrib.auth.models import User from django.db import models from eghamat.models import Room class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) return total class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = … -
Store multiple values in 1 field Django (Postgres)
My plan is to have a model that is able to store multiple values in 1 row. Basically what I want is that when a user submits my form, than it will save the weight the height and the current date. And for example the user does the same thing a month later than he will have 2 values. (They will be displayed on a graph). Thanks in advance! Models File class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile') weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True), null=True, ) height = models.FloatField(max_length=20, blank=True, null=True) date = ArrayField( models.DateField(auto_now_add=True), null=True, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views file def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(request.user.user_profile) form = WeightForm(request.POST, instance=profile) if form.is_valid(): print(request.POST) form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, 'Landing/index.html',{'form':form}) Forms class WeightForm(ModelForm): class Meta: model = Profile fields = ['weight','height'] -
How does Gmail know when a new email comes in?
In gmail, when I get an email, I don't need to refresh the page, it automatically updates my inbox UI to show the new email. How do they do this? Do they make a POST request every second or something? Can you achieve this in Django or Node? Thanks! -
How to save nested data via django rest
JSON object: { "MajorUnitHeaderId": 10793322, "Parts": [ { "DealerId": "", "Description": "BATTERY 6 VOLT", "SetupInstall": "S", "Qty": 4, "Cost": 174.95, "Price": 0.0 }, { "DealerId": "", "Description": "1400/1000/185 BATTERY", "SetupInstall": "S", "Qty": 2, "Cost": 189.95, "Price": 0.0 } ] } Serializers: class MajorUnitPartSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitPart fields = '__all__' class MajorUnitSerializer(serializers.ModelSerializer): parts = MajorUnitPartSerializer(many=True) class Meta: model = MajorUnit fields = '__all__' def create(self, validated_data): pdb.set_trace() parts_data = validated_data.pop('Parts') unit = MajorUnit.objects.create(**validated_data) for part_data in parts_data: MajorUnitPart.objects.create(unit=unit, **part_data) return unit Views: @api_view(['GET','POST']) def majorunitapilist(request): query = '76179602?$top=1&$skip=0' api_majorunit_list = get_majorunit(query) for unit in api_majorunit_list: pk = unit.get('MajorUnitHeaderId') try: obj = MajorUnit.objects.get(Cmf=pk) serializer = MajorUnitSerializer(instance=obj, data=unit) if serializer.is_valid(): serializer.save() except: serializer = MajorUnitSerializer(data=unit) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response(serializer.data) Errors: {'parts': [ErrorDetail(string='This field is required.', code='required')], 'Parts': [ErrorDetail(string='Incorrect type. Expected pk value, received list.', code='incorrect_type')]} [09/Oct/2020 12:40:59] "GET /api/majorunit-apilist/ HTTP/1.1" 200 7605 -
When would you use Client Side Rendering VS. Server Side Rendering?
I am new to React and wondering when someone would use: 1. Server Side Rendering 2. Client Side Rendering With React and Django Rest Framework. What causes something to be better with one or the other? Thanks! -
Use a decorator to add in a variable to request
I know the suggested way to do this is middleware, but I'd like to implement the following to add in an env variable so that my view can access it: @api_wrapper def my_view(request): print env # this is the variable I want, such as request.env And the decorator: def api_wrapper(func): def api_inner(request): request.env = 'something' return func(request) return api_inner What's the best way to do this? I have about 100 functions to wrap so I don't want to add in a new parameter for every function but would just like to use the simplest approach to pass that 'env' variable. How should I do it. -
Do I need to learn django to implement tensorflow into my webapp
i am a college student studying my first semester in BCA(BAchelor in Computer Applications) and i'm still in the process of learning mern stack for web development , and yeah like everyone i got hella interested in machine learning and i came across some frameworks such as tensorflow and tensorflow.js, so the problem is i have spent a lot of time learning express to build the backend of webapps and i dont want to end up spending time on more courses, do i have to take a course on django as well in order to implement tensorflow into my websites, i dont want to use tensorflow.js since its much slower and heard a lot of people saying tensorflow is better another question will it be wise to buy a book to learn tensorflow, i seriously want to get into web development and machine learning, ive seen a book on amazon with the title:( Hands-On Machine Learning with Scikit-Learn, Keras and Tensor Flow: Concepts, Tools and Techniques to Build Intelligent Systems (Colour Edition)) will it be good enough And yes I need to post these types of questions on other places like reddit or Quora but I find stack overflow answers … -
Associate AJAX Image Uploads to Post During Post Creation (generic CreateView)
I have a typical Post model: models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField(blank=True) ... My content area uses Editor.MD. EditorMD has user image upload capabilities. The post form is rendered from a typical CreateView class-based view. views.py (the gist) class CustomCreateView(LoginRequiredMixin, CreateView): model = Post form_class = AddNewPostForm template_name = 'myapp/post_create.html' success_url = None ... class UploadView(View): result = { 'success': 0, 'message': 'Image upload failed.', 'url': '', } # processing # goal is to return that result.url of where the image lives return JsonResponse(self.result) When these images are uploaded during the creation of a new post, they are essentially "unattached" or not related to the Post instance itself. I would like these uploaded images to ultimately and eventually have a relation to the post being created. The problem is, when a user is in the process of creating / writing the post, there is no Post ID to attach these images to since it hasn't been created yet. So here are my questions: How can I relate these user-uploaded images to the current post that hasn't been submitted yet? How should I manage user-uploaded images in the content area that the user adds, … -
How can we get more than two users from the database randomly in Django?
Well I am creating profile of every new user with signals and I am trying to add some default followers in the new user profile. I am trying with the following code and that is actually doing quite fine but not exactly that thing which i am wishing to do. Well with the following code. first 2 users with pk=1,pk=2 are becoming default followers of every new profile. I wish i could give some random users as a followers to every new user. For example: first user created new account and get two users following by default with pk=1 ,pk=2 than second user created new account and get two users following by default with different primary key such as pk=2 , pk = 4. Code: With the following code every new user is getting the same two 2 users with pk=1,pk=2, I dont want that. How can do that things which i have explained with example. Please help cause i need in this case. I shall be very thankful to you. if more detail or code is needed than tell me. I will share that with you. def create_profile(sender, created,instance,**kwargs): if created: userprofile = UserProfile.objects.create(user=instance) default_user_profile = UserProfile.objects.get_or_create(user__pk=1)[0] default_user_profile.follower.add(instance) userprofile.follower.add(default_user_profile.user) … -
How to get a file using post request on Django - upload file via HTML
I have a model called ImageFile, with a field Image = models.IamgeField() and I have this on my template: <form action="." method="POST> <label for="img">Select image:</label> <input type="file" id="img" name="img" accept="image/*"> <input type="submit"> </form> How can I save this image which I get from the template? -
Angular 8: Unable to set autorization and responseType in the headers of GET REQUEST (i want to download pdf from my backend API with authorization)
I wanted to download pdf using httpClient servie of Angular 8 and using django as a backEnd API, first problem that i face is i not able to set response Type and authorization on headers. and i m getting these errors. Errors if Accept is set to 'application/pdf': Could not satisfy the request Accept header if i ommit Accept from header error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt… Front end Code const HEADERS = { headers: { Authorization: "Token " + this.authService.token, Accept: 'application/pdf', responseType: 'blob', }, }; this.http.get<Blob>(SERVER_URL, HEADERS) .subscribe(response => { console.log(response); }, error => { console.log(error); }) Back end Code class ModelView(viewsets.ModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def retrieve(self, request, pk=None): print(request.headers) file = Model.objects.get(id=pk) file_path = "media/" + str(file.file) try: return FileResponse(open(file_path, 'rb'), filename=file_path[10:]) except IOError: return Response("file not found") -
Associating a Microsoft Account with an existing user in Django using Oauth2
I want to be able to allow a user do the following: Register an account using a traditional email/password flow, or sign up with a Microsoft account Sign in a existing user with either email/password flow or a Microsoft account After registering an account the traditional way, allow a user to link/ associate their account with a Microsoft account. To do this I created a MicrosoftConnection model to hold the users microsoft data, and token from the OAuth2Session. I have had no problem with the tokens, creating a new connection & User (for register) or verifying the expected state. The problem I am having is that when I attempt to associate an existing account with a new MicrosoftConnection (the user is currently signed in at this point) or sign in an existing user using the microsoft signin, I loose all references to the authenticated user as soon as I get the callback from Microsoft. I can find no way to just grab the token without overriding this user. These are the sign_in and callback views which are pretty standard as far as Oauth goes. I was going to try and use the session var in sign_in to help with creating … -
NameError: Python name 'BASE_DIR' is not defined How To Fix?
I am trying to deploy my website and the images wont load because I am having this error this is causing my images not to load on my website any help is appreciated thank you! NameError: name 'BASE_DIR' is not defined my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a49c&2is^-d$y8ycdycbenh*@dm3$3phszrs_72c*fh-ti1449' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # remember to change to false ALLOWED_HOSTS = ['anim3-domain.herokuapp.com'] # 'https://anime-domain.herokuapp.com/' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' … -
cant run a django project
just starting with django, it is a bit too much for me reading this error log. if anyone has any opinions it would be much appreciated. thanks in advance. Traceback (most recent call last): File "c:\users\deanpc\appdata\local\programs\python\python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\deanpc\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\deanPC\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init .py", line 401, in execute_from_command_line utility.execute() File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init .py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py" , line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands \runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py" , line 371, in execute output = self.handle(*args, **options) File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands \runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\conf_init_.py", line 83, in getattr self.setup(name) File "c:\users\deanpc\appdata\local\programs\python\python39\lib\site-packages\django\conf_init.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing sett ings. -
text editor and font style for blog in django
I would like to know how I could make a text field that has font styles, sizes, and other options for text editing for django if anyone has an idea or example I would be super grateful -
Use direct SQL Queries to access database in Django
I have an app that was built in Django. And I want to use direct SQL Queries to access my MySQL Database. So far, this are my codes models.py class FillWeight(models.Model): weight_description = models.CharField(max_length=100, blank=True, null=True) filler_operator = models.CharField(max_length=100, blank=True, null=True) weight_date = models.DateField(auto_now_add= False, blank=True, null=True) start_time = models.TimeField(auto_now_add = False, blank=True, null=True) finish_time = models.TimeField(auto_now_add = False,blank=True, null=True) class Meta: db_table = 'fill_weight' views.py def show_list_of_info(request): template_name = 'oof_ord/homepage.html' list = FillWeight.objects.raw('SELECT * FROM fill_weight WHERE id = 1') context = { 'list':list } return render(request, template_name, context) It works really fine but is there any way that I can access database and do some process Like SELECT , UPDATE or DELETE without using my models.py ? -
Staff users don't have permission to access admin site without explicitly assigning them
I'm using Django 3.1.2 and staff users added by superuser in the admin site can't access the same admin site after login. All pages in /admin/ return 403 forbidden error. I'm using Windows 10, Python 3.8.5, inside a virtual environment (venv). My commands were made in Git Bash. It first happened in other project, so i created a new one to try. It's the same error in Firefox, Edge and Chrome. Exactly what i did: Git Bash: $ mkdir test_staff $ cd test_staff/ $ python -m venv venv_dev $ source venv_dev/Scripts/activate $ pip install Django==3.1.2 $ pip list Package Version ---------- ------- asgiref 3.2.10 Django 3.1.2 pip 20.1.1 pytz 2020.1 setuptools 47.1.0 sqlparse 0.4.1 $ django-admin startproject mysite $ cd mysite/ $ python manage.py migrate $ winpty python manage.py createsuperuser username: admin password: 12345 $ python manage.py runserver Browser: Login with "admin" user: http://localhost:8000/admin/login Add staff user: http://localhost:8000/admin/auth/user/add/ username: staff_user password: Ax47y](U[1fpw;8H2?}) > Save and continue editing staff status = True > Save Logout: http://localhost:8000/admin/logout/ Login with "staff_user": http://localhost:8000/admin/login Result: Git Bash: [09/Oct/2020 12:49:39] "GET /admin/ HTTP/1.1" 200 2282 Other URL: Git Bash: Forbidden (Permission denied): /admin/auth/user/ Traceback (most recent call last): File "C:\Users\DELL\Documents\github\test_staff\venv_dev\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = …