Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override `base.html` Django admin only for one admin form?
I have a model that will be used for getting data from user. There will be only one input field and one button for submitting. Therefor i want to remove other buttons. -
How to specify custom command in docker-compose
I'm using docker for testing my django application. I want to run custom command which runs the test cases from my django application. Here's my docker-compose file: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: start: sh -c "cd sms && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" test: sh -c "cd sms && python manage.py test && flake8" I want to run the test case using something like docker-compose run app test -
How to update a default value of boolean for notification on and off in django rest framework
class NotificationOnOffSerializer(serializers.ModelSerializer): """ To create class for get account function """ is_allow_notify = serializers.BooleanField(required=True) class Meta(object): model = User fields = ('is_allow_notify',) This is my serializer where user model has field is_allow_notify of boolean field and default is true. class OnOffNotification(CustomModelViewSet): """ This view-set is used for check there are any user for this email """ serializer_class = NotificationOnOffSerializer http_method_names = ('post',) permission_classes = (IsAuthenticated,) def create(self, request, *args, **kwargs): """ To check there are any user for this email :param request: wsgi request :param args: argument list :param kwargs: keyword argument object :return: success message or error """ serializer = self.serializer_class(data=request.data, context={"user": request.user}) if serializer.is_valid(): serializer.save() data = User.objects.get(is_allow_notify=True) return custom_response(status=status.HTTP_200_OK, detail=SUCCESS_CODE_VIEW['3042'], data=data) return custom_error_response(status=status.HTTP_400_BAD_REQUEST, detail=list(serializer.errors.values())[0][0]) This is my view.py file where i want notification to be on and off. please correct where i am wrong in my view.py -
Django Rest Framework simplejwt
how to use rest_framework_simplejwt with email for token? I tryed class EmailTokenObtainSerializer(TokenObtainSerializer): username_field = User.EMAIL_FIELD -
CKEDITOR CONFIGS issue
I've added this config CKEDITOR_CONFIGS = { "default": { "removePlugins": "stylesheetparser", } as in https://github.com/django-ckeditor/django-ckeditor#if-you-want-to-use-allowedcontent but nothing changes. What I want is to add some microdata / tags and to be able to view them in the CKEditorWidget. The thing is that they get saved in the db but when displaying the source code in the widget ..... it's just basic HTML elements. widget = CKEditorWidget( config_name='CKEDITOR_CONFIGS', attrs={ # These get injected in the HTML as attributes of the textarea # and used by the ckeditor. 'data-type': 'ckeditortype', 'data-processed': '0', 'data-external-plugin-resources': '[]', } ) and it fails with django.core.exceptions.ImproperlyConfigured: No configuration named 'CKEDITOR_CONFIGS' found in your CKEDITOR_CONFIGS setting. -
Django: how to manage/prevent back arrow event
I know this topic has been already discuss but none of solutions resolve my problem. I have 3 forms that update the same models. I would like to manage/prevent user going back using back arrow. I tried using window.location, window.onhashchange = function () {}, flag session variable but nothing works and I am lost When user click on back arrow from 2nd form to go back to 1st form, I would like either the event is blocked (best), either user is redirected to home page I notice that click on back arrow on the 2nd form do not call index view, reason why 'flag strategy' do not work @login_required @permission_required('unblind.can_unblind') def index(request): if request.method == "POST": form = AveugleProcedureForm(request, data=request.POST or None) if form.is_valid(): unblind = form.save() # database treatment return redirect('unblind:edit', pk = unblind.pk) else: form = AveugleProcedureForm(request) return render(request, 'unblind/index.html', {'form': form}) @login_required @permission_required('unblind.can_unblind') def edit(request, pk): if request.method == "POST": form = AveugleForm(request, data=request.POST or None) if form.is_valid(): # unblind = form.save() # database treatment unblind = Aveugle.objects.get(unb_ide = pk) unblind.unb_pro = form.cleaned_data['unb_pro'] unblind.unb_nom_dem = form.cleaned_data['unb_nom_dem'] unblind.unb_nom_rea = form.cleaned_data['unb_nom_rea'] unblind.unb_dat = form.cleaned_data['unb_dat'] unblind.pat = form.cleaned_data['pat'] unblind.unb_num = form.cleaned_data['unb_num'] unblind.unb_mot = form.cleaned_data['unb_mot'] unblind.save() # contrôler le couple numéro … -
How to output in HTML all objects from Django database?
I just started learning Python and Django. Trying to output on HTML data from the database, I can do it if I set a id, but I wanna have a page where I list all the data from the database in a table. This is my views: from django.shortcuts import render from django.http import HttpResponse from .models import clientes, viagem # Create your views here. def index(request): ls= clientes.objects.all() context= {'ls': ls} return render(request, "booking/home.html", context) And this is my page: {% extends 'bulma/base.html' %} {% block title %}Travel{% endblock %} {% for clientes in clientes %} {% block content %} <table class="table is-fullwidth is-hoverable"> <thead> <tr> <th><abbr title="ID">ID</abbr></th> <th>Nome</th> <th>Apelido</th> <th>Morada</th> <th>Telemóvel</th> <th>NIF</th> </tr> </thead> <tbody> <tr> <th>{{ls.id}}</th> <td>{{ls.nome}}</td> <td>{{ls.apelido}}</td> <td>{{ls.morada}}</td> <td>{{ls.tel}}</td> <td>{{ls.nif}}</td> </tr> </tbody> </table> {% endblock content %} {% endfor %} Can someone point me in the right direction? -
Django login required middleware not working
I'm new to Django and I'm trying to implement the django-login-required-middleware in my project to be able to direct all the users who are not logged in to the index page with login view. I Installed the pip install django-login-required-middleware, added login_required in my INSTALLED_APPS settings and added login_required.middleware.LoginRequiredMiddleware in my MIDDLEWARE. Then in my settings I ignore the views that I want to display to users even when They're not logged in. settings.py LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [ 'index', 'register' ] However, when I run the server, I get the error Not Found: /accounts/login/ [22/Jan/2020 12:27:56] "GET /accounts/login/?next=/ HTTP/1.1" 404 4417 and in my browser: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ It seems like it automatically directs me to the accounts, even though my app is called movies_app and not accounts. Anyone knows how to fix this? Thank you very much! -
how to set django_settings_module environment variable
Please help me on how to set django_settings_module environment variable. Where do I include the setting in the path? Here is the path I set for python: C:\Users\Freddy\AppData\Local\Programs\Python\Python38-32;C:\Users\Freddy\AppData\Local\Programs\Python\Python38-32\Scripts. What prompted me to seek help is that in the command prompt I typed "django-admin" and I got the following message "note that only Django core commands are listed as settings are not properly configured before accessing settings" -
I want to display python opencv video on django html page how can i achive it
I need to display video frame on web browser in django html page please guide me how to achieve it @gzip.gzip_page def home(request): try: return StreamingHttpResponse(home_video(), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass def home_video(): cap = cv2.VideoCapture('D:/AI/videoplayback.mp4') if (cap.isOpened() == False): print("Error opening video file") while (cap.isOpened()): ret, frame = cap.read() if ret == True: cv2.resizeWindow('image', 1000, 1000) cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break cap.release() cv2.destroyAllWindows() -
Nested Inline in Django?
I have a Teacher model: class Teacher(models.Model): """ The Teacher model. """ INITIALS = ( ("MR", "Mr."), ("MRS", "Mrs."), ("MS", "Ms."), ) initials = models.CharField( max_length=10, choices=INITIALS, default="MR" ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.first_name+" "+self.last_name # Control model features class Meta: verbose_name = 'Teacher' verbose_name_plural = 'Teachers' Then a Class Model that points to Teacher (The Teacher is Class Teacher of that Class): class Class(models.Model): class_name = models.CharField( max_length=10, default=None ) division_name = models.CharField( max_length=10, default=None ) class_teacher = models.ForeignKey( Teacher, on_delete=models.SET_NULL, default=None, null=True, blank=True) def __str__(self): return self.class_name+" "+self.division_name # Control model features class Meta: verbose_name = 'Class' verbose_name_plural = 'Classes' Then I have a Student Model: class Student(User): religion = models.ForeignKey( Religion, on_delete=models.SET_NULL, null=True) caste = models.ForeignKey(Caste, on_delete=models.SET_NULL, null=True) date_of_birth = models.DateField(default=timezone.now) parent_name = models.CharField(max_length=255, default=None) address = models.CharField(max_length=255, default=None) phone_number1 = models.CharField( "Phone Number 1", max_length=10) phone_number2 = models.CharField( "Phone Number 2 (optional)", max_length=10, blank=True) def __str__(self): return self.first_name+" "+self.last_name # Control model features class Meta: verbose_name = 'Student' verbose_name_plural = 'Students' And then there's an Admission model that points to both Student and Teacher: class Admission(models.Model): admission_date = models.DateField() class_teacher = models.ForeignKey( Teacher, on_delete=models.SET_NULL, null=True) student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) … -
Appending retrieved data to python dictionary in django views
So I am trying to append data to the below mentioned dictionary d, and I am getting confused about where to begin. Given below is the segment of the code I am referring to. d={} vendor_choice = request.POST["inlineDefaultRadiosExample"] date_choice = request.POST["inlineDefaultRadiosExample1"] x = employee.objects.all() for i in x: if date_choice == 1: d.update(transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=30))) elif date_choice == 2: d.update(transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=60))) else: d.update(transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=180))) print(d) I want to append queries fetched by the transaction.objects.filter to the dictionary d. How to proceed with it? Any help is appreciated. -
Django - How to interact with GitHub with permissions?
I'm trying to create Django app with below functionality. User A owns several GitHub organizations. A connects my app and give access permission to all the organizations he have. My app registers github webhook into their repositories automatically to notify events to my app. I found django-github-webhook package. But it seems it should register webhook manually first. Can you please suggest some helpful documentation? -
Django : how to use multiple databases?
I'm building a website with Django and I need to have a gps coordinate attribute in my User model. I will be using GeoDjango, which needs PostgreSQL and, since my website is already working with the sqlite3 default database, I need to install a PostgreSQL database to the project in order to create a Coordinates model in it and link it to the User model of the sqlite database. I found lots of tutorial on internet about "how to use multiple databases" but they are all very basics. Since I'm quite new to Django and web programming, I'm needing a in-depth tutorial about multiples databases. I have a few questions and I thank you in advance if you can answer one or more of those ! Note : I'm using windows 10 with PostgreSQL installed with the ubuntu app of windows. 1) How can I create and initialize the file for the new database in the Django project ? The file db.sqlite3 was automatically created with the Django project initialization so how can I create an other one ? 2) Do I need to use a new app for the GPS coordinates or can I use an existing one ? … -
Running web application on specific port
I have django and angular web application.It's my first deployment, sorry about this question. I have server that I can use it by ssh and I want to create script file on server to execute my app on specific port.I don't know how to fill .sh file to execute my app on port 80. -
Django custom error handling when the url supplied does not match with any URL in ROOT_URLCONF
How can I send a custom error message to front end when the endpoint coming from front end does not match with any URL in ROOT_URLCONF in settings.py. Currently if URL is not found in ROOT_URLCONF, a 403 error is raised and the entire html content is going in the error message. How to send a custom error message in this case. -
"Model class myproject.models.MyModel doesn't declare an explicit app_label during" During Django test
With Django 2.2.9 I'm getting the following error when I try to run ./manage test File "/home/simernes/workspace/myproject/myapp/test/test_functions.py", line 3, in <module> from ..functions import make_response File "/home/simernes/workspace/myproject/myapp/functions.py", line 2, in <module> from .serializers import MyModelSerializer, \ File "/home/simernes/workspace/myproject/myapp/serializers.py", line 2, in <module> from .models import MyModel, \ File "/home/simernes/workspace/myproject/myapp/models.py", line 7, in <module> class MyModel(models.Model): File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. It appears that simply by importing something from the file containing a class extending Model this error occurs, because it happens with the following test definition: from django.test import TestCase from ..functions import make_response class MyTestCase(TestCase): def setUp(self): pass def test_make_response(self): self.assertTrue(True) Is there any way to solve this? Installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'corsheaders', 'myapp', ] -
Add up django fields from several models
My application has several post types, each post type is a single model, each of these models has a field called "up_vote" and "down_vote". Now i want to display the user a add-up of all those fields, so that i calculate request.user.model1.up_vote + request.user.model2.up_vote + request.user.model3.up_vote and same for down_vote. But i dont know how the query has to look like at my views models.py # code example class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=30) ... up_vote = models.IntegerField(default=0) down_vote = models.IntegerField(default=0) class Post_Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE, null=True) voted = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: unique_together = ('voter', 'voted') thx for reading :) -
Django, double link or script protection
I would like to know if in Django there is a specific tag to protect template against static file double inclusion? In my case I have multiple distinguish app then all of them use bootstrap. It would be great if it's possible to include header of each app without to take care about if bootstrap.min.css is include more than one time. _base.html <head> {% block head %} <link href="/static/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/mypr/index.css" rel="stylesheet"> {% endblock %} </head> map.html {% block head %} {{ block.super }} {% map_head %} {% endblock %} templatetags/map.py @register.inclusion_tag('map/head.html') def map_head() : pass map/head.html <link href="/static/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/leaflet/dist/leaflet.css" rel="stylesheet"> <link href="/static/map/css/map.css" rel="stylesheet"> Thank you. -
How to import modules from multiple app in Django shell using relative path?
I'm trying to load classes of multiple application in Django shell-plus but I receive an error saying it cannot find the module. I would like to tell the shell interpreter to load a module inside my app directory using the relative path. How can I do that? Shell from .app1.models import Class1 from .app2.models import Class2 ModuleNotFoundError: No module named '__main__.app1'; '__main__' is not a package Files structure /project -- __init__.py -- settings.py -- /app1 ---- __init__.py (empty) ---- models.py -- /app2 ---- __init__.py (empty) ---- models.py /project/__init__.py from __future__ import absolute_import, unicode_literals default_app_config = 'project.app1.apps.App1Config' -
How to display a dataframe from views to django template
I have created an application in django where i read a csv file and stored it in media folder. Next i converted the csv file into pandas dataframe now i need to render the dataframe into my template and display it as a bootstrap table(atleast a general table tag). How should i send the dataframe and how to display it as bootstrap table in template. Thank You Views.py def dq(request): if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) file_path = settings.MEDIA_ROOT + '\\' + uploaded_file.name df = pd.read_csv(file_path) return render(request,'dq.html') -
Static files not loading in production
Moved my project to my production server on namescheap. Noticing however that while the pages are loading the static files (css,js and images) do not seem to be loading. I have tried to read the django documentation to understand if there are any settings that I need to change when moving from development to production and tried to read similar questions on stackoverflow but still have the same issue. This is what I have in my settings ... DEBUG = False # DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ["thegradientboost.com", "localhost", "127.0.0.1","http://thegradientboost.com/gradientboost"] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'classroom', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', # 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'django_school.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], '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 = 'django_school.wsgi.application' ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'allstaticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'public/static'), ] CRISPY_TEMPLATE_PACK = 'bootstrap4' #deployment SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 60 SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD = True SECURE_REFERRER_POLICY = "same-origin" wsgi: import os from django.core.wsgi import … -
DRF need values instead of ID
This is my serializer class class ProjectSerializer(ModelSerializer): class Meta: model = Project exclude = ['deleted_at'] This is Models.py class MandatoryFields(SoftDeletionModel): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_created",null=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_updated",null=True) created_date = models.DateTimeField(auto_now_add=True,null=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True class Project(MandatoryFields, Model): project_name = models.CharField(max_length=255, blank=True) project_areas = models.CharField(max_length=255, blank=True) project_manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name="%(app_label)s_%(class)s_project_manager") start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) REQUIRED_FIELDS = [] def __str__(self): return self.project_name I am getting Id's for the foreign keys created_by,updated_by,project_manager . But I need the values of those I have tried the following class ProjectSerializer(ModelSerializer): created_by = SlugRelatedField(read_only=True, slug_field='created_by') class Meta: model = Project exclude = ['deleted_at'] But I am getting null values. -
"python: can't open file 'src/profiles_project/manage.py': [Errno 2] No such file or directory" when running Docker-compose up
I have been following this tutorial https://youtu.be/610jg8bK0I8?t=3m When running docker-compose up (time= 3:00), I get web_1 | python: can't open file 'src/profiles_project/manage.py': [Errno 2] No such file or directory byob-profiles-rest-api-docker_web_1 exited with code 2 even if my manage.py is in D:...\byob-profiles-rest-api-docker\src\profiles_project Check it out: I bet the code needs the permission to open manage.py. If so, how do I allow it to do it? Here is the complete traceback: $ docker-compose up Building web Step 1/7 : FROM python:3 3: Pulling from library/python 8f0fdd3eaac0: Pull complete d918eaefd9de: Pull complete 43bf3e3107f5: Pull complete 27622921edb2: Pull complete dcfa0aa1ae2c: Pull complete 61cf1e8f9385: Pull complete 6cb6c5f51ace: Pull complete 6c164355f57f: Pull complete 11f88e8d4be6: Pull complete Digest: sha256:e5a6b05bf9f991ac2a07007a60a132a98a67db67ff84b0687fceb875815ed566 Status: Downloaded newer image for python:3 ---> 1f88553e8143 Step 2/7 : ENV PYTHONUNBUFFERED 1 ---> Running in de506e7625bb Removing intermediate container de506e7625bb ---> 34e1e4bfc80b Step 3/7 : RUN mkdir /code ---> Running in b855df518561 Removing intermediate container b855df518561 ---> f3d222639153 Step 4/7 : WORKDIR /code ---> Running in e437636da59a Removing intermediate container e437636da59a ---> 1bb45a02ac18 Step 5/7 : ADD requirements.txt /code/ ---> 1a0c34f20c6d Step 6/7 : RUN pip install -r requirements.txt ---> Running in 0b572730b40c Collecting appdirs==1.4.3 Downloading https://files.pythonhosted.org/packages/56/eb/810e700ed1349edde4cbdc1b2a21e28cdf115f9faf263f6bbf8447c1abf3/appdirs-1.4.3-py2.py3-none-any.whl Collecting Django==1.11 Downloading https://files.pythonhosted.org/packages/47/a6/078ebcbd49b19e22fd560a2348cfc5cec9e5dcfe3c4fad8e64c9865135bb/Django-1.11-py2.py3-none-any.whl (6.9MB) Collecting djangorestframework==3.6.2 Downloading https://files.pythonhosted.org/packages/d2/79/e68b85647c539a155c6f6a0738208eb5ed09c61adabfd6f2e6edde944529/djangorestframework-3.6.2-py2.py3-none-any.whl … -
Add a Matplotlib plot to Reportlab (platypus) directly
I want to add 3 different charts that I make using Matplotlib to a Reportlab pdf. I know I can save the plot and then add image on the report and then delete the image (since I don't want the image anymore). But I am curious if there is some way to do it directly using a b64 image or something like that. Moreover, I already have the charts made in Google charts on the client side, but since I resize them based on window size of the user, It is giving me weird images for my report. If there is a way to get consistent sized images from the Google charts itself, It'll be really cool. All suggestions are appreciated. Thanks