Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to transfer data from several models to one summary by the smallest size of one of the models?
I have three databases - table models (Django Models ). In which there is a different amount of data - a different number of rows of elements in the database table. One table has 100 rows - the other model table has 150 rows. I'm going to migrate the data from these models to another one - a general summary table model. Sequentially transferring data from each model. How can I do this - to transfer data to the summary table - only by the size (number of rows) of the smallest model table? -
Django manage command run scrapy spider
I have a parser on scrappy that works correctly and returns me a dictionary under the car key yield { 'car': car } it lies in the same directory with the Django project, which has a model in which I can put these dictionaries. my task is to write a django manage command in which I can catch this stream of data from the spider during its operation: class Command(BaseCommand): help = 'run all scrapper scripts' def handle(self, *args, **options): print("Hello its work") Can someone tell me how to get the data from the spider correctly here, I will be very grateful -
How can I launch Dash Pivottable inside Django?
I have made a Django project in which I have a many pages build in Django dash. Recently i have some requirement in which i have to use Dash Pivottable, but it's not working inside Django. Whereas, when I run it seprately (outside django project), then it is working fine. can anyone help me with this? This is the Dash graph code I used (simpleexample.py): from dash import dcc import dash_html_components as html from dash.dependencies import Input, Output, State from django_plotly_dash import DjangoDash import pandas as pd import requests import dash from dash import callback_context from dash import Dash #from dash.dash_table.Format import Group import os import os.path from datetime import datetime import dash import dash_pivottable from datetime import date app = DjangoDash('stock', external_stylesheets=external_stylesheets) app.layout = html.Div( dash_pivottable.PivotTable( data=[ ['Animal', 'Count', 'Location'], ['Zebra', 5, 'SF Zoo'], ['Tiger', 3, 'SF Zoo'], ['Zebra', 2, 'LA Zoo'], ['Tiger', 4, 'LA Zoo'], ], cols=["Animal"], rows=["Location"], vals=["Count"] ) ) if __name__ == '__main__': app.run_server(debug=True) I have also linked it with URL in urls.py: This is views.py This is my html template (stock.html): {% extends 'base.html' %} {% block body %} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> {% load plotly_dash %} <div class="{% plotly_class name='stock' %}" style="height: 100%; width: 100%"> {% … -
Django admin fails to use unsigned URL for some static files in an AWS bucket
I am serving static files from an AWS bucket for my Django 4.0 powered site. My own apps function perfectly, but the Admin app tries to use unsigned URLs for some of the static files. More specifically, fonts.css and widgets.css under /admin/css/ are requested with unsigned URLs (resulting in 403 Forbidden) whereas all other CSS files are requested with presigned URLs and served just fine. As to images, only icon-addlink.svg is requested with unsigned URL (403 Forbidden) and all other images under /admin/img/are requested and served as expected. The image below (from the browsers Inspect feature) shows how Django tries to fetch some of the files with no querystring at all. What could be causing this? And how to get around it? I have checked that the problematic CSS and image files are properly copied to the static files folder with collectstatic command and they do exist in the AWS bucket. This issue has persisted upgrading to Django 4.0 from 3.X. -
Vs Code browser not working while using Django
I am trying to test the frontend of a Django project and want to use the VS code simple browser to open the local hosted site. In doing so it gives me no output(while it works perfectly on chrome) and the terminal show me this output enter image description here "GET /1?vscodeBrowserReqId=1676305382720 HTTP/1.1" 200 176 I haven't found anything related to this issue on the net and was wondering if it a Django problem or VS code -
Remove loading from postman during celery task
I have implemented celery on a django project and used redis as broker and django_celery_results as backend. Everything is working fine but I want to remove loading from postman. I want to print a message like task processing and when it is done, it shows result on reloading or sending the request again. Code celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) … -
How to replace classic ImageUploadForm with dropzone.js?
I am totally new to Django, but currently I want to deploy my model. I am working on a Django project where users should be able to upload one image using Dropzone.js. Althoung I don't want to save these files anywhere, just have it for further processing with ML. I want to replace current ImageUploadForm to have dropzone for one image on website, Current views.py: import base64 import io import json import os from PIL import Image from django.shortcuts import render from .forms import ImageUploadForm import matplotlib.pyplot as plt from io import StringIO def index(request): image_uri = None graph = None quantity = 0 if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') #some image processing else: form = ImageUploadForm() context = { 'form': form, 'image_uri': image_uri, 'quantity': quantity, 'graph': graph } return render(request, 'image_classification/index.html', context) Current index.html: <!DOCTYPE html> <html lang="en"> <style> body { width: 100% !important; margin: 0 auto; background-color:DarkGray !important; text-align: center !important; } </style> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> </head> <body> <br>Uploaded images are not saved.</p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> … -
How to merge multiple csv files?
I have several csv files that has same first row element in it. For example: csv-1.csv: Value,0 Currency,0 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 csv-2.csv: Value,0 Currency,1 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 And with these files (more than 2 files by the way) I want to merge them and create something like that: left csv-1 csv-2 Value 0 0 Currency 0 1 datetime 0 0 How can I create this funtion in python? -
Running a Pytorch model inside Django
I am trying to run a model (that i have saved already) inside my django project and i dont know how this is to be done . I simply searched web for this problem and came across this https://stefanbschneider.github.io/blog/pytorch-django Here, this guy imports a densenet and json but in my case i already have a running model and there are only 2 classes that is ant and bees Can anybody help me with this? what i did try is i cloned the project and replaced with the preloaded model with my model and skipped the json and added my classes but nothing seems to work -
Celery didn't run from pycharm's terminal
I am trying to run celery in pycharm's terminal by using command "celery --app SF_news worker -l INFO". Instead of normal startup i got " "celery" is not an internal or external command, executable program, or batch file." I tried execute that comand through windows cmd and get and it run properly but i really need to run it from pycharm's terminal because I need to send fully workable pycharm project to my teacher. init.py from project folder (near settings.py) celery.py from project folder (also near settings.py) -
customize models in Django RestFramework using AbstractBaseUser, BaseUserManager
i wanna customize models. so i used AbstractBaseUser, BaseUserManager i use **extra_field to add 'point' attribute. i enterd http://127.0.0.1:8000/account/signup/ and write my data but the errors occured enter image description here what's wrong with my code? i'm a beginner, plz help me # serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = User.objects.create_user( email = validated_data['email'], nickname = validated_data['nickname'], name = validated_data['name'], password = validated_data['password'], point = validated_data['point'] ) return user class Meta: model = User fields = ['name', 'nickname', 'email', 'password'] # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, nickname, name, password=None, **point): if not email: raise ValueError('must have user email') if not nickname: raise ValueError('must have user nickname') if not name: raise ValueError('must have user name') user = self.model( email = self.normalize_email(email), nickname = nickname, name = name, point = point ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, nickname, name, password=None): user = self.create_user( email, password = password, nickname = nickname, name = name ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): id = models.AutoField(primary_key=True) email = models.EmailField(default='', max_length=100, null=False, blank=False, unique=True) nickname = models.CharField(default='', max_length=100, null=False, blank=False, unique=False) name = … -
connect emulator with backend django
So I have a backend with django and I am using react native for frontend. I added a emulator in android studio. And when I start the backend like: python manage.py runserver I can run also the frontend with expo start. But now I want to fetch the data with react native. So I start the backend with: python manage.py runserver 192.168.1.68:19000 - settings file of django: ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:8081", "http://localhost:19006", "http://localhost:19002", "http://192.168.1.69:8000", "http://192.168.1.68:19000", ] CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] And react native service: export const fetchCategoryData = async () => { try { const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Network response was not ok"); } return await response.json(); //setCategoryData(data); } catch (error) { console.error("There was a problem with the fetch operation:", error); throw error; } }; And when I then start the react native app with expo start and I do a r after a. I get this message: warn No apps connected. Sending "reload" to all … -
How to fix VercelEerror python setup.py egg_info did not run successfully
I'm trying to deploy a Django web app on Vercel, but the deployment fails with the following message: Error: enter code hereCommand failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info writing /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Can someone help me? Thank you. -
How to get a parameter from a form and insert it in the url with django?
I am a beginner with django. I want to get a parameter that the user has to enter from a form. This parameter must be visible in the url except that the django server returns an error because the parameter is empty. Here is what I did: This is my template: <form method="POST" action="{% url 'direct_aeg' id_aeg %}" enctype="multipart/form-data"> {% csrf_token %} {{form}} <div class="input-field button"><input type="submit" name="submit_btn" value="Recherche AEG"></div> </form> this is my forms.py: from django import forms class Form_direct_aeg(forms.Form): id_aeg = forms.IntegerField(label="N° AEG",required=True) this is my views.py def direct_aeg(request,id_aeg): # doing some_stuff def show_aeg_tool(request): if request.method == 'POST': form = Form_direct_aeg(request.POST) if form.is_valid(): id_aeg = form.cleaned_data['id_aeg'] url = str(id_aeg) # return redirect(url) else: form = Form_direct_aeg() . . . . this is my urls.py path('a/b/c/d/direct_aeg/<int:id_aeg>', aeg.direct_aeg, name='direct_aeg'), as soon as I load the page I get the following error: Reverse for 'direct_aeg' with arguments '('',)' not found. 1 pattern(s) tried: ['a/b/c/d/direct_aeg/(?P<id_aeg>[0-9]+)\\Z'] I have this error because the id_aeg parameter must be initialized. How to solve this problem? -
Custom Select2 form not posting selected value on Submit
This is a really complex customization of a django form using an external endpoint to generate the autocomplete so dont blame me for the horrible code... But I would love to know why the request.body dont have the selected value on POST... <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="SySOrQ0mzaXY8yGOHcO8OCktWOFBLSCvYPNQI8sic8gJ8lndaPBh1SBu1qRAaAK6"> <input type="hidden" name="pk" value="4"> <!-- We present Dynamic Question --> <input type="hidden" name="endpoint" value="https://media.seenka.com/api/programs/brand-autocomplete/?q=" id="id_endpoint"> <select name="value" id="id_value" data-autocomplete-light-language="en" data-autocomplete-light-url="/front/generic_autocomplete/" data-autocomplete-light-function="select2" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true" data-select2-id="id_value"> <option value="32377" data-select2-id="14">Evagina</option> </select> <span class="select2 select2-container select2-container--default select2-container--below select2-container--focus" dir="ltr" data-select2-id="2" style="width: 22px;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-id_value-container"> <span class="select2-selection__rendered" id="select2-id_value-container" role="textbox" aria-readonly="true" title="Evagina"> <span class="select2-selection__clear" title="Remove all items" data-select2-id="16">×</span> Evagina </span> <span class="select2-selection__arrow" role="presentation"> <b role="presentation"></b> </span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span> <div style="display:none" class="dal-forward-conf" id="dal-forward-conf-for_id_value"> <script type="text/dal-forward-conf">[{"type": "field", "src": "endpoint"}]</script> </div> <input type="submit" value="Submit"> </form> can you find what is wrong with this html form already selected that when I press the submit button the response.body is: {'pk': '4', 'data': {'username': 'mmandrille', 'values': []}}? -
How to display searched item for users, but all items only for admins?
There is a page where the list of elements is displayed. Also, there is a search to display elements that have the requested value. I have an account and access control, some elements of the site are visible to everyone, and some only through the account. The problem is that I need to remove the display of the entire list of elements for the guest, but leave the display of the element based on the search results. Now I have restricted access to the entire list of items, and the user does not see the items in the search results. How to fix it? Home.html {% extends 'base.html' %} {% block content %} <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> {% if user.is_authenticated %} <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> {% endif %} {% endblock %} Urls.py from django.urls import path #from . import views from .views import HomeView, Search urlpatterns = [ path('', HomeView.as_view(), name="home"), path('search/', Search.as_view(), name="search"), Views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' … -
How to have only redoc url in drf-spectacular
I'm using drf-spectacular for my django project: https://github.com/tfranzel/drf-spectacular On urls.py I have this: urlpatterns = [ # YOUR PATTERNS path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), ] I just want to have 'api/schema/redoc/' so I removed the other two URLs. After removing 'api/schema/' I get the following error: Reverse for 'schema' not found. 'schema' is not a valid view function or pattern name. How can I remove that URL but resolve the error -
Docker + Django + Postgres doesn't work. ERROR: Is the server running on that host and accepting TCP/IP connections? [duplicate]
I'm trying to run docker container with django + postgres. When i run two containers (db + web) i see that it's ok on the db side: LOG: starting PostgreSQL 12.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 8.3.0) 8.3.0, 64-bit LOG: listening on IPv4 address "0.0.0.0", port 5432 LOG: listening on IPv6 address "::", port 5432 LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" LOG: database system was shut down at 2023-02-13 14:36:17 UTC LOG: database system is ready to accept connections But on the django side i see the error: django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? DockerFile: FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml: version: '3.9' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=my_admin - POSTGRES_PASSWORD=my_api - POSTGRES_DB=my_db volumes: postgres_data: Also, i have this setting in Django: ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '0.0.0.0', '::1'] … -
Django allauth Configuration
I have implemented Django allauth as a method of authenticating users. I am using Django allauth in an attempt to try and handle multi user authentication system. Now when I omit "username" field in my forms.py file, Django complains of the integrity error as below. IntegrityError at /accounts/accounts/student UNIQUE constraint failed: accounts_user.username Request Method: POST Request URL: http://127.0.0.1:8000/accounts/accounts/student Django Version: 4.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.username Exception Location: /home/offensive/Desktop/Target/.venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: accounts.views.StudentSignUpView Python Executable: /home/offensive/Desktop/Target/.venv/bin/python Python Version: 3.8.10 Python Path: ['/home/offensive/Desktop/Target', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/offensive/Desktop/Target/.venv/lib/python3.8/site-packages'] Server time: Mon, 13 Feb 2023 14:14:23 +0000 below is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.contrib.auth import get_user_model from django.db import transaction from .models import Student, User, Writter class StudentSignUpForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = get_user_model() fields = ( "email", # "username", ) @transaction.atomic def save(self): user = super().save(commit=False) user.email = self.cleaned_data.get('email') user.is_student = True user.save() student = Student.objects.create(user=user) return user class WritterSignUpForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) phone = forms.CharField(required=True) address = forms.CharField(required=True) class Meta: model = get_user_model() fields = ( "email", # "username", "phone", "address", ) By default, I think Django allauth … -
How to set ManToManyField to None?
I have a Section model for storing different sections of laws. A law has Part, Book, Chapter, Title, Section, SubSection, ... and Article Instead of making models for each of the above parts, I created a section model to store the sections in the database. The level field in the section model specifies the depth of levels. as you can see in the picture. class Section(Timestamped): parent = models.ManyToManyField( to='self', verbose_name=_("Parent Section"), help_text=_("Specifies the links to another section."), blank=True, symmetrical=False ) level = models.PositiveIntegerField( verbose_name=_("Level of the section"), ) ... My problem is that when I store the first section or level, the parent should be set to null(which means that the first section has no parent). But I get an error when I set the parent to None. I have all the sections in a JSON file: The script for section in sections: section_data = { "text_id": section.get("id"), "level": 1, } section_db, created = Section.objects.get_or_create(**section_data) section_db.parent.add(None) The error django.db.utils.IntegrityError: null value in column "to_section_id" of relation "laws_section_parent" violates not-null constraint DETAIL: Failing row contains (3, 22, null). Is there any solution? Are the models correctly designed? -
Jinja html code gets incorrectly formatted when saved in VS code
I am writting a Django project using VS Code. I find a strange Jinja formatting issue. What I want is {% extends "../base.html" %} {% load static %} {% block title %} {% if category %} {{ category.name }} {% else %} Products {% endif %} {% endblock %} {% block content %} {% endblock content %} But when I save the file or ctrl+s, it gets formatted like {% extends "../base.html" %} {% load static %} {% block title %} {% if category %} {{ category.name }} {% else %} Products {% endif %} {% endblock %} {% block content %} {% endblock content %} and the render gets error due to broken brackets. I am using Jinja2 Snippet Kit and Prettier plugins. Do I need to make some changes in setting? Could someone give me a help? Thank you. -
Django blog post views count adds two instead of one
I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly Models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() from ckeditor_uploader.fields import RichTextUploadingField class Subscribe(models.Model): email = models.EmailField() class Comments(models.Model): name = models.CharField('Name', max_length=120) post_id = models.IntegerField(null=True) email = models.EmailField() website = models.URLField(max_length=200) comment = models.TextField(blank=True) date_created = models.DateTimeField(blank=True,null=True) def publish(self): self.date_created=timezone.localtime(timezone.now()) self.save() class Category(models.Model): name = models.CharField('Name', max_length=120) slug = models.SlugField(default="", null=False) def __str__(self): return self.name class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = RichTextUploadingField() image = models.ImageField(upload_to='images/', null=True) slug = models.SlugField(default="", null=False) views = models.IntegerField(default=0) def __str__(self): return self.user.username def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField('Post Title', max_length=120) date = models.DateTimeField() status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,) author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,) details = RichTextUploadingField() slug = models.SlugField(default="", null=False) image = models.ImageField(upload_to='images/', null=True) post_views = models.IntegerField(default=0) … -
Django UniqueConstraint not working as expected
At the moment I am using the following condition to avoid duplicates MyModel.objects.filter(other_model=self, ended__isnull=True, started__isnull=False).exists() which works, however due to unfortunate caching etc. in the past there were duplicate instances of this. I want to move this exact check to the database level with Django. I tried different constraints using a simple unique_together ([['other_model', 'ended']]) constraint and constraints = [ models.UniqueConstraint(fields=['other_model', 'ended'], name='unique_name', condition=models.Q(ended__isnull=True)) ] This is my testcase, which runs without a problem (which it shouldn't) ts = timezone.now() MyModel.objects.create(other_model=same_instance, ended=ts, started=ts) MyModel.objects.create(other_model=same_instance, ended=ts, started=ts) This is the latest migration (I even reset the entire DB and reapplied all migrations): migrations.AlterUniqueTogether( name='mymodel', unique_together={('other_model', 'ended')}, ), -
How to send data to particular users in Web Sockets?
I am implementing web sockets in my Django Project with channels library. When an object is created, name of that object should be sent to a consumer with group name test_consumer_group_1. class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is the code of my consumer: class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") data = json.loads(event["value"]) print(data) obj_name = data["current_team"] response = { "obj_name": obj_name } self.send(text_data=json.dumps(response)) How to send data to a particular employee only inside send_notification function? e.g. If a super admin has created an object of MyClass, data should be sent to only those members who are added in members attribute? -
How can I keep track of user selections on each page of a questionnaire using django-formtools till final submission?
I am new to Django and looking to write a small questionnaire containing about 300 or more questions. I just learnt of django-formtools it it seems like what I needed. I have searched without success as to how to start. Assuming each page contains 10-20 questions, how can I keep track result of each page and then display the final result on the final page (the done method) I believe? As I am new to this, the more specific the better. I have search all over and there's nothing related to my objective.