Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not returning Language Model in forms
I am working on Django Tutorial by MDN on local library I got no error returned in admin site for Language Model, where I have to select language for books. But there is error reflected by Language model on user site while rendering books detail. Error: Language: catalog.Language.none Code and model details are as follows models.py for class Language class Language(models.Model): name = models.CharField(max_length=200, help_text='Enter a book language(e.g. English)') def __str__(self): return self.name models.py for class Book class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField( max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField( Genre, help_text='Select a genre for this book') language = models.ManyToManyField( Language, help_text='Select Language for this book') def get_language(self): return ', '.join(language.name for language in self.language.all()) get_language.short_description = 'Language' class Meta: ordering = ['title', 'author'] def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs= {'pk': str(self.id)}) def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' Book List View Model class BookListView(ListView): model = Book Book Detail View Model class BookDetailView(DetailView): model = Book HTML for … -
How many model fields are too much in a single model django
well I have a doubt, in general you will have many models in a models.py , and that model would have many fields under it(Charfield, foreign key etc...) How many model object are too much in a single model file, for eg if I have 50 model object is it too much? Pls comment your thought on limit for the model object and what's the solution.... -
Django: Handeling data without models
Is there a way to manage data in Django without models? I want to make an app 'Settings' where I can make "global" settings for the webapp. (e.g. Upload a new logo or defining text) But since there would only be one "entry", a model would be excessive. I need to be able to access the data via the REST framework in order to use it in my React frontend. -
I wanted to do a post request with django using ajax
I want to make a request with the method post using ajax. But my django server returns a Forbidden error (CSRF token missing or incorrect.): / Post / it asks me for the csrf token here is my code: -
How to optimize call to database with OneToOneField?
According to the documentation, to optimize the db access : If you only need a foreign key value, use the foreign key value that is already on the object you’ve got, rather than getting the whole related object and taking its primary key. i.e. do: entry.blog_id No problem to use with a ForeignKey and it works as intended. But if I want to do the same with OneToOneField, it is not working : Class CustomUser(Model): ... class Profile(Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, ) Then, if I try to use the same tip as described in the documentation, in a view for example : request.user.profile_id I got the followig error : AttributeError: 'CustomUser' object has no attribute 'profile_id' Of course, it works with request.user.profile.uid but it is not the point here because there is an additional query to the DB. Is it intended ? Is it a con to using OneToOneField ? -
How to validate a paypal webhook json response?
I am integrating paypal subscriptions in a Django project with the webhook method. I got it working well but I'm thinking that is possible that someone malicious can simulate a webhook call and get a free subscription. Currently I have no way to verify if the webhook really comes from Paypal. In other payment with similarities I could set a secret word in the call(from the service provider) and then in the app server validate the call through the secret word. I analysed multiple paypal subscriptions json responses and there seems to be no reference to validate the veracity of the webhook. Anyone experienced on this one? Thanks -
Django LogoutView doesn't logout but redirects to login page
I am new to Django. I have this problem that The auth LoginView works perfectly well but the LogoutView doesnt. It only redirects to login page. from django.contrib.auth import views as auth_views path('user/login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('user/logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout'), Please does anyone know why this could be happening. Is it possible that the default auth LoginView could be working and the default auth Logoutview is not working. Or am I doing something wrong?. Thank you for your answers. -
Group base permission rest api in Django
i am using Django rest framework for my login api. Now i want to login only certain group user through api. I have created group and assigned user to the group.I have created a permission class and used to APIView but it's show ""Authentication credentials were not provided." Here is my permissions.py class from rest_framework.permissions import BasePermission class FanOnlyPermission(BasePermission): def has_permission(self, request, view): if request.user and request.user.groups.filter(name='fan'): return True return False Here is my view.py from rest_framework import views, permissions, status, generics class UserLoginApiView(generics.GenericAPIView): """ User Login Api View """ permission_classes = (FanOnlyPermission, ) def post(self, request): """ Handle POST request :param request: :return: """ serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried through postman. when i print request.user from permission.py it shoed "Anonymous user". -
How to display an array of data in python
I am trying to display the data of this array in django: [('abdo', 'daou', 'charbel', 'hankach', datetime.date(2021, 5, 19), 40000, 30000, 10000),('abdo', 'daou', 'charbel', 'hankach', datetime.date(2021, 5, 19), 40000, 30000, 10000)] This array is given by this python code: def getConsultations(request): con=mysql.connector.connect(host="localhost",user="root",password="",database="djangohospital") mycursor=con.cursor() mycursor.execute(some query) res=mycursor.fetchall() print(res) return render(request,'consultations.html',{'consultations':res}) The sql query is: select ( select firstname from hospitalmanagementwebsite_doctors where hospitalmanagementwebsite_doctors.id = hospitalmanagementwebsite_consultations.doctor_id_id ) as doctor_firstname, ( select lastname from hospitalmanagementwebsite_doctors where hospitalmanagementwebsite_doctors.id = hospitalmanagementwebsite_consultations.doctor_id_id ) as doctor_lastname, ( select firstname from hospitalmanagementwebsite_patients where hospitalmanagementwebsite_patients.id = hospitalmanagementwebsite_consultations.patient_id_id ) as patient_firstname, ( select lastname from hospitalmanagementwebsite_patients where hospitalmanagementwebsite_patients.id = hospitalmanagementwebsite_consultations.patient_id_id ) as patient_lastname, consultation_date, total, paid, leftt from hospitalmanagementwebsite_consultations I want to display these data in html,and i am trying it like this: {% for cons in consultations %} <tr> <td>{{cons[0]}} {{cons[1]}}</td> <td>{{cons[2]}} {{cons[3]}}</td> <td>{{cons[4]}}</td> <td>{{cons[5]}}</td> <td>{{cons[6]}}</td> <td> <a href="/editdoctor/{{doctor.id}}"><span class="btn btn-success">Edit</span></a> <a href="/deletedoctor/{{doctor.id}}" class="btn btn-danger">Delete</a> </td> </tr> {% endfor %} but it is giving me this error: Could not parse the remainder: '[0]' from 'cons[0]' -
When saving PDF via PyPDF2 it's making hidden layers visible
while saving via PDFFileWriter() of PyPDF2 the output file has all previously hidden layers visible. Is there a possibility to delete them from file or at least still hide them? with open(self.file.path,"rb") as f: inputpdf = PdfFileReader(f) output = PdfFileWriter() output.addPage(inputpdf.getPage(pagenumber)) output.write(outputStream) Otherwise, is there another library which supports hidden layers? best regards -
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?