Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How read a file from Django when using docker?
I run Django in docker and I want to read a file from host. When I test os.stat(path), "No such a file or directory" error returned. The path is something like this '/home/user/file.txt'. Is there any idea that how can I access to host from a running container? thanks -
Django ORM group by week day and sum the day of each separately
I am having trouble to query based on weekday. This is my models: class Sell(models.Model): total_sell = models.IntegerField() date = models.DateField(auto_now_add=True) and this is my query: weekly_sell = Sell.objects.annotate( weekday=ExtractWeekDay('date'), total=Sum('total_sell') ).values( 'weekday', 'total' ) But data i am getting and it is not my expected. Like I have an entry in the table Sunday sell 4 Sunday sell 7 Friday sell 10 So i am expecting it should return these data: [ [ { "weekday": 7, "total": 11 }, { "weekday": 6, "total": 0 }, { "weekday": 5, "total": 10 }, { "weekday": 4, "total": 4 }, { "weekday": 3, "total": 0 }, { "weekday": 2, "total": 0 }, { "weekday": 1, "total": 10 }, ] ] But problem is, it not returning data that way i want, It is returning these: [ [ { "weekday": 7, "total": 4 }, { "weekday": 7, "total": 5 }, { "weekday": 5, "total": 10 }, ] ] I don't know what's wrong with this. Can anyone please help me in this case? -
Setting custom css classes for input container in django form
I have implemented something and I want to know if I did it right or there is a better way to do it. I will describe everything I did. if there's any problem, please excuse me it is my first time to ask questions. I want to implement a form like following with django forms <form id="register-form" class="mt-3"> <div class="py-6 relative"> <label for="email">Email</label> <input type="email" class="form-control" name="email" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="py-3 relative"> <label for="password">Password</label> <input type="password" id="password" class="form-control" name="password" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="py-3 relative"> <label for="repeatPassword">Repeat Password</label> <input type="password" class="form-control" name="repeatPassword" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="mt-4 text-center"> <button type="" class="btn btn-blue">register</button> </div> </form> At first I tried to implement it with django custom widget, like below class CustomInputWidget(forms.Widget): template_name = 'widgets/input.html' input_type = 'text' div_css_classes = '' input_css_classes = '' label = '' def __init__(self, attrs=None, div_css_classes=None, input_css_classes=None, label=None): super().__init__(attrs) if div_css_classes: self.format_div_css_classes(div_css_classes) if … -
Importing a table in SQLite from a .csv-file leads to unicode replacement characters
I am working on a Django (version 3.1) project and am using a SQLite3 database. I am importing tables in the database from a .csv-file. I am using SQLiteBrowser for a tool. After importing the database-table it is full of unicode replacement characters (black diamond with question mark). Prior to importing the table I saved the .csv-file with UTF-8 encoding. From the documentation I understand that SQLite databases are always UTF-8 encoded. So my feeling is that this should not happen. Now there is either something very fundamental or something very simple that I don't understand. I hope somebody can enlighten me. I don't know what else to post to illustrate my question. If need something more please ask. -
db takes duplicate data in Django
I'm creating a social login system in djangorestframework. In my db i'm getting duplicate value entry even i validate the serializers. if social_id exits in db then it must show false message that social_id already exits in db. but in case it's take duplicate entry.... Any help, would be much appreciated. serializers.py : class CreateSocialUserSerializer(serializers.ModelSerializer): social_id = serializers.CharField(allow_blank=True) device_type = serializers.CharField(allow_blank=True) device_token = serializers.CharField(allow_blank=True) login_type = serializers.CharField(allow_blank=True) # username = serializers.CharField(allow_blank=True) #password = serializers.CharField(allow_blank=True) social_img = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) phone_number = serializers.CharField(allow_blank=True) country_code = serializers.CharField(allow_blank=True) token = serializers.CharField(read_only=True) first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) class Meta: model = User fields = ['social_id','device_type','device_token','login_type', 'email','phone_number', 'country_code','token','first_name','last_name', 'social_img'] def validate(self,data): logger.debug(data) social_id = data['social_id'] email = data['email'] device_type = data['device_type'] device_token = data['device_token'] login_type = data['login_type'] #password = data['password'] # username = data['username'] phone_number= data['phone_number'] country_code = data['country_code'] social_img = data['social_img'] if not social_id or social_id =='': raise APIException400({ 'success' : 'False', 'message' : 'Please provide social id' }) userdata_qs = User.objects.filter(social_id__iexact=social_id) if userdata_qs.exists(): raise APIException400({'success': 'False', 'message': 'User with this social_id is already exists. Please login.'}) else: pass return data def create(self,validated_data): # username = validated_data['username'] email = validated_data['email'] phone_number = validated_data['phone_number'] country_code = validated_data['country_code'] login_type = validated_data['login_type'] social_id = validated_data['social_id'] … -
Django Heroku, server does not support SSL, but SSL was required
I have a Django application deployed to Heroku and Postgres, I'm trying to add pgbouncer to scale the app a bit, but I'm getting this error: django.db.utils.OperationalError: server does not support SSL, but SSL was required as a lot of other questions say, the problem is the SSL in django-heroku package. So I tried to approaches, first: adding to the end of setting file the following: del DATABASES['default']['OPTIONS']['sslmode'] the error is still being raised, so I took django-heroku settings function and modified it to disable SSL directly in there def custom_settings(config, *, db_colors=False, databases=True, test_runner=True, staticfiles=True, allowed_hosts=True, logging=True, secret_key=True): # Database configuration. # TODO: support other database (e.g. TEAL, AMBER, etc, automatically.) # Same code as the package # CHANGING SSL TO FALSE config['DATABASES'][db_color] = dj_database_url.parse(url, conn_max_age=MAX_CONN_AGE, ssl_require=False) if 'DATABASE_URL' in os.environ: logger.info('Adding $DATABASE_URL to default DATABASE Django setting.') # Configure Django for DATABASE_URL environment variable. config['DATABASES']['default'] = dj_database_url.config(conn_max_age=MAX_CONN_AGE, ssl_require=False) logger.info('Adding $DATABASE_URL to TEST default DATABASE Django setting.') and calling it: django_heroku_override.custom_settings(config=locals(), staticfiles=False, logging=False) but that didn't work as well, I'm still getting the original error adding Procfile just for complicity: web: bin/start-pgbouncer daphne rivendell.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 -
How to access dynamically generated id of my HTML file in CSS and JS file associated to it
I am creating a blog page in HTML. In the backend I'm using Django. I have created a general HTML template for every post. In Django admin when I upload the image and other data, I'm getting it in Frontend and setting the id of each post dynamically using an autogenerated id coming from Backend. My HTML template is this <div class="row"> {% for blog in blogs_post %} <div class="col-sm-3 offset-sm-1 col-12" id="{{ blog.id }}"> <div class="row"> <div class="col-12"> <img src="{{ blog.image }}" alt=" {{ blog.tittle }}" class="img-fluid"> </div> <div class="col-12"> <h3>{{ blog.tittle }}</h3> <p class="d-none" id="card-body"> <h6>{{ blog.description }}</h6> </p> {% if blog.url %} <a href="{{ blog.url }}" type="submit" role="button" class="btn btn-info">Read more</a> {% endif %} </div> </div> </div> {% endfor %} </div> I want to use this id="{{ blog.id }}" In my CSS file and JS file to uniquely identify each post and apply changes to them. Like if I click one card all the cards should not expand but only the card I clicked will expand. For that I need the dynamically set id to be accessed in my CSS file and JS file. How can I achieve it please help! -
How to get the latest record in the database using django
I have two models, PurchaseOrder and PurchaseOrderdetail, I just want to know how do i get the latest record save in the PurchaseOrder by filtiring the PurchaseOrderdetail , this is my models.py class CustomerPurchaseOrder(models.Model): .... inputdate = models.DateTimeField(auto_now_add=True, verbose_name="OrderSubmittedDateTime") .... class CustomerPurchaseOrderDetail(models.Model): .... customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerPurchaseOrder") this is my views.py allrelatedProduct = CustomerPurchaseOrderDetail.objects.filter(profile__in=client.values_list('id')).latest('customer_Purchase_Order__inputdate') this is the error i get 'CustomerPurchaseOrderDetail' object is not iterable my full traceback Template error: In template C:\Users\USER\Desktop\LastProject\OnlinePalengke\customAdmin\templates\customAdmin\clientAdmin.html, error at line 341 'CustomerPurchaseOrderDetail' object is not iterable 331 : <h1>My Account</h1> 332 : 333 : <div class="grid"> 334 : <div class="grid__item medium-up--two-thirds"> 335 : 336 : <div class="content-block"> 337 : 338 : <h2>Order History </h2> 339 : 340 : <div class="scrollable-container"> 341 : {% for history_product in allrelatedProduct %} 342 : 343 : <table class="responsive-table cart-table"> 344 : <thead class="cart__row visually-hidden"> 345 : <th colspan="2">Product</th> 346 : <th>Quantity</th> 347 : <th>Total</th> 348 : </thead> 349 : <tbody id="CartProducts"> 350 : <tr class="cart__row responsive-table__row"> 351 : <td class="cart__cell--image text-center"> Traceback: File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\LastProject\OnlinePalengke\customAdmin\decorators.py" in wrapper_func 42. return … -
Django group by field and get all items related to that particular field
I'm using Django 3.1.1 and I've got a News model which has a field called source_name. class News(models.Model): title = models.CharField(max_length=350) content = RichTextField(blank=True, null=True) link = models.URLField(max_length=500, unique=True) # Source source_name = models.CharField(max_length=100) I want to group each news by source_name and for each source i want to get all the news. News(title='test',source_name='AAA',...) News(title='test-1',source_name='AAA',...) News(title='test-2',source_name='AAA',...) News(title='test-B',source_name='BBB',...) News(title='test-B1',source_name='BBB',...) In the html template I want to get the following output - AAA -test -test-1 -test-2 - BBB -test-B -test-B1 It would be so easy if I could the following loops: {% for source in source_names %} {{ source }} {% for news in source %} {{news.title}} {% endfor %} {% endfor %} How can I achieve the above descriped output in the django template? Thanks -
Django : NameError: name 'X' is not defined
I don't understand why ? this is my project urls : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls'), name=account), ] and this is my app urls: from django.urls import path from . import views urlpattern = [ path('signup/', views.SignUp.as_view(), name=SignUp), ] Error is : NameError: name 'SignUp' is not defined Have you an idea what's the problem ? Thanks for your answer :) -
Object of type User is not JSON serializable in DRF
I am customizing the API that I give when I send the get request. The following error occurred when the get request was sent after customizing the response value using GenericAPIView. traceback Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\encoders.py", line 67, in default return super().default(obj) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type User is not JSON serializable What's problem in my code? I can't solve this error. Please help me. Here is my code. views.py class ReadPostView (GenericAPIView) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] def get (self, serializer) : serializer = self.serializer_class() posts = Post.objects.all() data = … -
django when I save a model, a group is not assigned to it
when I save to a group is not assigned to the user. def save(self,*args, **kwargs): if self.is_active: group = Group.objects.get(name = 'test') self.groups.add(group) super().save(*args, **kwargs) -
Django admin panel performance degradation
I'm facing some performance issue in admin view of my site. I am using regular Dajngo's admin panel without any special plugins and yet, when I want to open User preview it takes around 30 seconds. When investigated a bit deeper with Django Debug Toolbar I found that single User preview page requires around 270 queries, in DB where there are only 23 users total. In users list view there is only 5 queries required. According to DjDT this huge number of queries is caused by number of queries looking like this: SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = <some number> where <some number> can change. Moreover, I see that there are 77486 voluntary, 6742 involuntary context switches. Which I suppose is just crazy big number for so small number of users. I have slightly modified User model, in a way that it is now using email instead of integer value as primary key. Other than that I have added only one integer field and that's it. Does someone has an idea what can be done to improve the performance? -
Django Unique Constraint doesn't Work on creating unique project titles for each user
So I have this project where I have several supervisors that can create projects. I want that for each supervisor they can't make a project with the same title. I tried to use UniqueConstraint but now it's not working. Supervisors can still create a project with the same title. Note: Project's supervisor is automatically assigned to the project creator. models.py class Project(models.Model): title = models.CharField(max_length=100) due_date = models.DateField() due_time = models.TimeField() supervisor = models.ForeignKey(User, default=None, on_delete=models.SET_DEFAULT) class Meta: constraints = [models.UniqueConstraint(fields=['title', 'supervisor'], name="unique title")] verbose_name = "Project" def __str__(self): return str(self.title) + "-" + str(self.supervisor) forms.py class CreateProjects(forms.ModelForm): class Meta: model = models.Project fields = ['title', 'due_date', 'due_time'] widgets = { 'due_date': DateInput() } views.py @login_required(login_url="/signin") def create_project(response): if response.user.is_staff: if response.method == 'POST': form = forms.CreateProjects(response.POST, response.FILES) if form.is_valid(): # save project to db instance = form.save(commit=False) instance.supervisor = response.user print(instance.supervisor) instance.save() return redirect('/dashboard') else: form = forms.CreateProjects(initial={'supervisor': response.user}) ctx = {'form': form, 'FullName': response.user.get_full_name} else: form = "Only Teachers can create projects" ctx = {'form': form, 'FullName': response.user.get_full_name} return render(response, "create_project.html", ctx) -
my form.is _valid() function is returning False value in django . please check the below files to know more about the issue
Below is the code in models.py file it has some fields models.py from django.db import models class Measurement(models.Model): location = models.CharField(max_length=200) destination = models.CharField(max_length=200) distance = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"distance from {self.location} to {self.destination} is {self.distance}" in views.py i am tryin to insert some data from the form into the table views.py from django.shortcuts import render, get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm # Create your views here. def calculate_distance_view(request): obj = get_object_or_404(Measurement,id=2) form = MeasurementModelForm(request.POST or None) if form.is_valid(): print("valid") instance = form.save(commit=False) instance.destination = form.cleaned_data.get('destination') instance.location = 'san francisco' instance.distance = 5000.00 instance.save() else: print("not valid") print(form.errors) context = { 'distance' : obj, 'form' : form, } return render(request,'measurements/main.html', context) main.html {% extends 'base.html' %} {% block title %} calculate distance {% endblock title %} {% block content %} {{ distance }} <hr> <form action="" method="post" autocomplete="off"></form> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" >confirm</button> </form> {% endblock content %} in the console it is prinnting blank for form.errors python console C:\Users\vishnu.vijaykumar\Desktop\src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 26, 2020 - 13:46:55 Django version 3.1.1, … -
Request.POST.get("amount") convert to float
I have this code in my html <input type="number" value="{{total|floatformat:'2'|intcomma}}" name="total"> it display on my browser " 1,071.00 " and when i tried to convert it to float inside my views.py views.py total = request.POST.get('total') totals = float(total) print(totals) I receive this error -
Filling in database of Django in development mode using multiple ports simultaneously
I am developing a Django project with Postgresql database. I need to scrape data from online resources and save into database while in development mode. Then, I will filter out irrelevant data for deployment and get a smaller-sized database. However, web-scraping and writing into the database is too slow (you can say the online resources are huge). I need to fill in the database faster while in development mode, using a local server. Is it possible/advisable to create multiple projects, using the same database and run them on multiple ports to fill in different sections of my database simultaneously? -
Error: No such command 'flower'. Did you mean one of these? worker
I am trying to use django + celery + rabbitmq + flower, but after i downloaded flower using pip3: Collecting flower Using cached flower-0.9.5-py2.py3-none-any.whl (459 kB) Requirement already satisfied: celery>=4.3.0; python_version >= "3.7" in /home/denys/env2/myshop/lib/python3.8/site-packages (from flower) (5.0.0) Requirement already satisfied: humanize in /home/denys/env2/myshop/lib/python3.8/site-packages (from flower) (2.6.0) Requirement already satisfied: pytz in /home/denys/env2/myshop/lib/python3.8/site-packages (from flower) (2020.1) Requirement already satisfied: tornado<7.0.0,>=5.0.0; python_version >= "3.5.2" in /home/denys/env2/myshop/lib/python3.8/site-packages (from flower) (6.0.4) Requirement already satisfied: prometheus-client==0.8.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from flower) (0.8.0) Requirement already satisfied: vine<6.0,>=5.0.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (5.0.0) Requirement already satisfied: click-didyoumean>=0.0.3 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (0.0.3) Requirement already satisfied: billiard<4.0,>=3.6.3.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (3.6.3.0) Requirement already satisfied: click-repl>=0.1.6 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (0.1.6) Requirement already satisfied: click>=7.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (7.1.2) Requirement already satisfied: kombu<6.0,>=5.0.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from celery>=4.3.0; python_version >= "3.7"->flower) (5.0.2) Requirement already satisfied: six in /home/denys/env2/myshop/lib/python3.8/site-packages (from click-repl>=0.1.6->celery>=4.3.0; python_version >= "3.7"->flower) (1.15.0) Requirement already satisfied: prompt-toolkit in /home/denys/env2/myshop/lib/python3.8/site-packages (from click-repl>=0.1.6->celery>=4.3.0; python_version >= "3.7"->flower) (3.0.7) Requirement already satisfied: amqp<6.0.0,>=5.0.0 in /home/denys/env2/myshop/lib/python3.8/site-packages (from kombu<6.0,>=5.0.0->celery>=4.3.0; python_version >= "3.7"->flower) (5.0.1) Requirement already satisfied: wcwidth in /home/denys/env2/myshop/lib/python3.8/site-packages (from prompt-toolkit->click-repl>=0.1.6->celery>=4.3.0; python_version >= "3.7"->flower) (0.2.5) Installing collected packages: … -
Django User Model, which one should I use, AbstractBaseUser or AbstractUser model?
I honestly do not know the difference between the two, AbstractBaseUser and AbstractUser model class. So, in my project, a website for a school, I might need the student number to be the username and I need to add more fields than just the existing fields in the default AUTH_USER_MODEL of django. I think I really need to substitute the user model (or, do I?) but what I do not know is how should I configure my custom model, should I use AbstractBaseUser or AbstractUser? Thanks! -
About Django Model CharField 'max_length'
class User(models.Model): user_no = models.AutoField(primary_key=True) name = models.CharField(max_length=50, null=False) email = models.EmailField(max_length=255, null=False) password = models.CharField(max_length=50, null=False) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) last_access = models.DateTimeField(auto_now=True) We use like that when want to make Table in Django's models.py We use 'max_length=n'. Here, What does 'n' mean? bits? bytes? ex) when max_length=255, 255 is 255bits? or 255bytes? -
User getting saved as tuple
I am trying to register a user and save his details. I am not getting any error but the user is getting saved as a tuple. Here is the code: Views.py: @csrf_exempt def signup(requests): if requests.method == 'POST': username = requests.POST['uname'], firstname = requests.POST['firstname'], lastname = requests.POST['lastname'], email = requests.POST['email'], password = requests.POST['password'] user = User(username= username, first_name=firstname, last_name=lastname, password=password) user.set_password(password) user.save() return JsonResponse({"message": "User Registered"}) I am getting a success response but the user is saved like this: -
File upload not working after deploying my Django application on a shared hosting
Hi I have recently deployed my Django application on a shared hosting and the deployment went successful, but after the deployment whenever I try to submit a form that contains an input field with type="file" I get an index page as a response. Basically the form request is not even reaching to it's specific method in the 'views.py' file. I am using Ajax-jQuery to submit my forms. Please help me. settings.py """ Django settings for eLearning_platform project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'r%h3za5pxq%3%^q8lzmpdjoen0k8$p@c%*heawr5c_)*8*l9$3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third-part apps 'eLearning_app', ] 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 = 'eLearning_platform.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, … -
collectstatic collecting static files but they're not loading on webpage
I am deploying my Django site on A2 Hosting. I can get the page to display but no static files (images/css) are loading. I have this in my settings.py: ROOT_PATH = os.path.dirname(__file__) STATICFILES_DIRS = [os.path.join(ROOT_PATH, 'static')] I am running python manage.py collectstatic in the terminal. It is creating a static folder with a file structure including admin and subfolders within that admin folder. My images css files are appearing in the newly generated static file (in the base folder) yet neither the css nor my images are showing on my webpage (I've been restarting my server). My link to my css file within my html template is: <link rel="stylesheet" href="{% static 'style.css' %}" type="text/css"> Thank you. -
why my pip gives same error when i run Django server?
I updated version of my pip but when i run every time any command with pip on terminal it gives same error.. before i tried to create django project.. and after some time when i run project it gives error. i dont know where i am doing wrong.. File "/Library/Frameworks/Python.framework/Versions/3.8/bin/pip", line 8, in <module> sys.exit(main()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 17, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 22, in <module> from pip._internal.req.constructors import ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 10, in <module> from .req_install import InstallRequirement File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 10, in <module> import uuid File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/uuid.py", line 57, in <module> _AIX = platform.system() == 'AIX' File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 891, in system return uname().system File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 857, in uname processor = _syscmd_uname('-p', '') File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 613, … -
'NoneType' object has no attribute 'keys' at starting of my website
When I open my website then I click to my cart page it show error 'NoneType' has no attribute key. but when I add product it work clearly then, I clear my cart it also work but at starting it doesn't work. what to do? def cartpage(request): ids=list(request.session.get('cart').keys()) products= Product.objects.filter(id__in=ids) return render(request,'cart.html',{'products':products})