Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' But the module is installled
I get the error above when launching my django project, I am on windows I have tried installing the module again and tried pip install psycopg2-binary as well.I also checked out other treads but they don't seem to work I need to fix it pretty soon so thank you in advance! -
Limiting amount of objects user can add in another object
I just have a quick question, I would like to limit exercises in training unit to 3-5 exercises , and limit trianing units in trainingplan to 12 training units, so the user will not add an infinite ammount of exercises,or infinite amount of training units in a plan? class TrainingPlan(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) nameoftheplan = models.CharField(verbose_name="Name of the plan",max_length=20, null=True) Squat1RM = models.PositiveIntegerField(verbose_name="100%RM in squat",default=0, blank=True, null=True) DeadliftT1RM =models.PositiveIntegerField(verbose_name="100%RM maximal repetition in deadlift",default=0, blank=True, null=True) Benchpress1RM = models.PositiveIntegerField(verbose_name="100%RM maximal repetition in benchpress",default=0, blank=True, null=True) mesocycle= models.CharField(max_length=40, choices=MESOCYCLE_CHOICES,default=MESOCYCLE_GPP) timeoftheplan= models.CharField(max_length=40,choices=TIME_CHOICE,default=TIME_WEEK3 ) def __str__(self): return str(self.nameoftheplan) class TrainingUnit(models.Model): trainingplan=models.ForeignKey(TrainingPlan, on_delete=models.CASCADE) class Exercise(models.Model): trainingunit=models.ForeignKey(TrainingUnit,on_delete=models.CASCADE) exercisename=models.CharField(max_length=100,verbose_name="Exercise",choices=EXERCISE_CHOICES) exercisesets=models.IntegerField(choices=SETSCHOICES) exercisereps=models.IntegerField(choices=REPCHOICES) -
How to calculate the values of child-tables by using ForeignKey from a parent-table
My purpose is to gain averages of values stored in child-tables depending on each parent-table. In my case, I want to gain averages of satisfaction stored in the Evaluation model (child) depending on each Professor model (parent). models.py class Professor(models.Model): college = models.CharField(max_length=50, choices=COLLEGE_CHOICES) name = models.CharField(max_length=50) def __str__(self): return self.name class Evaluation(models.Model): name = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_names', null=True) satisfaction = models.IntegerField(choices=SATISFACTION_CHOICES) def __str__(self): return self.comment views.py class ProfessorDetail(generic.DetailView): model = Professor context_object_name = "professor_detail" template_name = "professors/professor_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['avgs'] = Professor.objects.all().evaluation_set.all().annotate(avg_satisfactions=Avg('satisfaction')) return context professors/professor_detail.html {% for evaluation in avgs %} <p>{{ evaluation.avg_satisfactions }}</p> {% endfor %} I tried following codes for views.py. context['avgs'] = Professor.objects.all().evaluation_set.all().annotate(avg_satisfactions=Avg('satisfaction')) context['avgs'] = Professor.objects.prefetch_related().all().annotate(avg_satisfactions=Avg('satisfaction')) context['avgs'] = Professor.objects.all().prefetch_related(Prefetch('evaluation_set', queryset=Evaluation.objects.all().annotate(avg_satisfactions=Avg('satisfaction')))) But, all of them do not work. -
How to use static files in the Django code
Hi there, on my Django 4.0 project, I'm implementing a profanity filter validator. So I have a file.txt with a list of profanity words. I put that file in my static folder and now need to use it in my validators.py code. But how to import it to the code for usage? I think it's a bit tricky. Please advise somehting.. -
Sending html button status to django view
I am trying to create a button the picks orders from a list of paid products to a list of unpaid or Vice versa upon clicking the pick me button. But I don’t know how to go about this problem as Iam not well vested in using JavaScript. What I want is when a user clicks the pick me button on the list of unpaid orders, the order stops showing on the unpaid orders and starts to show on the paid orders and Vice versa or rather when the click the pick me button the order goes to the myorders list in there account. I tried just filtering with jinja templates and sending the value of the button as True on a condition model field that by default I made false then sending it as post form data to the view. But this just kept blowing up in my face as it did not work when the order will be made by someone else and picked by someone else -
how to resolve eror - "django.db.utils.ProgrammingError"
' File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/mihirshah/Desktop/api/create_area_api/urls.py", line 3, in <module> from create_area_api.views import api_create_area File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 7, in <module> class api_create_area(viewsets.ModelViewSet): File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 10, in api_create_area print(queryset.get()) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 646, in get num = len(clone) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __len__ self._fetch_all() File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 87, in __iter__ results = compiler.execute_sql( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute with self.db.wrap_database_errors: File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "accounts_project" does not exist LINE 1: ...."start_date", "accounts_project"."end_date" FROM "accounts_... ` I typed cmd - "python3 manage.py makemigrations" and encountered the above error, I tried several commands and tried refreshing the database too by changing it, Deleted all the .pyc in migrations and pycache folder but still … -
Django Models: How to add two lists of options in a way that one is dependent on the other
I have two models in salesnetwork application, as below. salesnetwork.models: class Provinces(models.Model): name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "provinces" def __str__(self): return self.name class Cities(models.Model): province = models.ForeignKey("Provinces", models.DO_NOTHING) name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "cities" def __str__(self): return self.name In another app named core, I have a model for a contact form as below: core.models: class ContactUsFormModel(models.Model): first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) # province = Provinces //How to add Provinces? # // TODO add phone number field # phone_number = models.IntegerField(max_length=11) email = models.EmailField(blank=False, null=False) subject = models.CharField(max_length=250, blank=False, null=False) message_body = models.TextField() def __str__(self): return self.subject Whic I use this model for creating a ModelForm as below: core.forms: class ContactForm(ModelForm): class Meta: model = ContactUsFormModel fields = "__all__" widgets = { "first_name": forms.TextInput( attrs={ "class": "form-control", "placeholder": "First name", "required": "True", } ), "last_name": forms.TextInput( attrs={ "class": "form-control", "placeholder": "Last name", "required": "True", } ), "email": forms.EmailInput( attrs={ "class": "form-control", "placeholder": "email@address.com", "required": "True", } ), "subject": forms.TextInput( attrs={ "class": "form-control", "placeholder": "Subject", "required": "True", } ), "message_body": forms.Textarea( attrs={ "class": "form-control", "placeholder": "Write your message here.", "required": "True", } ), } Now the GOAL is to add a … -
what is the difference between Django and React . which is better for a new programmer in future ? HELP ME OUT
DJANGO AND REACT DIFFERENCES In future which would be more applicable. OR more scope in future . -
Data not being passed from views.py to template
I'm passing a dictionary to views.py and I want to output data from it to the site page. But instead I get pure html, no data. views.py: ` def index(request): data = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [37.62, 55.793676] }, "properties": { "title": "«Легенды Москвы", "placeId": "moscow_legends", "detailsUrl": "static/Moscow_map/places/moscow_legends.json" } } ] } return render(request, 'index.html', context=data) ` index.html: ` {{ data|json_script:"data-b" }} <script id="data-b" type="application/json"> </script> ` -
Pymongo : Ignore null input value when searching documents
In mongodb i have many document structure like this in root collection _id: ObjectId() A : "a" B : "b" _id:ObjectId() A : "c" B : "d" And then i want to find document depend on user input, for example data = request.data item_A = data.get('A', None) item_B = data.get('B', None) for item in root.find({ 'A': item_A, 'B': item_B }): print(item) but the problem is if the user just want to find document depend on A and dont have input value for item_B then item_B will be None, so that the code don't return anything. Any suggestion? -
Can't open User model using mongo db
I'm using mongo db in my django project. Whenever I try to open a record of User model in django admin, it gives me this error All the other models are working fine. But getting problem in User model and my user model is -
How to block user authorization for Django Rest Framework in custom Middleware?
Hi I am creating a custom middleware in Django for the DRF. So that when an user try to access any of the api the middleware will perform some operation and determine if the user is authorized to access the endpoint or not. My code is like below: class PermissionMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): if request.path.startswith('/admin/'): return None if request.path.startswith('/api/'): is_allowed = True if not is_allowed: return # < -- What needs to return to block the access return None My problem is what should I return from the method for disallowing access to api? I can return None, if I want to give access. But I want to disallow access and return some message from the api view so that user knows that he is not allwed. So in summery: What should I return from the middleware to block access? How can I return message to user from the view that he is not authorized? Thanks -
How to take JavaScript variable as input in Django
I am trying to pass a JavaScript variable in Django views but I am not sure what I am doing. Here are the codes: JavaScript code: `function result_output() { document.getElementsByClassName("result_window")[0].style.display="block"; $(document).ready(function () { var URL = "{% url 'homepage' %}"; var data = {'all_filter_value': all_filter_value[0]}; $.post(URL, data, function(response){ if(response === 'success'){ alert('Yay!'); } else{ alert('Error! :('); } }); }); }` Views.Py `from django.shortcuts import render from django.http import HttpResponse from .models import moviedb import pandas as pd def homepage(request): movies = moviedb.objects.all().values() df = pd.DataFrame(movies) mydict = { "df": df } if request.method == 'POST': if 'all_filter_value' in request.POST: all_filter_value = request.POST['all_filter_value'] return HttpResponse('Success') return render(request=request, template_name="movierec/home.html", context=mydict)` I tried using JQuery to pass the variable(an array) to Django views.py. It seems like it is going there but it is not getting accepted there for some reason. I get below error in console: jquery.min.js:5 POST http://127.0.0.1:8000/%7B%%20url%20'homepage'%20%%7D 404 (Not Found) send @ jquery.min.js:5 ajax @ jquery.min.js:5 b.<computed> @ jquery.min.js:5 (anonymous) @ scripts.js:103 c @ jquery.min.js:3 add @ jquery.min.js:3 ready @ jquery.min.js:3 result_output @ scripts.js:99 nextPrev @ scripts.js:48 onclick @ (index):71 -
Updating record in Database using Django
I am trying to update a record in Database using Django but it adds the same record again. How i can fix it? code is given below. def update(request, id): book = tblbook.objects.get(id=id) form = tblbook(BookID = book.BookID, BookName=book.BookName, Genre=book.Genre,Price=book.Price) form.save() return redirect("/show") -
Finding the average of IntegerField
I'm trying to create a new datafield that stores the value according to the average of the 3 fields and also want to use the orderby in the views.py file class TodoList(models.Model):username = models.CharField(max_length = 50) title = models.TextField(max_length = 100) num1 = models.IntegerField() num2 = models.IntegerField() num3 = models.IntegerField() #average = (num1 + num2 + num3)/3 -> NoneType error I'm trying to create a new datafield that stores the value according to the average of the 3 fields and also want to use the orderby in the views.py file def profile(request, pk): user_object = User.objects.get(username = pk) user_profile = Profile.objects.get(user = user_object) #user_profile has the things related to that usertodolist = TodoList.objects.filter(username = pk).order_by('average') context = { 'user_object' : user_object, 'user_profile' : user_profile, 'todolist' : todolist, } return render(request, 'profile.html', context) I tried using the property function, but wasn't able to order_by from that function. But was able to pass it in the html page -
A problem with rendering objects on the template django?
I am trying to make a filter on my ecommerce website. I could filter and print queryset on the console, but I could not render it on the templete. It's not giving any errors, it's just not showing items. views.py def Products(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() gender = Gender.objects.all() categories = Category.objects.all() product_types = ProductType.objects.all() try: data = json.loads(request.body) productTId = data['productTId'] productVId = data['productVId'] genderId = data['genderId'] genderId = get_object_or_404(Gender, id=genderId) productVId = get_object_or_404(Category, id=productVId) productTId = get_object_or_404(ProductType, id=productTId) filtered_products = Product.objects.filter(typeP=productTId).filter(category=productVId).filter(Gender=genderId) countFilter=filtered_products.count() print(filtered_products) print(countFilter) except: None try: context = {'countFilter':countFilter,'filtered_products':filtered_products,'gender':gender,'categories':categories,'product_types':product_types,'products':products, 'cartItems':cartItems, 'order':order, 'items':items} except: context = {'gender':gender,'categories':categories,'product_types':product_types,'products':products, 'cartItems':cartItems, 'order':order, 'items':items} return render(request, 'product.html', context) html {% for product in filtered_products %} <div class="card"> <div class="card__img"> <picture><source srcset="{{product.imageURL}}" type="image/webp"><img src="{{product.imageURL}}" alt=""></picture> </div> <h6 class="card__title">{{product.name}}</h6> <div class="card__descr">{{product.description}}... <div class="card__more" onclick="More('{{product.id}}')">подробнее...</div> </div> <div class="card__func"> <a class="btn-hover card__button-buy update-cart" data-product="{{product.id}}" data-action="add">В КОРЗИНУ</a> <div class="card__right"> <div class="card__price">{{product.price}} р</div> <div class="card__changed-price card__changed-price--card"> <div class="card__changed-btn card__changed-btn--prev card__changed-btn--max increase" data-product="{{product.id}}" data-action="minus"><svg width="8" height="2" viewBox="0 0 8 2" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M1 1L7 1" stroke="#7ABC51" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> <p class="card__changed-thing" id="quantity" class="quantity" data-product="{{product.id}}">1</p> <div class="card__changed-btn card__changed-btn--next increase" data-product="{{product.id}}" data-action="plus"><svg width="8" height="8" viewBox="0 0 8 … -
Does anyone have any insight on why my css is not rendering?"GEThttp://127.0.0.1:8000/static/css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found)"
All of the source code is in my GitHub repo here I've already looked at this this Stack Overflow thread and tried all of the suggestions with no luck. When running "python manage.py runserver" I expect the CSS and HTML to render properly to create the bootstrap front end. Thanks. -
How to access user instance in custom login system?
I want to make a very custom login system and I'm failing to receive the user instance when the token is sent within the headers. I have number of APIs which need to work with and without users logged in and need to access the user.id (primary key). In my custom Login, I want to get the user instance and do a custom check. But I can never access the user even though the token is created and is being sent within the header. I'm sending the token in header within Postman: "Authorization": "Token {{token}}" settings.py: ..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'corsheaders', 'pgtrigger', 'rest_framework', 'rest_framework.authtoken', 'myapp' ] ..... AUTH_USER_MODEL = "myapp.User" ..... login.py: from typing import Any from django.db.models import Q from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.request import Request, QueryDict from rest_framework.views import APIView import bcrypt from myapp.util.functions import contains, API_CallBack from myapp.util.classes import Error from myapp.models.user.user import User class Endpoint(APIView): authentication_classes = [BasicAuthentication, SessionAuthentication] permission_classes = [AllowAny] def post(self, request: Request): # -------------------- # Get and Check Data # -------------------- print() print(request.user) // NOT GETTING THE USER HERE print() par: QueryDict = … -
Django 4.1 not identifying static file
i'm a beginner with Django and have been working a small project that requires quite a bit of styling. However, for some reason, Django isn't picking up on my static css file. This is what I have in settings.py folder. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = Path(BASE_DIR) / 'templates' STATIC_DIR = Path(BASE_DIR) / 'static' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-nke)1=*9!e-26=n8_u@eki%9#o7=*@wn@mhg-84#i&s@s8ofr$' # 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', 'CalculatorApp' ] 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 = 'Calculator.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Calculator.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
I have a problem in submitting comments to server using json and fetch in django
I am working on a bookstore project using django and javascript. I want to allow user to add comments on each book and send the comment without reloading the page using JSON html: <form id="addcomment"> {% csrf_token %} <input hidden name='thecommentuser' value="{{ request.user.id }}" id="commentsubmitter"> <input hidden name='thecommentbook' value="{{ book.id }}" id="commentbook"> <textarea name='thecomment'id="comment"></textarea> <input type="submit"> </form> script: document.addEventListener('DOMContentLoaded', function() { document.querySelector('#addcomment').onsubmit = function() { fetch('/comments', { method: 'POST', body: JSON.stringify({ thecomment: document.querySelector('#comment').value, thecommentuser: document.querySelector('#commentsubmitter').value, thecommentbook: document.querySelector('#commentbook').value, })})}}); models.py: class comments(models.Model): comment = models.CharField(max_length= 100) commentuser = models.ForeignKey('User', on_delete=models.CASCADE, default=None) commentbook = models.ForeignKey('books', on_delete=models.CASCADE, default=None) def serialize(self): return { 'thecomment': self.comment, 'thecommentuser': self.commentuser, 'thecommentbook': self.commentbook } urls.py: urlpatterns = [ path('comments', views.addcomments, name='comments') ] views.py: @csrf_exempt @login_required def addcomments(request): if request.method == 'POST': print('posted') data= json.loads(request.body) comment = data.get('thecomment', '') commentuser = data.get('thecommentuser') commentbook = data.get('thecommentbook', '') cuser = User.objects.get(id = commentuser) cbook = books.objects.get(id = commentbook) thecommentt = comments( thecomment=comment, thecommentuser=cuser, thecommentbook=cbook ) thecommentt.save() when I open the comments in the admin page I don't find any submitted data and the page reload upon submitting a comment. the order of print('posted') in views.py isn't displayed to me upon adding a comment and that means that the request isn't sent … -
TypeError at /studentform Field 'prn_no' expected a number but got ('1',)
I had a problem here....so I have created a MySql databases and connected it with Django framework, my website'titled 'School Management System' has 5 tables and all of them work flawlessly whether it is fetching data from user through Django forms and storing it in mysql database or vice versa but Student and faculty table returns same error as mentioned below : TypeError at /studentform Field 'prn_no' expected a number but got ('1',). I dont understand what is it that is leading to this error. Rest all I tried deleting my whole Django migration and creating it again my python manage.py makemigration python manage.py migration But still the same error. Below are some snippets of my code: studentform.html {% extends 'base.html' %} {% block title %}Student{% endblock title %} {% block body %} <div class="container"> <br> <form class="row g-3" method="post" action="/studentform"> {% csrf_token %} <div class="col-md-4"> <label for="prn_no" class="form-label">prn_no</label> <input type="number" class="form-control" id="prn_no" name="prn_no" required> </div> <div class="col-md-4"> <label for="fname" class="form-label">fname</label> <input type="text" class="form-control" id="fname" name="fname" required> </div> <div class="col-md-4"> <label for="lname" class="form-label">lname</label> <input type="text" class="form-control" id="lname" name="lname" required> </div> <div class="col-md-4"> <label for="DOB" class="form-label">DOB</label> <input type="date" class="form-control" id="DOB" name="DOB" required> </div> <div class="col-md-4"> <label for="Address" class="form-label">Address</label> <input type="text" class="form-control" … -
Randomly changing text in django base template
I have just started learning Django. Currently I am building project with several apps. I have templates folder at the project level which contains base.html. This file contains Bootstrap5 elements Navbar and Card (quote). At the app level I also have templates folder that contains several html files. All of them extends base.html from project level. I would like to randomly change the text in quote Card, so every time when bowser render template from app level it displays new quote. I have Model named Quotes at the app level and I can use quote=Quotes.objects.all(?).first() to select random entry. But I have no idea how to connect to the base.html. Could you give me a hint how to solve my problem? <!--templates/base.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> <title>{% block title %}{% endblock title %}</title> </head> <body> <!--NAVBAR--> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a … -
Why upgrading django version to 3.2 makes project run "ValueError: Empty module name"?
when I upgrade django version from 3.1 to 3.2 and run my django project, I faced this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/config.py", line 210, in create app_module = import_module(app_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1011, in _gcd_import File "<frozen importlib._bootstrap>", line 950, in _sanity_check ValueError: Empty module name I tried to run the project, but it fails with previous error. -
Heroku/ S3/ Django - Timed out running buildpack Python when pushing code to Heroku
I have deployed a django project onto Heroku and used S3 for statics. The S3 bucket is working: if I upload a picture on heroku, it gets uploaded on "websitename.3.amazonaws.com/static/". However, there is still 2 problems and I feel these 2 are actually related, as I didnt have that issue before I setup S3. First problem, the actual staticfiles dont seem to be working with Heroku: I can see them on the S3 bucket, but small styling tests (which are in statics) fail. Second problem, I get timed out when uploading statics with git push heroku master. remote: -----> $ python manage.py collectstatic --noinput remote: -----> Timed out running buildpack Python and I need disable statics if I wan to push anything. Interesting fact, if I run $ python manage.py collectstatic --noinput, I do not get timed out. However, it takes easily 25 minutes to upload collect. When I run heroku run python manage.py collectstatic --dry-run --noinput, no error is returned either. I am a bit insure what code to post, as this is the first time I attempting to do something like this and I dont see be to getting any error message beside "timeout". I found a few … -
DoesNotExist at /settings : Profile matching query does not exist
@login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == 'POST': if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() if request.FILES.get('image') !=None: image = request.FILES.get('image') bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() return render(request, 'setting.html', {'user_profile' :user_profile}) user_profile = Profile.objects.get(user_profile=request.user) Hello i am trying to run this code for a social app i am creating and i cant proceed further because i keep getting an error message and i cant proceed. please i need help with this thank you.