Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django auth groups not finding groups and does not give permission to users, regardless of the group in which they are
I'm making a simple real estate app where the users must be separated into two different groups. A regular user and a broker. I'm using the Django admin backend for creating user groups. I'm also using a post_save signal to assign all the new users to the regular users' group. At first glance, it works well and in Django admin, it shows me that the user is in the corresponding group. But when I try to print self.request.user.groups the value is None. Also when I try to check if users have permission to do something, regardless of the permissions I gave the view I check always gives me 403 Forbidden regardless of whether the user has permission or not. I use class-based views and PermissionRequiredMixin respectively. Here is my user model: class DjangoEstatesUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): USERNAME_MAX_LENGTH = 30 username = models.CharField( max_length=USERNAME_MAX_LENGTH, unique=True, ) date_joined = models.DateTimeField( auto_now_add=True, ) is_staff = models.BooleanField( default=False, ) USERNAME_FIELD = 'username' objects = DjangoEstatesUserManager() Also the signal for assigning the new users to a group: @receiver(post_save, sender=DjangoEstatesUser) def create_user_profile(sender, instance, created, **kwargs): if created: instance.groups.add(Group.objects.get(name='Users')) and this is one view that I'm trying to restrict for different users: class AddEstateView(auth_mixins.LoginRequiredMixin, auth_mixins.PermissionRequiredMixin, views.CreateView): permission_required = 'main_estate.add_estate' … -
Using Models and Views in Django
I need help with a project in Django. In views.py I have created a login to the site including registration, but I need to somehow use models.py to edit and add more user parameters, which I don't think is possible in views. Can someone please help me with this. I am attaching the code below. views.py from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from rocnikovka import settings from django.core.mail import EmailMessage, send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str from . tokens import generate_token def home(request): return render(request, "authentication/home.html") def signup(request): if request.method == "POST": # username = request.POST.get("username") username = request.POST["username"] fname = request.POST["fname"] lname = request.POST["lname"] email = request.POST["email"] pass1 = request.POST["pass1"] pass2 = request.POST["pass2"] if User.objects.filter(username=username): messages.error(request, "Username already exist! Please try some other username.") return redirect("home") if User.objects.filter(email=email).exists(): messages.error(request, "Email Address already registered! ") return redirect("home") if len(username)>20: messages.error(request, "Username must be under 20 characters.") return redirect('home') if pass1 != pass2: messages.error(request, "Passwords did not match") return redirect('home') if not username.isalnum(): messages.error(request, "Username must be Alpha-numeric!") return redirect("home") myuser = … -
Django Graphene union of 3 tables
I am programming a website using Django and using Graphene to implement GraphQL. I have three tables that contain different products types and would like to return a query that aggregates those three tables together. So that the products returns are all in a single nest in the response. class Cards(DjangoObjectType): class Meta: model = magic_sets_cards fields = ['name'] class Tokens(DjangoObjectType): class Meta: model = magic_sets_tokens fields = ['name'] class Sealed(DjangoObjectType): class Meta: model = magic_sets_sealed_products fields = ['name'] class MagicSearchTestUnion(graphene.Union): class Meta: types = (Cards, Tokens, Sealed) @classmethod def resolve_type(cls, instance, info): if isinstance(instance, magic_sets_cards): return Cards if isinstance(instance, magic_sets_tokens): return Tokens if isinstance(instance, magic_sets_sealed_products): return Sealed return MagicSearchTestUnion.resolve_type(instance, info) class MagicSearchTestQuery(graphene.ObjectType): magic_search_cards = graphene.List(MagicSearchTestUnion) @staticmethod def resolve_magic_search_cards(self, info, search=''): cards = magic_sets_cards.objects.filter(name=search).all() tokens = magic_sets_tokens.objects.filter(name=search).all() sealed = magic_sets_sealed_products.objects.filter(name=search).all() return list(chain(cards, tokens, sealed)) magicSearchTestSchema = graphene.Schema(query=MagicSearchTestQuery) This seems to work fine without errors and I am able to access the GraphQL GUI, but there is not the expected fields in the query. { magicSearchCards { __typename } } The above is all the fields that seem to be available to me. -
TypeError: Object of type Tag is not JSON serializable
I am trying to send my result as JsonResponse but when I run the function then it is showing every time TypeError: Object of type Tag is not JSON serializable views.py def saveJson(request): response = getReturnedData() results = [] for result in response: results.append({'json': result}) return JsonResponse({'results': results}) returned data from getReturnedData() is :- Note :- "Image1" is not the real data I got in list BUT it is a link of image url (not string), I didn't post it because stackoverflow was showing spam while posting img links [ "Image1", "Image1" ] converted from for loop is :- [ { 'response': [ "Image1", "Image2" ] } ] I have also tried by using json.dumps but it returns nothing And I also tried using data = serializers.serialize("json", results) but it showed 'NoneType' object has no attribute 'concrete_model I have tried hours but it didn't work, Any help would be much Appreciated. Thank You in Advance -
users (except come from createsuperuser) cannot login to web app
I have registration page and login page. Users who registrated cannot login in login page. It always return else block which is redirecting HttpResponse('error'). Could you please help me? note: users successfully registrated (can be seen in database) and they are all active users. note2: only users who created from createsuperuser can login at login.html. others cannot. in views.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return HttpResponseRedirect(reverse('users:home')) else: print("error") return HttpResponse('error') else: return render(request, 'auth/login.html', {}) in urls.py from django.urls import path from users import views app_name = 'users' urlpatterns = [ path('', views.home, name='home'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ] in login.html {% extends 'base.html' %} {% block title %} Login {% endblock %} {% block head %} {% endblock %} {% block content %} <div class="container"> {% if user.is_authenticated %} <h1>You have already signed in</h1> {% else %} <h2>Login Page</h2> <form action="{% url 'users:login' %}" method="POST"> {% csrf_token %} <label for="username">Username:</label> <input type="text" name="username"><br> <br> <label for="password">Password:</label> <input type="password" name="password"><br> <br> <input type="submit" class="btn btn-primary" value="Login"> </form> {% endif %} </div> {% endblock %} I would be grateful if anyone help … -
Python panel (bokeh) server connection display empty html page without error message
I have a Django project where one view function start a bokeh server by a python script. Popen(["panel", "serve", "/opt/bitnami/projects/blog/EnviAI/scripts/visz_pn_ssm_1.py", "--show"]) With another view, I try to connect to the server and display the dashboard from visz_pn_ssm_1.py . def redirect_bokeh_server(request): session = pull_session(url="http://localhost:5006/visz_pn_ssm_1") script = server_session(model=None,session_id=session.id,url="http://localhost:5006/visz_pn_ssm_1") return render(request, 'dashboard_ssm.html', {'script' : script}) in my dashboard_ssm.html <body> {{script | safe}} </body> From the console i get: Starting Bokeh server version 2.4.2 (running on Tornado 6.1) 2022-04-03 08:26:03,800 User authentication hooks NOT provided (default user enabled) 2022-04-03 08:26:03,804 Bokeh app running at: http://localhost:5006/visz_pn_ssm_12022-04-03 08:26:03,804 Starting Bokeh server with process id: 269292022-04-03 08:26:06,550 WebSocket connection openedtest2022-04-03 08:26:07,762 ServerConnection created But the page is empty? The content of my panel script visz_pn_ssm_1.py: import pandas as pd import geopandas as gpd import panel as pn import hvplot.pandas import pickle pn.extension() pn.config.js_files = {'deck': 'https://unpkg.com/deck.gl@~5.2.0/deckgl.min.js'} pn.config.css_files = ['https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css'] with open ('/opt/bitnami/projects/data/filepath_ssm_user.pickl', 'rb') as temp: res = pickle.load(temp) # ried soil samples 30m 17-19 gdf = pd.read_csv(f'/opt/bitnami/projects/data/tables/{res[0]}' ,)[['date', 'ssm']].dropna().reset_index(drop=True) gdf['date'] = gdf['date'].astype('datetime64[ns]') #Options for Widgets years = gdf.date.dt.year.unique() # Widgets year_slider = pn.widgets.IntSlider(name = 'Year', start=int(years.min()), end=int(years.max()), value=int(years[0])) @pn.depends(year_slider) def plot_data(year_slider): data_select = gdf[gdf['date'].dt.year == year_slider] # Scatter Plot scatter = data_select.hvplot.scatter( x = 'date', y = … -
Getting "CSRF token missing or incorrect" on obtain token request
We are using Django REST Framework and we are using user logins. From a web client we have a login screen and use obtain_auth_token from the REST Framework to obtain an api token. The web client uses XMLHttpRequest. It starts out with working fine. The web client obtains a token using username+password and uses that token in the following API calls. When I return the next day and open a new browser tab and try to log in I get a 403 Forbidden and the Django logs (and the body reply) says {"detail":"CSRF Failed: CSRF token missing or incorrect."} I can see that the incoming request has a csrftoken cookie and a sessionid cookie. I can see the same cookies if I use the browser "Developer Tools". If I remove those two cookies, it works fine afterwards. Also, if I launch a private browser window (= incognito), the web app works fine. I am do not know why those cookies appear, when they appear exactly and why the REST framework do not like them. I have two suspicions: We also use the Django admin interface. Could it be that the login to the admin interface on the same domain will … -
Fork() crashes Python in Mac OS Monterey
I'm running Djangorq on my virtualenv with python 3.8.6 as follows export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES;sudo python manage.py rqworker --with-scheduler When I call any function as django_rq.enqueue(func, request.user,arg=arg1) Python crashes and I get this on my console: +[NSPlaceholderString initialize] may have been in progress in another thread when fork() was called. objc[78776]: +[NSPlaceholderString initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. 12:33:17 Moving job to FailedJobRegistry (work-horse terminated unexpectedly; waitpid returned 6) Before Monterey, I used to solve it with export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES But this doesn't seem to work anymore. Any idea how to fix this? -
why increasing worker numbers increase request time in gunicorn, wsgi, django
I am using gunicorn with wsgi and django for my rest beckend app. When I used gunicorn with one sync worker and send 20 same parallel requests, request execution time is about 100ms. When I increased number of workers to 4 and do the same thing execution time of request is four time bigger. I am using AWS and my app is in docker. How this could be possible? Should times be the same in both cases? -
Login action not working in django, csrf token is missing or forbidden
when the login button is clicked it only refreshes the page it is not performing the function loginAction even i cant print the details that i write in that function. HTML page {% csrf_token %} <div class="row"> <div class="col-md-6 wow fadeInLeft" data-wow-duration="2s" data-wow-delay="600ms"> <div class="form-group"> <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="password *" id="phone" name="phone" required data-validation-required-message="Please enter your password."> <p class="help-block text-danger"></p> </div> <div class="col-lg-12 text-center wow zoomIn" data-wow-duration="1s" data-wow-delay="600ms"> <button type="submit" class="btn btn-primary">login</button> </div> </div> <div class="col-md-6 wow fadeInRight" data-wow-duration="2s" data-wow-delay="600ms"> <div class="form-group"> <img src="/static/asset/images/flickr/capture.jpg" height="330px" width="200px"> </div> </div> </div> </div> </div> </form> def loginAction(request): if request.method == 'POST': #print("email") email = request.POST["email"] password = request.POST["password"] user = register_tb.objects.filter(email=email, password=password) if user.count()> 0: return render('home.html',{'msg':"login success "}) else: return render ("login.html",{'msg':"login failed "}) -
Django makemigrations: Makemigration not detect fields, only creates id filed
my problem is about makemigrations, it not detect fields and only creates id and foreignkey field. I added studentapp to INSTALLED_APP: added studentapp into INSTALLED_APP and models.py has: from django.db import models class Department(models.Model): name = models.CharField(null=True, ), active = models.BooleanField(default=True), def __str__(self): return self.name class Student(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE, related_name="students", default=None) name = models.CharField(max_length=50, default=None, null=True, blank=True), date_born = models.DateField(), hobbi= models.CharField(max_length=100,), active = models.BooleanField(default=True), def __str__(self): return self.name then I run command: python manage.py makemigrations studentapp this is result of command newly created migration files (0001) only have id field and foreignkey field. code in migrations 0001: code in migrations 0001 only create id and foreignkey field -
Django per-site cache is not working properly
I'm facing some difficulties caching my website (JS, CSS, fonts, images). When I use lighthouse, I got these results [Cache TTL are all None] while I'm already applying the per-site caching as described in Django documentation. `MIDDLEWARE = [ ... 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ... ] CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 2 592 000 # for 1 month ` Is there any help in order to well cache the website? Tech used: Python 3.8 Django 3.2 Deployed through CPanel Thanks -
Get data from form without submit button Django
I have Django form like this,how i can get data without submit? class TestForm(forms.Form): cod = forms.CharField(max_length=6) class Meta: fields = ('cod',) Maybe it is made with AJAX or WebSocket? Thanks! -
how to fix error occure during installing mysqlclient for django in ubantu?
I am trying to install mysqlclient and got the following error. I am using Ubuntu 20.04 LTS I also did update and upgrade commands. My mysql password is toor mysql -u root -p toor (cc_env) amol@amol-Ideapad-320:~/My Code/Python/Project$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-2erfc_zu/mysqlclient_02a7d23804a54d6dafa6098aa7d9f18f/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. pip list (cc_env) amol@amol-Ideapad-320:~/My Code/Python/Project$ pip list Package Version … -
Only the first Django site to be loaded works
I recently submitted a problem to stackoverflow titled Django infinite loading after multiple requests on apache using mod_wsgi. Anyways, I have recently changed a lot of that code and now I have a new problem. The first Django website I request works, however, the second one points to the first one I loaded and gives the response DisallowedHost because obviously it is trying to access that Django application with a different domain name. I obviously want it to do that it should do so if anyone can help me that would be great. Here is all my code. Vhosts LoadFile "C:/Users/taber/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName astinarts.uk.to SSLEngine on SSLCertificateFile "conf/astinarts/astinarts.uk.to-chain.pem" SSLCertificateKeyFile "conf/astinarts/astinarts.uk.to-key.pem" WSGIApplicationGroup %{GLOBAL} Alias /static "C:/xampp/htdocs/astinarts/static" <Directory "C:/xampp/htdocs/astinarts/static"> Require all granted </Directory> Alias /media "C:/xampp/htdocs/astinarts/media" <Directory "C:/xampp/htdocs/astinarts/media"> Require all granted </Directory> Alias /.well-known "C:/xampp/htdocs/astinarts/.well-known" <Directory "C:\xampp\htdocs\astinarts\.well-known"> Require all granted </Directory> Alias /sitemap.xml "C:/xampp/htdocs/astinarts/sitemap.xml" Alias /robots.txt "C:/xampp/htdocs/astinarts/robots.txt" <Directory "C:/xampp/htdocs/astinarts/astinarts"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/astinarts/astinarts/wsgi.py" <Directory "C:/xampp/htdocs/astinarts/astinarts"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ################################################################################################## # NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName neostorm.us.to SSLEngine on SSLCertificateFile "conf/ssl.crt/neostorm.us.to-chain.pem" SSLCertificateKeyFile "conf/ssl.key/neostorm.us.to-key.pem" WSGIApplicationGroup %{GLOBAL} Alias /static "C:/xampp/htdocs/neostorm/static" <Directory … -
django ckeditor upload not working in production
django settings: CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_RESTRICT_BY_DATE = False CKEDITOR_UPLOAD_PATH = 'uploads/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_ROOT = os.path.join(BASE_DIR, "attachments") STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'), ) STATIC_URL = f"{FORCE_SCRIPT_NAME}/backend/static/" MEDIA_URL = f"{FORCE_SCRIPT_NAME}/backend/attachments/" urls: urlpatterns = [ path('admin/filebrowser/', site.urls), path("grappelli/", include("grappelli.urls")), path('admin/', admin.site.urls), path("api/", include(api_urlpatterns)), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=settings.DEBUG) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=settings.DEBUG) if settings.DEBUG: import debug_toolbar urlpatterns = [ path("__debug__/", include(debug_toolbar.urls)), ] + urlpatterns nginx: location /project_name/ { set $service project_name; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://$service; client_max_body_size 16m; } In dev all works, upload and browse, but in prod with not (AH00128: File does not exist: /var/www/html/project_name/ckeditor/upload). I try add alias/root to nginx config, change ckeditor path to re_path(r'^ckeditor/', include('ckeditor_uploader.urls')) and still nothing( -
What happens line by line after I register a model in django
I'm new to programming and I don't really understand what's going on line by line in the code For example: to register a model in Django, we can register the class “class Genre(models.Model)” and specify only one field, for example “models.Charfield.” In turn, the parent class “Model(metaclass=ModelBase) (django.db.models.base)” contains about 50 methods. Most of them are private Questions: Were these 50 methods called when I registered the model? If “yes”, which line of code is responsible for this call? Or which principle of OOP? Could you recommend any article or book to delve into this topic? Thanks in advance! -
how can we filter objects of data from database on the basics of latest? python [duplicate]
I want only 3 database objects which are latest in database, table from django table. like if we have 20 in whole table , so the code will give only three which are latest as per date. -
Custom template tag wont assign to {% with %} context
I'm in need of a custom tag where multiple keyword arguments can be passed in for the purpose of creating an unique id for a given object instance. Whatever string the tag returns it assigns the string as a context variable to the included template. Yet the id context variable remains empty. In this case, the ids for the SVG elements only return the hardcoded strings upvote_ and downvote_. How can I fix this so that the id context variable is interpolated into the string of the SVG id attributes? An example being: upvote_queston101 {% for answer in question.answers.all %} {% include "./posted.html" with post=answer id=set_id question=question.id answer=answer.id %} {% endfor %} <div class="rating_box"> <div class="vote"> <svg id="upvote_{{ id }}" class="vote_button"> </svg> <p>{{ post.score }}</p> <svg id="downvote_{{ id }}" class="vote_button"> </svg> </div> <p class="post_body_content">{{ post.body }}</p> </div> from django import template register = template.Library() @register.simple_tag def set_id(*args, **kwargs): if kwargs['question'] and kwargs['answer']: q_id, a_id = kwargs['question'], kwargs['answer'] return f"question{q_id}_answer{a_id}" q_id = kwargs['question'] return f"question{q_id}" -
Flutter Web on Firebase hosting refused to make API Calls
I have a Flutter Web application that I have deployed on Firebase Hosting. I have a Django backend that I have deployed on an EC2 instance and is running on http. I have CORS enabled in the backend, tried accessing endpoints via browsers and it works just fine. But, when I try to make the same call using FlutterWeb, it fails. And error type of blocked:mixed content appears. (See image below) I want to call those HTTP endpoints and I don't want an SSL certificate mess because this is just a college project. How do I fix this? I am using Dio on Flutter Web to make requests. What would be causing this problem? -
How to pass values multiple html file by render_to_string class in django?
This is my code when I delete a product from header_3.html everything fine but I want to do the same delete work on the cart page. It working but need to reload the page. how to pass multiple html file names through render_to_string? selected_item_html = render_to_string( 'header_3.html', { 'num_of_cart': cart_value, 'total_cart': total_cart, 'subtotal_amount': cart.get_subtotal_price(), } If I replace header_3.html with cart.html it working fine but I want both header_3.html and cart.html -
No Django settings specified. Unknown command: 'createsuperuser' Type 'manage.py help' for usage
I am trying to create a superuser through createsuperuser command in manage.py console is throwing an error "No Django settings specified. Also tried in python console by runninf python manage.py createsuperuser Unknown command: 'createsuperuser' Type 'manage.py help' for usage." I AM USING PYCHARM settings.py """ Django settings for MovieFlix project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-#*8cdy*ul906(s4ei#g7h17)vv%)#0s5b##weupzn-&ct@ylez' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.2.12', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Core.apps.CoreConfig', 'movie.apps.MovieConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'MovieFlix.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'Core/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', ], }, }, ] WSGI_APPLICATION = 'MovieFlix.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES … -
File C:\ProjectName\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system
Allow Windows PowerShell to Execute ScriptsPermalink. Type the following command in the PowerShell admin window to change the execution policy: set-executionpolicy remotesigned then enter "Y" or "A". Now you can activate your Django project. -
Getting top 3 most enrolled course by students
I am building a website where an instructor can create courses and students can enroll the courses. I wanted to display top 3 most enrolled courses/popular courses. I tried to filter the courses that the instructor has, find the number of students that has enrolled to the courses and ordered them by descending which means it will display from highest to lowest number of enrolled students per course. It will then display only the top 3 most enrolled courses. However, my code does not work. Please help T.T models.py class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) enrollment_date = models.DateField(auto_now_add=True, null = True) class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.TextField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.TextField(max_length=2500, null = False) timeline_budget = models.TextField(max_length=250, null = False) req_prerequisite = models.TextField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) views.py … -
In Django have written a clear code everything good but still the css does not display on the webscreen and i am using python 3.10 and django 4
Am using Python 3.10 And django 4.0.3 I tried to change my base dir but still did not work Firstly it was STATIC_URL = ' /static/' STATICFILES_DIR=[os.path.join(BASE_DIR),] Then secondly i tries this STATIC_URL = ' /static/' STATICFILES_DIR = [os.path.join(BASE_DIR),] STATIC_ROOT = os.path.join (os.path.dirname (BASE_DIR),"static")