Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to print query of Django ORM
I am using Django ORM query with Extra params. when I try to print the SQL query relevant to that ORM Query,i am getting the below Error message. ORM Query: Record = SAMPLE_TABLE.objects.extra(where=["REPLACE(Message,' ','') "+whereCaseSensitive+" like %s "+query],params=[duplicateCheckMessage]).filter(~Q(iStatus=2),~Q(iAppStatus=2),iEntityID=entityId,iTemplateType=1).first() Message - FieldName , whereCaseSensitive - '', query - ( FIND_IN_SET("test",Testfield)) I am trying to fetch the sql query related to this using print(Record.query) when i run this i am getting Exception as 'NoneType' object has no attribute 'query' Can any one help on this ? -
I am learning Django very hardly [closed]
I am stuck in Django Templates views (parameter) request: Any "request" is not accessedPylance No quick fixes available -
Using d Django Abstract Base User model to enable Profile tab
Using Django Abstract Base User model, How do I make the Profile tab show when a user is logged in. Should I create a model/form for Profile, This is the image of the html file. The backend for signup and login works perfectly fine but when a user signs up or logs in, the nav bar doesn't change at all. Please help {% extends 'base.html' %} {% block title %}Profile{% endblock %} {% block content %} <h1>Hello World</h1> {% if user.is_authenticated %} <a href="{% url 'profile' %}" type="button" class="btn btn-primary">Profile</a> <a href="{% url 'logout' %}" type="button" class="btn btn-primary">Logout</a> {% else %} <a href="{% url 'signup' %}" type="button" class="btn btn-primary">Sign Up</a> <a href="{% url 'login' %}" type="button" class="btn btn-primary">Log In</a> {% endif %} {% endblock %} -
Redirection from the link itself
I have auto logged-in URL for external service but it's one link open on the home page but I want to redirect the user to another page. Is there any way to open the logged-in link at first to save the credentials and then redirect the user to the desired page? -
Getting error on installing a python package regarding mysqlclient
I am currently working on a new project. Trying to install the requirements using pip but getting this error. Using python version 3.6.9 This is the error message I am getting. Collecting en-core-web-sm@ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl (12.8 MB) |████████████████████████████████| 12.8 MB 5.9 MB/s ERROR: mysqlclient-1.4.6-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. Any help would be highly appreciated and thank you in advance to anyone who looks into this. -
Point is not stored in database
I have a location based geodjango project. I got latitude and longitude from user and tried creating a point latitude = float(request.POST.get('latitude')) longitude = float(request.POST.get('longitude')) form.point = Point((latitude, longitude)) but data is not stored into the database, what is the real issue? -
django.core.exceptions.SynchronousOnlyOperation
Upgraded python from 3.6 to 3.8. Getting this error when I tried to connect to Django Admin. Is this because of version change? django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line … -
pip install PyDictionary : python setup.py egg_info did not run successfully. │ exit code: 1 [27 lines of output]
PS D:\projects\english-dictionary-with-django> pip install PyDictionary Collecting PyDictionary Using cached PyDictionary-2.0.1-py3-none-any.whl (6.1 kB) Requirement already satisfied: bs4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (0.0.1) Requirement already satisfied: requests in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (2.28.0) Collecting goslate Using cached goslate-1.5.4.tar.gz (14 kB) Preparing metadata (setup.py) ... done Collecting click Using cached click-8.1.3-py3-none-any.whl (96 kB) Requirement already satisfied: beautifulsoup4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from bs4->PyDictionary) (4.11.1) Requirement already satisfied: colorama in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from click->PyDictionary) (0.4.5) Collecting futures Using cached futures-3.0.5.tar.gz (25 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [27 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 14, in File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_init_.py", line 189, in monkey.patch_all() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 99, in patch_all patch_for_msvc_specialized_compiler() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 169, in patch_for_msvc_specialized_compiler patch_func(*msvc14('get_vc_env')) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 149, in patch_params mod = import_module(mod_name) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\importlib_init.py", line 126, in import_module return bootstrap.gcd_import(name[level:], package, level) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_distutils_msvccompiler.py", line 20, in import unittest.mock File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py", line 26, in import asyncio File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio_init.py", line 8, in from .base_events import * File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 18, in import concurrent.futures File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_init.py", line 8, in from concurrent.futures._base import (FIRST_COMPLETED, File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_base.py", line 357 raise type(self._exception), self._exception, self._traceback ^ … -
Django Loop Through Objects After Bulk .update()
This code runs on cron. So I want to update the status of the objects immediately so that these objects don't get picked up again if a second cron starts before the current one finishes (which will eventually start to happen with my app.) # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') # Loop through the pending emails. for email in emails: The current code doesn't work, as I seem to no longer have access to the objects after I .update() them. This is the workaround I implemented: # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') emails = delivery_que.objects.filter(status='SENDING') # Loop through the pending emails. for email in emails: Is there another better solution I'm missing? I'd prefer not to query the database again to reselect the objects that I should already have access to from the first query. -
Django - filtering related objects
I have a puzzle. These are my models: class StatusGroup(models.Model): name = models.TextField() def __str__(self): return self.name class StatusDetail(models.Model): action = models.CharField(choices=[("CORRECT", "CORRECT"), ("INCORRECT", "INCORRECT")], max_length=64) status_group = models.ForeignKey(to=StatusGroup, on_delete=models.CASCADE, related_name="status_details") def __str__(self): return f"Detail: {self.action}" serializers: class StatusDetailSerializer(serializers.ModelSerializer): class Meta: model= models.StatusDetail fields = "__all__" class StatusGroupSerializer(serializers.ModelSerializer): status_details = StatusDetailSerializer(many=True) class Meta: model = models.StatusGroup fields = [ "pk", "status_details", "name" ] And a view: class Status(viewsets.ModelViewSet): queryset = models.StatusGroup.objects.all() serializer_class = serializers.StatusGroupSerializer authentication_classes = [] permission_classes = [permissions.AllowAny] filter_backends = (DjangoFilterBackend,) filterset_fields = ['status_details__action'] When I hit localhost:8000/api/status?status_details__action=INCORRECT I get: [ { "pk": 2, "status_details": [ { "id": 3, "action": "CORRECT", "status_group": 2 }, { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] Whereas I would like to have: [ { "pk": 2, "status_details": [ { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] How do I force Django to filter the related objects? I can get the result I want in SQL console, but Django adds, all the related objects that belong to the StatusGroup. I have a misconception, but I don't know what that is. -
How to implement Django case insensitive for login without overriding the function get_by_natural_key
I want to make user login case insensitive without overiding the function get_by_natural_key , is there is any way to achieve that with __iexact ? I dont want to overide any internal functions,also note that we add users from django admin so i just want to make the use login case insensitive -
search functionality in Django ORM
if there is two type of data in table :'ABC-DE' and 'ABCDE' if someone search with space and underscore or hyphen so how to search for it without the regular expression -
Deploying Django application using openlitespeed and Gunicorn
Can I deploy a django application using gunicorn and openlitespeed ? Gunicorn can be used with LiteSpeed as mentioned here. But I am not getting any resource for openlitespeed. -
Image is not showing in DRF
I get the serializer data properly but when I click the url of the image it shows error even that image stores properly to the directory. I am not getting what is the issue here. Please suggest me what should I do to show the image. models.py: class TutorProfile(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) travelling_distance = models.CharField(_("Traveling Distance"),max_length=255,null=True,blank=True) where_tutoring = models.CharField(_("Where Tutoring"),max_length=255,null=True,blank=True) taken_out_to_store_account = models.BooleanField(_("Taken To Store Credit Card"),default=False) account_number = models.PositiveIntegerField(_("Account Number"),default=0) routing_number = models.PositiveIntegerField(_("Routing Number"),default=0) upload = models.FileField(null=True, blank=True,upload_to="uploads/%Y/%m/%d", validators=[FileExtensionValidator( ['pdf','jpg','jpeg','pjp','pjpeg','jfif','png','webp'] ) ]) university = models.CharField(_("University"),max_length=255,null=True,blank=True) years_of_experience = models.CharField(_("Years Of Experience"),max_length=255,null=True,blank=True) professional_photo = models.ImageField(upload_to = user_directory_path) bio_teacher = models.TextField() tutor_profile_completed = models.BooleanField(default=False) tutoring_subject = models.ForeignKey( TutoringSubject, on_delete=models.CASCADE,blank=True, null=True) tutor_availablility = models.ManyToManyField( Day) booking_date = models.CharField(_("Booking Date"),max_length=255,null=True,blank=True) def save(self, *args, **kwargs): self.user_type = 'Teacher' # if self.brief_description_of_child is not Null if self.bio_teacher: self.tutor_profile_completed = True super(TutorProfile, self).save(*args, **kwargs) def __str__(self): return self.travelling_distance serializers.py class TutorProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault(),source = 'user.username') image_url = serializers.SerializerMethodField('get_image_url') class Meta: model = TutorProfile fields = '__all__' def get_image_url(self, obj): request = self.context.get("request") return request.build_absolute_uri(obj.professional_photo.url) viewsets.py @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) class TutorprofileViewSet(ModelViewSet): serializer_class = TutorProfileSerializer http_method_names = ["post","delete","get"] queryset = TutorProfile.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): """ This view should return a list of all … -
How to map URLs to views in django?
Goal: 127.0.0.1:8000/about Should give: welcome to to about us page 127.0.0.1:8000/contact Should give: welcome to contact page Problem: Both are giving "page not found at /" This error: https://imgur.com/a/P0uWhWl This is my folder structure: https://imgur.com/a/84uc5Pw This is my main project "taskmate"'s urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), ] And for todolist_app, these are my details: Urls.py: from django.urls import path from todolist_app import views #from . import views urlpatterns = [ path('', views.todolist), path('contact', views.contact,name='contact'), path('about', views.about, name="about"), #the path can be anything. ] Views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def todolist(request): context={'welcome_text':"welcome to todo list app"} return render(request, 'html/todolist.html',context) def contact(request): context={'welcome_text':"welcome to contact page"} return render(request, 'html/contact.html',context) def about(request): context={'welcome_text':"welcome to to about us page"} return render(request, 'html/about.html',context) I'm suspecting that the problem is in my main project urls.py as I've not included any details about contact and about URLs there. So, I did this there. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), path('about/',include('todolist_app.urls')), ] The website runs but the goal isn't achieved. Which is obvious because about/ is getting … -
How do i successfully push my app to heroku using git without getting the 'src refspec does not exist' error?
Wanted to deploy my app on heroku using Git but whenever I try running the command "git push heroku main", I get the following error; error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/edgarcollections.git' -
Django ORM multiple chained JOIN equivalent and aggregation
Given the following Django models (lots shown just as an example, could be more or less nested): class ModelA(models.Model): value = models.IntegerField() class ModelB(models.Model): modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) value = models.IntegerField() class ModelC(models.Model): modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE) value = models.IntegerField() class ModelD(models.Model): modelC = models.ForeignKey(ModelC, on_delete=models.CASCADE) value = models.IntegerField() class ModelE(models.Model): modelD = models.ForeignKey(ModelD, on_delete=models.CASCADE) value = models.IntegerField() # etc... How can we use the Django ORM to do the following operations: e.g. all ModelE for a given modelA, SQL equivalent: SELECT ModelE.* FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 e.g. group all records by some model, SQL equivalent: SELECT ModelC.*, SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 GROUP BY ModelC.id The specific query I'm trying to get is equivalent to the following: SELECT ModelC.value * SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id WHERE ModelA.id = 1 AND ModelD.value … -
How to make django form.errors display only error and not input field affected
Basically, what i am trying to achieve is to remove the name of the input field which in this case is tel and display only the error message using {{ form.errors }} -
AJAX request returns HTML file instead of data. ( Django & Python )
I have a profile page with user posts. People can like/dislike the posts. It works well but it reloads the page, that is why I am implementing AJAX. The route goes like this. Inside the profile view is the "like POST" request ending with a data = { 'likes':post.likes.all().count() } return JsonResponse(data,safe=False)" When clicking on the like button, I can see the data on a blank page if I want to. So I know it is receiving it. Unfortunately, when using AJAX, instead of returning the data. it returns the profile view's return render(request, "profile.html", context) Here is my AJAX code const post_id = $(this).attr('id') const likeText = $( `.like_button${post_id} `).attr('name') const trim = $.trim(likeText) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() || 0 const trimCount = parseInt(likes) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success: function(data){ console.log('success', data) }, error: function(data){ console.log('error', data) } }) Any help would be much appreciated. First time using AJAX, so as much details would be appreciated. -
Django Filtering between dates
I am creating a filter in heatmap where the filter will only extract the date from and to date transaction only. I am not sure with the codes on the filter date but I have not received an error, It only goes top of the page. My HTML for date is MM/DD/YYYY. I am not sure if it helps. But how can I embed filter between dates? Thank you Views def index_map(request): if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__date__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor')) print(df) # coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1] map1 = folium.Map(location=[14.676208, 121.043861], zoom_start=12, ) # df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date']) # mapquestopen fg3=folium.FeatureGroup(name='Map with Markers', show=True) map1.add_child(fg3) # marker_cluster = MarkerCluster().add_to(fg) folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1) # folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1) # folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1) folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1) folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1) plugins.Fullscreen(position='topright').add_to(map1) folium.LayerControl().add_to(map1) for id,row in df.iterrows(): folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], icon=folium.Icon(icon="car", prefix='fa') ,popup=row['accident_factor']).add_to(fg3) # folium.Marker(coordenadas).add_to(map1) # df['user_report__date'] = df['user_report__date'].sort_values(ascending=True) # data = [] # for _, d in df.groupby('user_report__date'): # data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()]) map1 = map1._repr_html_() context = { 'map1': map1 } return render(request, 'index1.html', context) Views class UserReport(models.Model): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, … -
Invalid block tag on line 4: 'endblock'. Did you forget to register or load this tag?
I am getting an error Invalid block tag on line : 'endblock. Did you forget to register or load this tag? {% extends 'main/base.html' %} {% block title %} Home {% endblock %} {% block content %} <h1>Home Page</h1> {% endblock %} #This is tag that the error is referring to This is my base.html in which it inherits from <html> <head> <title>{% block title %} My Site {% endblock %}</title> </head> <body> <div id="content" , name="content">{% block content %}{% endblock %}</div> </body> </html> -
Adding an extra field in a forms.ModelForm
I am trying to create a modelForm in django, however when i try to add an extra field, i get a field error: django.core.exceptions.FieldError: Unknown field(s) (select_file_path) specified for ProjectFile My form is as follows: class ProjectFileForm(forms.ModelForm): select_file_path = forms.Select() class Meta: model = ProjectFile fields = ["project", "form_type", "select_file_path", "file_name", "full_file_path", "author"] widgets = {"author": HiddenInput()} field_order = ["project", "form_type", "select_file_path", "file_name", "full_file_path"] Not too sure whats going wrong here as a model form is defined the same way in the docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#overriding-the-default-fields -
Problem with Back-end DB connection: React + Django + MySQL setup with Docker
I am trying to configure a docker-compose for this stack setup. I am having trouble understanding the whole volume principle and thus made a lot of trial and error. I would like to make my database persistent, of course. I would also very much want my Django container to connect to the MySQL DB. Thank you in advance for your answers. Currently, my docker-compose.yml looks like this: version: '3.8' name: scout services: front-end: container_name: front-end build: context: front-end dockerfile: Dockerfile command: npx serve build restart: always environment: NODE_ENV: production expose: - 3000 ports: - 3000:3000 db: container_name: db image: mysql:latest restart: always env_file: - .env back-end: container_name: back-end build: context: back-end dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 restart: always env_file: - .env expose: - 8000 ports: - 8000:8000 depends_on: - db My .env file: MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_ROOT_HOST=% MYSQL_DATABASE=scout_db MYSQL_USER=guillaume MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password My Back-end Dockerfile: FROM python:3.10 ENV BACKEND_HOME /home/app/back-end RUN mkdir -p $BACKEND_HOME WORKDIR $BACKEND_HOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . ./ EXPOSE 8000 RUN python3 -m pip install --upgrade pip RUN pip install -r requirements.txt And within my settings.py in the Django setup, the DATABASES variable is the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', … -
Why am I receiving KeyError: 'django' when running python manage.py runserver
I get an error when I try to start my server. I'm using Django in a virtual environment. I've spent hours searching for this & can't find an answer Here is the error that I received: Traceback (most recent call last): File "C:\Users\jaiso\.virtualenvs\storefront2-4TwSyq5h\lib\site-packages\django\template\utils.py", line 69, in __getitem__ return self._engines[alias] KeyError: 'django' Here is my installed packages: Package Version asgiref 3.5.2 Django 4.1.2 django-debug-toolbar 3.7.0 django-rest-framework 0.1.0 djangorestframework 3.14.0 drf-nested-routers 0.93.4 mysqlclient 2.1.1 pip 22.2.2 Python-Rest-Framework 0.3.14 pytz 2022.4 setuptools 65.3.0 six 1.16.0 sqlparse 0.4.3 tzdata 2022.4 wheel 0.37.1 -
how to build a get_absolute_url with year, month, day and slug on Djano Rest Framework
I'm building a blog aplication with DRF, and I want it to be able to get my get_absolute_url method for wach post, like: http://127.0.0.1:8001/blog/posts/2022/10/11/my-post And not the default: http://127.0.0.1:8001/blog/posts/1 Here's my model: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(unique_for_date='publish', max_length=250) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') publish = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name="posts" ,blank=True, null=True ) objects = models.Manager() published = PublishedManager() tags = TaggableManager() feature_image = models.ImageField(upload_to="uploads/", null=True, blank=True) class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug], ) And my serializer: class BlogSerializer(serializers.HyperlinkedModelSerializer): author = serializers.ReadOnlyField(source='author.username') url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Post fields = ['url', 'id', 'title', 'slug', 'body', 'author', 'publish', 'created_at', 'updated_at', 'status', 'category', 'feature_image'] Somebody help how to do that, please. thanks!