Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(1242, 'Subquery returns more than 1 row') Django
I'm trying to get trending tags with the number of posts that are tagged with them. Everything seems fine but i'm facing a Subquery returns more than 1 row error.. # Model class Tag(models.Model): name = models.CharField(max_length=40, primary_key=True, db_index=True) created_at = models.DateField(auto_now_add=True, db_index=True) updated_at = models.DateField(auto_now_add=True, db_index=True) # Get trending tags tags = Tag.objects.filter(updated_at=timezone.now()).annotate( posts = Subquery( Post.objects\ .filter(text__icontains=OuterRef('pk'), deleted_at__isnull=True)\ .values('id')\ .annotate( count = Count('pk') )\ .values('count'), output_field=IntegerField() ) ).values('name', 'posts').order_by('-posts')[:5] -
how to solve Improperly Configuation error in django
I am developing a crud application using django,using Class based views, Create and retrieve functions are working properly but detail function don't here is my code snippets Error views.py class Details(DetailView): context_object_name = 'user_details' model = models.CreateUser template_name = 'main/detail_form.html' Models.py class CreateUser(models.Model): name = models.CharField(max_length=256) age = models.IntegerField() email = models.CharField(max_length=256) gender = models.CharField(max_length=50) def __str__(self): return self.name def get_absolute_url(self): return reverse('main:create', kwargs={'pk': self.pk}) app/urls.py urlpatterns = [ url(r'^create/$', views.Create.as_view(), name='create'), url(r'allUsers/$', views.UsersList.as_view(), name='allUsers'), url(r'^allUsers/(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail') ] main/urls.py path(r'user/', include('main.urls')) -
Django Rest: how to filter the data in twice nested model serializer?
I have models: class regularGrade(models.Model): lesson = models.ForeignKey(Timetable) studentID = models.ForeignKey(Student) ... class Timetable(models.Model): subjectID = models.ForeignKey(Subject) cohortID = models.ForeignKey(Cohort) ... class Subject(models.Model): cohortID = models.ForeignKey(Cohort) ... class Cohort(models.Model): ... class Student(models.Model): cohort = models.ForeignKey(Cohort, on_delete=models.CASCADE) ... I am trying to reach to all regularGrade of all students of 1 cohort for 1 subject. I am using the first serializer above to get it:: class StudentGradesOneSubjectSerializer(serializers.ModelSerializer): regularGrades = RegularGradesBySubjectSerializer(many=True) class Meta: model = models.Student fields = ('studentName','pk','cohort','regularGrades',) def get_regularGrades(self, student): grades = models.regularGrade.objects.all() return grades class RegularGradesBySubjectListSerializer(serializers.ListSerializer): def to_representation(self, data): **data = data.filter(lesson.subjectID=self.context["subjectID"])** return super(RegularGradesBySubjectListSerializer, self).to_representation(data) class RegularGradesBySubjectSerializer(serializers.ModelSerializer): class Meta: model = models.regularGrade fields = ('mark', 'lesson',) list_serializer_class = RegularGradesBySubjectListSerializer I am trying to filter by the line below: data = data.filter(data.lesson.subjectID=self.context["subjectID"]) However it is impossible because subject ID of lesson is not related to regularGrade, those are 2 different models. Is it possible to get all grades of one cohort of ONE subject? This is what I get without filter (data = data): [ { "studentName": "Alexander Surname", "pk": 22, "cohort": 5, "regularGrades": [ { "mark": 3, "lesson": 9 }, ] }, { "studentName": "FirstName SecondName", "pk": 23, "cohort": 5, "regularGrades": [ { "mark": 2, "lesson": 8 } ] … -
Setting up Celery with Redis on a server for a Django app
I am trying to set up my django project to work with Celery and Redis. I have no issues running it locally, but I can't get it working in the production server. My hosting recommends to setup Redis using unixsocket and run redis in a screen: port 0 unixsocket /path/redis.sock This all works, when I run redis I get: * The server is now ready to accept connections at /here-comes-my-path/redis.sock Now I have issues: How do I verify the connection? redis-cli -p 0 returns Could not connect to Redis at 127.0.0.1:0: Can't assign requested address not connected> How do I start celery worker? Running celery -A rbwpredictor worker -l info returns (I've xed sensitive data): Traceback (most recent call last): File "/usr/home/xxxx/.virtualenvs/xxxx/bin/celery", line 6, in from celery.main import main File "/home/xxx/domains/xxxx/public_python/xxxx/celery.py", line 6, in from celery import Celery ImportError: cannot import name 'Celery' My Celery settings in settings.py: CELERY_RESULT_BACKEND = 'django-db' CELERY_STATUS_PENDING = 'PENDING' CELERY_STATUS_STARTED = 'STARTED' CELERY_STATUS_RETRY = 'RETRY' CELERY_STATUS_FAILURE = 'FAILURE' CELERY_STATUS_SUCCESS = 'SUCCESS' As mentioned above locally everything works fine, it's the configuration on the server I struggle with. -
Remote IP in deploying Gitlab
I'm learning about Django and Gitlab. I have written a simple Django web, I want to deploy it on Gitlab CI/CD with docker, but in deploy.sh file I don't know which IP to deploy within SSH. deploy.sh #!/usr/bin/env bash ssh -o StrictHostKeyChecking=no root@remote_IP << 'ENDSSH' cd /webping docker login -u $REGISTRY_USER -p $CI_BUILD_TOKEN $CI_REGISTRY docker pull registry.gitlab.com/vuthehuyvnu/webping:latest docker-compose up -d ENDSSH Where can I find that remote IP?? Thank you -
Team Allocation Optimisation with PuLP
Background: I am trying to allocate students to teams where each student will have a series of preferences to other students being in their teams. I have an objective function which I want to minimise along with 3 constraints for the function (written in the image below). In my DB I have a set of students along with their preferences (such as student i rating student j as their 3rd choice) Mathematical Formula: https://i.stack.imgur.com/3v0J7.png Question: I am unsure whether I have written the constraints and variables correctly, and I can't find any close resources that do team allocation with preferences. I'm very new to PuLP and am struggling to figure out if what I've written is correct syntatically, thanks for any help! Here is the code that I have written in my file: from pulp import * model = LpProblem("Team Allocation Problem", LpMinimize) ############ VARIABLES ############ students = [1,...,20] n = 20 # this will be imported from the database r = [[...],...,[...]] team_sizes = [5,5,5,5] num_teams = len(z) # x(ik) = 1 if student i in team k x_vars = [[LpVariable("x%d%d" % (i,k), cat='Binary') for k in range(num_teams)] for i in range(num_students)] # y(ijk) = 1 if student i … -
Behavior from docker-compose command not the same as run in Dockerfile
I have a Django project and I've been struggling with the automation of the static files generation. My project structure has a docker-compose.yml file and a Dockerfile for every container image. The docker-compose.yml file for my project: version: '3' services: web: build: ./dispenser command: gunicorn -c gunicorn.conf.py dispenser.wsgi volumes: - ./dispenser:/dispenser ports: - "8000:8000" restart: on-failure nginx: build: ./nginx/ depends_on: - web command: nginx -g 'daemon off;' ports: - "80:80" volumes: - ./dispenser/staticfiles:/var/www/static restart: on-failure The Dockerfile for the Django project I'm using: FROM python:3.7.4 ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ WEBAPP_DIR=/dispenser \ GUNICORN_LOG_DIR=/var/log/gunicorn WORKDIR $WEBAPP_DIR RUN mkdir -p $GUNICORN_LOG_DIR \ mkdir -p $WEBAPP_DIR ADD pc-requirements.txt $WEBAPP_DIR RUN pip install -r pc-requirements.txt ADD . $WEBAPP_DIR RUN python manage.py makemigrations && \ python manage.py migrate && \ python manage.py collectstatic --no-input After several hours of test and research I've found out that running the collectstatic and migrations commands from the Dockerfile doesn't produce the same result as doing it via the command argument on the docker-compose.yml file. If I do it as shown above, when time for running the collectstatic command comes, only the "staticfiles" folder is generated (no files inside it). Also database migrations weren't applied (note that I'm using the … -
Image not displaying with status code 200 (even not displaying in admin page too)
github link : https://github.com/Raj-Cyber/project In admin upload image is success but when u click the image link in admin page it does not display the image but the status code is 200. Hence the media link is also behaving the same in html page. Please help me fix this bug. Thanks -
Django Mutlipleobjects at get() after migrating SQL to POSTGRES
Ok i was having problems with microsoft azure about OperationDatabase Locked, so i switched to POSTGRES db, here are the steps that i did on the project directory with activate virtualenv python manage.py dumpdata > db.json then i after changing db on the settings.py file i loaded the json and all sql stuffs were copied to the postgres db. now the problem that i am facing is that i used context processors for most of the projects def carousel(request): return { 'carousel': Carousel.objects.values('text1').get() } def carousel_1(request): return { 'carousel_1': Carousel.objects.values('text2').get() } This is the error that i am getting now get() returned more than one Carousel -- it returned 2 What might have i done wrong? The same code was working well on sqllite3, another problem is that when i open django admin page everything is duplicate have been duplicated like fields, names etc. my django admin -
Create action that creates and downloads a zip file of qr codes in Django
This is my code on my local server def make_qr_codes(modeladmin, request, queryset): for obj in queryset: qr = qrcode.QRCode( version=1, box_size=15, border=5 ) qr.add_data(obj.slug) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') img.save(r'media\Qr_codes\ ' + obj.name + ".png") So I'm selecting some objects and then create qrcodes based on their slug and adding them to the media directory. Now I've deployed my app to Heroku and I don't want to store the images on some server/filehost, I only want the admin user to get a zip file of the qrcodes of the selected objects. The approaches I've seen and tested all add local files to the zip. -
AWS Elastic Beanstalk 500 Internal Server Error with Django
I deployed a django server using AWS Elastic Beanstalk a week ago. There were no issues after I deployed the server and it worked without problems. However, I accessed today the server, there are Internal Server Error. I did not deploy any edited things on the server but it shows 500 errors. I have no ideas about this issue. Does anyone give advice on this? -
How to convert number to month name in Django?
This is what looks like the DateField data received from a form. I need to show a month name not a number in my dropdown list. This is what my dropdown list looks like How do I convert the number into a month name? -
ModuleNotFoundError : no module named : crispy_forms
I can import crispy_forms but when I run python3 manage.py runserver it say no module named crispy_forms, I can not why it is, because when I pip3 list, I can see django-crispy-forms. so I attach my setup for interpreter, really need your help interpreter setup image and Error message in terminal >>> python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/eunwoo/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/eunwoo/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/eunwoo/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/eunwoo/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' -
How to update Image in django rest framework
I am building an app using django rest freamwork & react js . I am sending some pictures as file from react to django using formdata via axios.post method. Then i retrieve those image from django to react as image url created by django. But if i want to edit an image or delete image then axios.put method not working. It shows "The submitted data was not a file. Check the encoding type on the form". Is there any way to update image via rest api. here is my code : Serilizers.py class PatientImageSerializer(serializers.ModelSerializer): Image1 = serializers.ImageField(use_url=True) class Meta: model = PatientImage fields = '__all__' Views.py: parser_classes = (MultiPartParser, ) serializer_class = PatientImageSerializer queryset = PatientImage.objects.all() React.js: for(let j=0 ;j< PatientImages.length ; j++){ form_data.append('Image'+[j+1],PatientImages[j]); } form_data.append('RPathy', grading.rPathy) form_data.append('MPathy', grading.mPathy) form_data.append('Lazer', grading.lazer) form_data.append('UnSpec', grading.uSfd) form_data.append('Remarks', grading.reMarks) axios.put(`http://127.0.0.1:8000/patientimage/12/`, form_data) .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log(err) }) -
How to send email once in Django admin after i have changed user inlines?
For example, let's say I have code like this: models.py class Application(models.Model): user = models.ForeignKey("account.Account", on_delete=models.CASCADE) status_choices = [(1.0, "Waiting for info"), (2.0, "Processing"), (3.0, "Problem detected"), (4.0, "Accepted"), (5.0, "Rejected")] status = models.FloatField(choices=status_choices, default=status_choices[0][0]) admin.py class ApplicationInLine(admin.TabularInline): models = Application @admin.register(Account) class AccountAdmin(UserAdmin): inlines = (ApplicationInLine,) Now on the Django admin page, I want to change user application status. If I have only one application under one user, then it is fine, I can use signals to notify the user via email that status has been changed. But if I have more than one application under one user, for example 4 and I want to make change all application statuses at once before I click Save button on admin, then signals will trigger 4 times. I have already tried to overwrite the save method too, but I have got the same results. Does anybody know how can I send an email only once, even when there has been a change in multiple applications under one user? -
Custom logout page not landing
On clicking logout button the custom landing page is not landing,but the default django-admin page is landing! hey! I am trying to learn django from the book django2 by example so i created a dashboard page which is having a logout button but on clicking the button it shows the django-admin landing page and not the one I created ! urls.py(main-project) from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('account.urls')), ] urls.py(account-app) from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ # post views path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='log_out'), path('', views.dashboard, name='dashboard'), # change password urls path('password_change/',auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] It should show thisenter image description here but apparantely it's showing the django-admin default logout pageenter image description here logged_out.html {% extends "base.html" %} {% block title %}Logged out{% endblock %} {% block content %} <h1>Logged out</h1> <p>You have been successfully logged out. You can <a href="{% url "login" %}">log-in again</a>.</p> {% endblock %} -
How can I connect django to mqtt broker?
I need to send some data from django wed server to board (esp8266), using MQTT protocol. I have problems with finding information about how to connect django and mqtt-broker. How can I implement this? -
How to get client's ip address from http reqeust?
I want to know is there a way to get ip address from Http request. The method i Googled doesn't work The code as follow: from django.http import JsonResponse from base.utils import * def check(request): ip = request.headers['X-Real-IP'] return JsonResponse(Result(RESULT_SUCCESS, "查找成功").get_json_str(ip)) -
How to extract text as kwargs of pdf in django
I have a pdf file that contains CV.Now I want to extract the Skills as kwargs so that I can use it for other purpose. How can I do it using any third party apps -
how can i access the objects in different view functions
i am trying to create a header.html to create a header for all pages and i want to create a dropdown for navigate b/w pages and i want to get the title from model i have two view here one for home page and for header page home page view: def homepage(request): aboutinfo = aboutpage.objects.all() servicesinfo = services.objects.all() programinfo = prgm.objects.all() return render(request, 'index.html', {'aboutinfo': aboutinfo, 'servicesinfo': servicesinfo, 'programinfo': programinfo}) header view def header(request): info = services.objects.all return render(request, 'header.html', {'info':info}) when i tried the info its not working and i tried the service info from home page it working only index page` <li class="menu-has-children"><a href="#services">All Services</a> <ul> {% for services in /* what is here */.all %} <li><a href="{% url 'details' services.slug %}">{{ services.title }}</a></li> {% endfor %} </ul> </li> -
How to send HttpResponse in Django with error message and error status
I want to send the HttpResponse from Django API when any error occur in the API. I am sending normal response from Django API in Json form inside a HttpResponse to the frontend. But when I use try and except, I can send the error in Json form to the frontend but still the status code is 200 Ok. If I am sending status='Some Error Code' in HttpResponse then how to send the error in JSON form. How to send both Error Code and Error message in HttpResponse in Django? -
How to send HttpResponse in Django with error message and error status
I want to send the HttpResponse from Django API when any error occur in the API. I am sending normal response from Django API in Json form inside a HttpResponse to the frontend. But when I use try and except, I can send the error in Json form to the frontend but still the status code is 200 Ok. If I am sending status='Some Error Code' in HttpResponse then how to send the error in JSON form. How to send both Error Code and Error message in HttpResponse in Django? -
Django - How can I remove some of the text displayed on the admin 'add user' page?
I currently have a system where the admin is the only way to add a user to the site. All they need to do is put in thier email and they will be sent a link allowing them to create a password and set up thier account. This is all working fine. The problem I have is shown in the image below, when the admin goes to add the user through the interface I am still greeted with the old text from the page, which I obviously do not want. "First, enter a username and password. Then, you'll be able to edit more user options." I obviously just want this original text removed and my description about entering an email to remain. I have found the text in the "add_form.html", but I dont believe the right solution is to delete it from there, so I am looking for a way to remove that text? -
How could I add the password placeholder in the ModelForm?
Django 1.11 I want to add a placeholder in all the forms I have, I want to know why the password field has (None value)? this is an image for clarification.enter image description here I need to know how can I add password placeholder by forms.PasswordInput forms.py from django.contrib.auth.forms import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class EditForm(UserForm): def __init__(self, form): super(EditForm, self).__init__(form) for key, field in self.fields.items(): if isinstance(field.widget, forms.TextInput) or \ isinstance(field.widget, forms.EmailInput) or \ isinstance(field.widget, forms.PasswordInput): field.widget.attrs.update({'placeholder': field.label}) register.html {% extends 'base.html' %} {% block title %} Register {% endblock %} {% block body %} <div class="register"> <div class="container"> <h1>Register</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Registier</button> </form> </div> </div> {% endblock %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.views import View from .forms import UserForm, EditForm from django.contrib.auth import authenticate def index(request): return render(request, 'account/index.html') class UserRegister(View): form_class = EditForm template_name = 'account/register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] … -
How to access ProtectedError variables in a view?
When django throws a ProtectedError (because on_delete=models.PROTECT in some model field), it runs this source code to render the response: class ProtectedError(IntegrityError): def __init__(self, msg, protected_objects): self.protected_objects = protected_objects super().__init__(msg, protected_objects) def PROTECT(collector, field, sub_objs, using): raise ProtectedError( "Cannot delete some instances of model '%s' because they are " "referenced through a protected foreign key: '%s.%s'" % ( field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name ), sub_objs ) When handling this error, I know it's easy enough to override delete() on the view: def delete(self, request, *args, **kwargs): self.object = self.get_object() try: self.object.delete() messages.error(self.request, 'Ok') except ProtectedError: messages.error(self.request, 'Whoops') return HttpResponse(json.dumps(data),mimetype="application/json") However, I'd like to be more specific in the message I pass. How can I access field.remote_field.model.__name__, sub_objs[0].__class__.__name__, and field.name from the PROTECT function in my view?