Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError at /courses/api/course/2/ 'id'
I'm trying the RetrieveUpdateDeleteAPIView and my update method gives me a key error api_views.py from rest_framework.generics import ( RetrieveUpdateDestroyAPIView ) from .serializers import CourseSerializer from .models import Course from django.core import cache class CourseRetrieveUpdateDestroy(RetrieveUpdateDestroyAPIView): queryset = Course.objects.all() lookup_field = 'id' serializer_class = CourseSerializer def delete(self, request, *args, **kwargs): course_id = request.data.get('id') response = super().delete(request, *args, **kwargs) if response.status_code == 204: cache.delete('course_data_{}'.format(course_id)) return response def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) if response.status_code == 200: from django.core.cache import cache course = response.data cache.set('course_data_{}'.format(course['id']), { 'title' : course['title'], 'description': course['description'], 'featured': course['featured'], }) return response serializers.py from rest_framework import serializers from .models import Course class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('title', 'description', 'issued_at', ) def to_representation(self, instance): data = super().to_representation(instance) data['time_passed'] = instance.time_passed() data['is_fresh'] = instance.is_fresh return data urls.py from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from .views import ( CourseListView, CourseDetailView ) from .api_views import ( #CourseList, #CourseCreate, CourseRetrieveUpdateDestroy ) app_name = 'courses' urlpatterns = [ path('', CourseListView.as_view(), name="course_list"), path('course/<int:pk>/', CourseDetailView.as_view(), name="course_detail"), #api-views path('api/course/<int:id>/', CourseRetrieveUpdateDestroy.as_view(), name="course_rud_api"), #path('api/list/', CourseList.as_view(), name="course_list_api"), #path('api/create/', CourseCreate.as_view(), name="course_create_api"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Whenever I try to update an object of … -
Docker with django issue "no module psycopg2" - but it's installed and in requirements.txt
I have the issue, that django_api has the error "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'" psycopg2 is installed -> Requirement already satisfied: psycopg2 in /Users/swestphal/Documents/privateProjects/vue_and_django/ddv/env/lib/python3.9/site-packages (2.8.6) My requirements.txt asgiref==3.3.4 Django==3.2.3 django-cors-headers==3.5.0 djangorestframework==3.12.4 psycopg2==2.8.6 psycopg2-binary==2.8.6 PyJWT==1.7.1 pytz==2021.1 And here my Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 And here my docker-compose.yaml version: '3.8' services: admin_db: container_name: django_admin_db image: postgres restart: always environment: - POSTGRES_DB=django_admin - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - ./data/admin_db:/var/lib/postgresql/data ports: - 33066:3306 admin_api: container_name: django_api build: context: . dockerfile: Dockerfile volumes: - .:/app ports: - '8000:8000' depends_on: - admin_db Thanks for helping! -
The issue is caused by a circular import. Django
Hello colleagues! I was in Django project. I have a problem with my urls In the project I only have one app within that app, I created my urls file to later import it into the urls of the entire project, but when the server was running, it gave me the following error: The included URLconf 'online_store.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My urls.py project from django.contrib import admin from django.urls import path, include urlspatterns = [ path('admin/', admin.site.urls), path('', include('online_store_app.urls')), ] And my urls.py of app # Dajngo from django.urls import path from online_store_app import views urlspatterns = [ # urls site path('home', views.home, name = 'home'), path('services', views.services, name = 'services'), path('store', views.store, name = 'store'), path('blog', views.blog, name = 'blog'), path('contact', views.contact, name = 'contact'), ] -
Reverse for 'post_detail' with arguments '('sport', '')' not found
When I have posts with the same category, I get a reverse error, if posts of different categories do not give errors, apparently the point is in the request submission, but I have no idea how to specify the address,if I remove the code next and previous (in post_detail), then the same categories also work, apparently the point is in them,@Willem Van Onsem hope for your help) urls.py path('<slug:category_slug>/<slug:slug>/', post_detail, name='post_detail'), path('<slug:slug>/', category_detail, name='category_detail'), views.py def post_detail(request, category_slug, slug): post = get_object_or_404(Post, slug=slug) try: next_post = post.get_next_by_date_added() except Post.DoesNotExist: next_post = None try: previous_post = post.get_previous_by_date_added() except Post.DoesNotExist: previous_post = None context = { 'post': post, 'next_post': next_post, 'previous_post': previous_post } return render(request, 'post_detail.html', context) def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) posts = category.posts.filter(parent=None) context = { 'category': category, 'posts': posts } return render(request, 'category_detail.html', context) frontpage.html <a href="{% url 'post_detail' post.category.slug post.slug %}">{{ post.title }}</a> | post_detail.html {% if previous_post %} <a href="{% url 'post_detail' post.category.slug previous_post.slug %}" > <i class="fas fa-angle-left pr-1"></i>< {{ previous_post.title }} </a> {% else %} xxxx! {% endif %} </td> <td></td> <td></td> <td> {% if next_post %} <p align="right"> <a href="{% url 'post_detail' post.category.slug next_post.slug %}" align="right" > {{ next_post.title }}><i class="fas fa-angle-right … -
Why my authors profile pictures are not visible?
So, like in title I have a problem with authors profile pictures which doesn't show as you can see on the photo. I learn Django from Corey Schafer's tutorials and in his video everything was fine, I have no idea why it occurs to me. views.py posts = [ { 'author': 'Eldzej02', 'title': 'Birthday', 'content': 'A birthday is the anniversary of the birth of a person, or figuratively of an institution. Birthdays of people are celebrated in numerous cultures, often with birthday gifts, birthday cards, a birthday party, or a rite of passage.', 'date': '10 May 2021', }, { 'author': 'AFX', 'title': 'Previous day', 'content': 'I didn\'t feel well the previous day, i must say.', 'date': '11 May 2021', }, { 'author': 'AFX', 'title': 'Today\'s day', 'content': 'Today was sunny at the morning but later, during the noon it started raining', 'date': '12 May 2021', } ] def index(request): context = {} if request.user.is_authenticated: context['parent_template'] = 'home.html' context['posts'] = posts else: context['parent_template'] = 'index_not_auth.html' return render(request, 'index.html', context) home.html (problem) {% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block content %} <div class="container"> {% for post in posts %} <article class="media content-section"> <img … -
Error 404 on Browser not showing Static folder file
When i imported os at first and write at the most bottom of settings.py STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static') ] To run my static folder which contains test.txt But when I tried to run it on Opera it shows Page not foun 404. Please tell what Can be the issue in this Django program. -
Maximum value from summation of a field value
I have a model Invoice.Below is a minified version. class Invoice(models.Model): appointment = models.JSONField(blank=False, null=True) doctor_amount = models.FloatField(null=True, blank=True, default=0.00) The appointment field has a doctor and a patient: "appointment": { "id": 14, "doctor": { "id": 103, "name": "MATTHEW"}, "patient": { "id": 10, "name": "JAMES"} } The doctor amount belongs to the doctor.I am hoping to use an SQL query to get the sum of the doctor_amounts that belong to each doctor and then get the doctor with the maximum doctor_amount sum from all the invoices. I have tried a bunch of solutions but I don't think either was close.So I will just leave this open hoping I can get fresh ideas Views.py class TopProvider(APIView): def get(self, request, format=None): all_invoices = Invoice.objects.all() invoices_serializer = InvoiceSerializer(all_invoices, many=True) invoices = invoices_serializer.data try: result = {} return Response(top_doc, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) -
ContentType 26 for <class ''> #2 does not point to a subclass
I'm having the following problem in django when calling a polymorphicserializer inside another serializer ContentType 26 for <class 'forms.models.generic.Province'> #2 does not point to a subclass! My code is as follows : class FieldSetSerializer(serializers.ModelSerializer): questions = SubFieldsPolymorphicSerializer(many=True) class Meta: model = models.FieldSet fields = '__all__' class SubFieldPolymorphicSerializer(PolymorphicSerializer): model_serializer_mapping = { models.Question : QuestionSerializer, models.ScannerQuestion: ScannerQuestionSerializer } The thing is Provinces has no relation with either FieldSet nor the second model. Is it a bug ? -
Frontend frameworks vs Backend frameworks
As someone just started in web development, I was constantly bothered with these terms and really hoping someone could explain some of my questions for me. What is the major difference and similarities between frontend frameworks and backend frameworks? Can I use both in one web project or does they conflict? (Never seen a project that use both front and backend framework). If one project only need one framework, then why are some named frontend frameworks some named backend frameworks. Currently I'm more familiar with Django, a backend framework and in Django, and In Django development, frontend becomes basic html and css, though I was expecting something fancier (something like react components) Never used a frontend framework in project or work. So how does backend stuff work in a frontend framework project? Any answers would be helpful 🙏🏻 -
POST Large amount JSON data via django rest api`
I'm trying to post large amount of JSON data (above 100mb) from react to django rest post api. I have checked with small amount of JSON data (40mb) its working fine, there is no issue. While using large data the browser is too slow and affect the system performance (Hanging). Request you to please suggest for this issue. Is anything to do with django rest api and react for sending large data. -
Make translations for dependencies in Django
I want to provide translations for errors and other strings in my Django application. The problem is that some of the dependencies such as djoser do not provide translations to the languages I need. Is there any way to generate translations for the dependencies in the Django application? It can be done manually every time. I.e. adding all the strings used in the dependencies with their translations in the django.po file but I'm seeking an automated solution. I mean something like this imaginary command: python manage.py makemessages --include-dependencies -
Consume a API with Oath2 in Django
ive been looking for att way to consume an Rest API that uses Oath2 security. Any tips, or guides i can fallow? I have truble finding anything. -
How to use bokeh-server (server_document) behind nginx, with django, on docker?
I'm Dockerising a Django app that serves a graph to users via bokeh server. I have split it into 3 main containers (on an Ubuntu host). (There are some DB containers too, but they're not the issue). These are 'webapp', 'serverapp', and 'nginx'. Using docker compose I can spin these up and hit them via localhost:port, and they all run as they should. Where I'm having difficulty is routing bokeh.server_document requests from 'webapp' to 'serverapp'. This is currently handled in django views: webapp/subapp/views.py def graphview(request, pk): """ Returns the view of requested graph """ script = server_document(url='serverapp';, arguments={"pk":pk,}, ) foo = Foo.objects.get(pk=pk) return render(request, 'graphview.html', {'script':script, 'foo':foo}) Which is rendered in this template: webapp/subapp/graphview.html <head> <script type = "text/javascript" src = "https://cdn.pydata.org./bokeh/release/bokeh-2.0.1.min.js"> </script> <script type = "text/javascript" src = "https://cdn.pydata.org./bokeh/release/bokeh-widgets-2.0.1.min.js"> </script> <script type = "text/javascript" src = "https://cdn.pydata.org./bokeh/release/bokeh-tables-2.0.1.min.js"> </script> </head> <div id="graphviewDisplay"> {% if user.is_authenticated %} {{script | safe}} {% else %} <p> You must be signed-in to see this content </p> {% endif %} </div> and accessible via this url pattern webapp/subapp/urls.py from django.urls import path from subapp import views urlpatterns = [ path('graphview/<int:pk>', views.graphview, name='graphview'), ] Over on 'serverapp' I have the basic bokeh server image (FROM continuumio/miniconda3) … -
Getting this error13 in django while using apache2 server
PermissionError at /upload/ [Errno 13] Permission denied: 'media/Ravi.pdf' Traceback (most recent call last): File "/home/rekrutbot/Documents/project2/resumeparser/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/rekrutbot/Documents/project2/resumeparser/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/rekrutbot/Documents/project2/resumeparser/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rekrutbot/Documents/project2/resumeparser/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/rekrutbot/Documents/project2/resumeparser/start/views.py", line 126, in upload handle_uploaded_file(file, file.name, file.content_type) File "/home/rekrutbot/Documents/project2/resumeparser/start/views.py", line 98, in handle_uploaded_file fo = open("media/" + str(name), "wb+") Exception Type: PermissionError at /upload/ Exception Value: [Errno 13] Permission denied: 'media/Ravi.pdf' -
How can I make a Django REST register/login routes available for Postman
I have a simple Django app with a model called Person: class Person(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) birthday = models.DateField(null=True) gender = models.CharField(max_length=10) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) I have also a User -model like this: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass # add additional fields in here def __str__(self): return self.username I can log in in the admin panel and create new users from there and link my Person -model with a User. What I'm wondering is how can I define for example register/ and login/ routes so I could for example register a new user with Postman? How about authentication, could someone give a simple example how to serve right data to right users? -
Instance on Django is not working, except for picture field
Would you know why Django instance is not working properly in my code below? The idea is to allow the user to edit their articles (called seed in my code) and to do so it's more convenient for them to access the data from the current article. But for some reason, the form stays empty, except the picture field, no matter what. So I was wondering if some part of my code was canceling this instance. Thank you for any help!! views.py def seed_edit(request, slug): to_edit_seed = Seed.objects.get(slug=slug) if to_edit_seed.user.id != request.user.id: return render(request, 'dist/inside/knowledge/404_not_allowed.html') else: if request.method == 'POST': seed_form_edit = SeedForm(request.POST, request.FILES, instance=to_edit_seed) seed_vc_edit = SeedFormVC(request.POST) if seed_form_edit.is_valid() and seed_vc_edit.is_valid(): seed = seed_form_edit.save(commit=False) seed.save() seed_form_edit.save_m2m() if Value_Chain_Seed.objects.filter(seed_id=to_edit_seed.id).exists(): f = Value_Chain_Seed.objects.filter(seed_id=to_edit_seed.id) f.delete() seed_vc_edit.instance.seed = to_edit_seed seed_vc_edit.save() else: seed_vc_edit.instance.seed = to_edit_seed seed_vc_edit.save() messages.success(request,'Your seed was successfully updated!') return redirect(reverse(("knowledge:one_seed"),args=[to_edit_seed.slug])) else: seed_form_edit = SeedForm(request.POST, request.FILES, instance=to_edit_seed) seed_vc_edit = SeedFormVC(request.POST) else: seed_form_edit = SeedForm(request.POST, request.FILES, instance=to_edit_seed) seed_vc_edit = SeedFormVC(request.POST) return render(request, 'dist/inside/knowledge/seed/edit_seed.html', { 'to_edit_seed': to_edit_seed, 'seed_form_edit': seed_form_edit, 'seed_vc_edit': seed_vc_edit, }) form.py class SeedForm(forms.ModelForm): sdg = forms.ModelMultipleChoiceField( queryset=SDG.objects.all().exclude(id=18), widget=forms.CheckboxSelectMultiple, ) industry = forms.ModelMultipleChoiceField( queryset=Industry.objects.all().exclude(id=10), widget=forms.CheckboxSelectMultiple, ) class Meta: model = Seed fields = ["title", "profile_seed","aim_seed", "keywords"] template <div class="row mx-n2"> <form method="post" class="post-form" … -
'OrderItem' object has no attribute 'Product'
app is runing good but when i try to add some items into add item through admin panel then I got this error meanwhile I have add product in my model. error says: AttributeError at /admin/store/orderitem/add/ 'OrderItem' object has no attribute 'Product' code of add item model: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Product.name -
Why doesn't Django serve static files when the dubug=False in settings?
when I tried to run the project, static files are missing, and the settings.debug is set to False. -
Is there a way of writting css that targets links in a summernote?
i need to open my links in a new tab, but those links are in a summer note page, they are in the metadata, not programmed directly. any idea would be highly appreciated. -
Domain in checkout view to enable payments in production environment with Stripe and Django
I have a question, what domain url I should include in the code below to make payments possible in production environment. When I include link to the development website it works on development server (and does not work on the production server), but when I provide the website address related to the production server it doesn't work. What address local/production I should include to make it work? ' @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = '..........' stripe.api_key = STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenti$ success_url=domain_url + '/success?session_id={CHECKOUT_SESSION$ cancel_url=domain_url + '/cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': STRIPE_PRICE_ID, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) ' -
django return link username in model
I know it's not true what's in the code how i can return the usernames that the api is linked to To view in the admin page from django.db import models from django.contrib.auth.models import User class api(models.Model): user = models.ManyToManyField(User) api_key = models.CharField(max_length=120) def __str__(self): return f"api key for: {self.user.username}" -
(2027, 'Malformed packet')
I am using Django with RDS along with Aptible deployement. I started receiving lots (2027, 'Malformed packet') for a while but when I run the same query using Django "shell" OR "dbshell" then the query works fine. I am not able to find any lead around that, found some articles/answers but now one could help. -
Why user permissions are not showing in Django Rest Framework?
I am creating a group, added permissions to that group and assigning that group to a user (as shown in below code): new_group, created = Group.objects.get_or_create(name=grp_name) permission_obj = Permission.objects.get(name=permission) new_group.permissions.add(permission_obj) user.groups.add(new_group) This code works properly but in admin interface the 'user permissions' section is not showing added group permissions -
Pytest new errors connecting to test database
I am running into strange errors I have never seen before on CircleCi where I am running my tests and nearly all are erroring out due to not being allowed to access the database. This is a new error that did not occur last week so I am hesitant to say it is a code change, and it does not happen when I run pyest locally. Here is the error: conftest.py:52: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/local/lib/python3.8/site-packages/django/db/models/query.py:287: in __iter__ self._fetch_all() /usr/local/lib/python3.8/site-packages/cacheops/query.py:271: in _fetch_all return self._no_monkey._fetch_all(self) /usr/local/lib/python3.8/site-packages/django/db/models/query.py:1308: in _fetch_all self._result_cache = list(self._iterable_class(self)) /usr/local/lib/python3.8/site-packages/django/db/models/query.py:53: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1154: in execute_sql cursor = self.connection.cursor() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <django.test.testcases._DatabaseFailure object at 0x7fb361b2d2b0> def __call__(self): > raise AssertionError(self.message) E AssertionError: Database queries to 'test' are not allowed in … -
convert SQL Query to django query?
i want to transform this sql query to django query : profs = django model I tried many times but i can't do it , please help SQL QUERY: select count(distinct prof_id) from profs WHERE "type"='m' and DATE_TRUNC('day',date_updated) > CURRENT_DATE - interval '30 day'