Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unable to revert migration that creates objects when a new field is added
I'm creating a table that should contain a fixed set of data, so not really user data. My initial migration creates the table with all the columns and I added RunPython code to populate the fixed data, something along these lines: from django.db import migrations, models import my_app.model.a_model def create_initial_data(apps, schema_editor): AModel = apps.get_model('my_app', 'AModel') AModel.objects.create( field_2='a value', ) AModel.objects.create( field_2='another value', ) class Migration(migrations.Migration): dependencies = [ ('my_app', '0008_a_migration'), ] operations = [ migrations.CreateModel( name='AModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('field_2', models.CharField(max_length=64, unique=True)), ], options={ 'db_table': 'a_model', }, ), migrations.RunPython(create_initial_data, reverse_code=migrations.RunPython.noop), ] However, if I add a field to the model AModel in a subsequent migration, say 0018_a_migration, I become unable to revert the migration 0008_a_migration with the python code that contains the new column (i.e. I have to comment out the new code to revert the old migration). A solution would be to not use ORM and just write SQL directly inside create_initial_data, I am aware. Is there another way of solving this issue, without writing raw SQL? -
How to calculate monthly fees , pending fees and payable amount in django?
Please help me. I'm planning to create a Student Mangement RestAPI in Django. Kindly suggest me how to create and how to solve this? Models.py :- class Batch(models.Model): batch_name=models.CharField(max_length=255) batch_date=models.DateTimeField(auto_now_add=True) batch_fees=models.DecimalField(max_digits=10, decimal_places=2) def __str__ (self): return self.batch_name class Teacher(models.Model): tech_name=models.CharField(max_length=255) tech_created_date=models.DateTimeField(auto_now_add=True) tech_join_date=models.DateField(blank=False) def __str__ (self): return self.tech_name class Student(models.Model): std_name=models.CharField(max_length=255) std_father_Name=models.CharField(max_length=255, blank=True) std_mother_Name=models.CharField(max_length=255, blank=True) std_date_of_birth=models.DateField(blank=False) std_join_date=models.DateField(blank=False) std_created_date=models.DateTimeField(auto_now_add=True) std_image=models.ImageField(upload_to='./static/prj_static_files/images', blank=True) std_batch=models.ForeignKey(Batch, on_delete=models.CASCADE) std_teacher=models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) std_fees =models.DecimalField(max_digits=10, decimal_places=2) std_pending_fees =models.DecimalField(max_digits=10, decimal_places=2) i need to create monthly fees , pending fees and payable amount how to add batch_fees in to Calculate and put in to std_fees,std_pending_fees -
Django Rest Framework: Add hyperlink related field on sub model
Im trying to find out how I can add hyperlink related field from a relationship model. Lets say i have the following models: class Model1(models.Model): id = models.AutoField(primary_key=True) model2 = models.OneToOneField(Model2, db_column='model2_id', related_name='model2_set', on_delete=CASCADE) class Model2(models.Model): id = models.AutoField(primary_key=True) model3 = models.ForeignKey(Model3, db_column='model3_id', related_name='+', null=True, blank=True, on_delete=FOREIGNKEY_PROTECT) class Model3(models.Model): id = models.AutoField(primary_key=True) description = models.TextField(db_column='description', null=True, blank=True, verbose_name=_('Description')) and I have a serializer for both Model1 and Model3 but not Model2 I want to have the following output { "id":123, "model3":"http://example:123/api/model3/123" } but in my model1 serializer i cant simply call a hyperlinkrelated field for a sub model because it cannot identify the source class Model1ListSerializer(ValidateByModelSerializer): id = serializers.IntegerField(read_only=True) model3 = serializers.HyperlinkedRelatedField( source='model2__model3', queryset=Model3.objects.all(), view_name='model3_rest-detail' ) Whats the best way to achieve this? -
django installation not working in virtual environment
I created a virtual environment and installed django in it using pip. In a python shell in the v.e. I can import django and print its version, but when trying to start a project or do a django-admin --version I get the following error: bash: /usr/bin/django-admin: No such file or directory Here are the steps I took before: sudo apt-get install python3-venv python3 -m venv my_env source my_env/bin/activate sudo apt install python3-pip -y pip --version sudo apt install python3-django django-admin --version --> ModuleNotFoundError: No module named 'django' sudo apt remove python3-django pip install django --> Successfully installed asgiref-3.3.1 django-3.1.7 pytz-2021.1 sqlparse-0.4.1 django-admin --version --> bash: /usr/bin/django-admin: No such file or directory -
react's styling overriden in django template
I am trying to build a django / react hybrid app as per the guide here: https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ and using react components from the @elastic/search-ui, specifically trying to replicate the following example in one of my django templates: https://codesandbox.io/s/getting-started-y9tnd So one of the django templates has the react search ui embedded and running from js bundle built using webpack. The problem is that it seems the search-ui's nice styling is overriden by the bootstrap styling I use for all django templates. Django template part: es_list_react.html {% extends "base_generic.html" %} {% block content %} Test React component <hr> {% load static %} <div id ='root'></div> <script src="{% static 'ui-react-build/index-bundle.js' %}"> </script> {% endblock %} base_generic.html <!DOCTYPE html> <html lang="en"> <head> ... {% load static %} <!-- Bootstrap core CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> ... </head> <body> ... </body> </html> React (search-ui) part: index.js import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(<App />, document.getElementById("root")); App.js ... import "@elastic/react-search-ui-views/lib/styles/styles.css"; ... What could be a root cause and a solution to the problem? The styling seems to be actually making it to the js bundle created by webpack: index-bundle.js ... ***/ "./node_modules/@elastic/react-search-ui-views/lib/styles/styles.css": /*!***************************************************************************!*\ !*** ./node_modules/@elastic/react-search-ui-views/lib/styles/styles.css ***! \***************************************************************************/ … -
Django admin annotation is multiplied if search_field (by related FK),
i have problem with multiplation of annotation... if i use search_field by email useremail__email (related fk of user model) ... then my annotation is multipled the problem is if the table with profileemails is joined (without search it works just good) in example: i have user named admin and emails.. admin1, admin2, admin3 then search is done by admin the result is sum * 3 (because 3 emails) my model: class Payment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.IntegerField() class SubPayment(models.Model): payment = models.ForeignKey(Payment, on_delete=models.CASCADE) amount = models.IntegerField() class UserEmail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.CharField(max_length=128) in admin i have User model where i want to display sum and count of subpayments: class UserAdmin(admin.ModelAdmin): list_display = ("username", "payment_count", "payment_sum") search_fields = ( 'useremail__email', 'username' ) def payment_count(self, obj): return obj.payment_count def payment_sum(self, obj): return obj.payment_sum def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs).annotate( payment_amount=Sum('payment__amount'), payment_count=Count('payment__subpayment'), payment_sum=Sum('payment__subpayment__amount'), ) return queryset I tried use distinct=True , but it remove duplicite subpayments with same amount... tried on django 2.2 and 3.17 works good: works wrong: Any help? Thanks! -
wfastcgi-enable show massage like this "Ensure your user has sufficient privileges and try again."
I finished my Django website and I want to deploy it in window server 2008. I follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ&t=306s but stuck at wfastcgi-enable It show message like this -
NOT NULL constraint failed: MyServer_links.redirect_url
It says problem with line 82 - store_links.save() views.py from django.http import HttpResponse from django.http import JsonResponse from django.http import HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from MyServer.models import * import string import random import re from datetime import datetime import json import os # TRACKING_DOMAIN_NAME = "http://127.0.0.1:8000/tracking" # DOMAIN_NAME = "http://127.0.0.1:8000" TRACKING_DOMAIN_NAME = '127.0.0.1:8000' DOMAIN_NAME = '127.0.0.1:8000' # Create your views here. def formaturl(url): if not re.match('(?:http|ftp|https)://', url): return 'http://{}'.format(url) return url def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def get_client_data(request): browser = request.user_agent.browser.family + " "+ request.user_agent.browser.version_string os = request.user_agent.os.family + " "+ request.user_agent.os.version_string device = request.user_agent.device.family device_type="" if(request.user_agent.is_mobile): device_type="Mobile" if(request.user_agent.is_tablet): device_type="Tablet" if(request.user_agent.is_pc): device_type="PC/Laptop" if(request.user_agent.is_bot): device="bot" resp = {"browser":browser,"os":os,"device_type":device_type,"device":device} print(resp) return resp @csrf_exempt def create_shortened_url(request): original_url = request.GET.get('127.0.0.1:8000') random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 6)) random_chars2 = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 5)) #append to domain name shortened_link = DOMAIN_NAME + "/" + random_chars tracking_link = TRACKING_DOMAIN_NAME + "/" + random_chars2 #What if randomly generated chars already exist? #Check the url in db before comitting - FUTUTRE WORK #Store in the DB store_links = Links(short_url=shortened_link,redirect_url=original_url,tracking_url=tracking_link) store_links.save() print("LINK SHORTENED : ",shortened_link) # return JsonResponse({'shortened_link':shortened_link,'tracking_link':tracking_link}) return render(request,'index.html',context={'shortened_link':shortened_link,'tracking_link':tracking_link}) def redirect_test(request): return redirect("https://facebook.com") … -
Permission denied, cannot open static files, Docker, Django
I am new in docker, I want dockerize my django application to production. I use the below steps My OS: Ubuntu 20.04.1 LTS Docker version 20.10.5, build 55c4c88 My docker-compose.yml file as below: version: '3.1' services: nginx-proxy: image: jwilder/nginx-proxy restart: "always" ports: - "80:80" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./nginx/vhost/:/etc/nginx/vhost.d:ro - ./nginx/conf.d/client_max_body_size.conf:/etc/nginx/conf.d/client_max_body_size.conf:ro - ./static/:/amd/static - ./media/:/amd/media postgres: image: postgres:9.6.6 restart: always volumes: - ./pgdb/:/var/lib/postgresql/ ports: - "5432:5432" env_file: ./.env redis: image: redis ports: - 6379:6379 restart: always web: container_name: amd build: . restart: "always" ports: - "8000:8000" volumes: - .:/code/ # - ./static/:/code/static # - ./media/:/code/media depends_on: - "postgres" env_file: .env celery: build: context: . dockerfile: celery.dockerfile volumes: - .:/code command: celery -A amdtelecom worker -l info links: - redis - postgres depends_on: - "redis" - "postgres" env_file: ./.env networks: default: external: name: nginx-proxy My Dockerfile as below: FROM python:3.7 ENV PYTHONUNBUFFERED 1 ENV DEBUG False COPY requirements.txt /code/requirements.txt WORKDIR /code RUN pip install -r requirements.txt ADD . . CMD [ "gunicorn", "--bind", "0.0.0.0", "-p", "8000", "amdtelecom.wsgi" ] in my project setting file: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", "http://localhost" ] STATIC_URL = '/static/' if PROD: STATIC_ROOT = os.path.join(BASE_DIR, 'static') else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] … -
How to extract data from the Database based on the input fields given in the HTML form using Django
I am using Django REST Framework for creating REST APIs. I am working with MySql Database where I have questionsModel table. In that table I am storing package(JEE, IEEE), Subjects(Phy, Chem, Math), Topics, SubTopics, Questions etc which are already mapped with another tables like packageModel, subjectsModel etc. This is my model : models.py : class questionsModel(models.Model): package_id = models.ForeignKey(packageModel, max_length=20, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(subjectsModel, max_length=20, null=True, on_delete=models.CASCADE) topic_id = models.ForeignKey(topicsModel, max_length=200, null=True, on_delete=models.CASCADE) subTopic_id = models.ForeignKey(subTopicsModel, max_length=20, null=True, on_delete=models.CASCADE) Question = models.CharField(max_length=1000, blank=False, null=True) choice = (('c1','c1'), ('c2','c2'), ('c3','c3'), ('c4','c4')) answer = MultiSelectField(choices=choice) numericAnswer = models.CharField(max_length=1000, blank=False, null=True) marks = models.PositiveIntegerField(default=0) easy = models.PositiveIntegerField() average = models.PositiveIntegerField() tough = models.PositiveIntegerField() very_tough = models.PositiveIntegerField() def __str__(self): return self.Question Here, I am storing n number of Questions in this table. Now my requirement is to fetch lets say 50 random Questions depending on the input given in the HTML form. I am putting my code here with the HTML form : This is the Screenshot of HTML Form where I am giving the values. On the basis of the input fields, I want to fetch record from my questionsModel Table serializers.py : class questionPaperSerializer(serializers.ModelSerializer): class Meta: model = questionPaperModel fields = … -
Errno 5 Input/output error on request.GET
Once my Django site has been deployed into "production" and set live using Gunicorn and nginx some URLs that did work before now result in a [Errno 5] Input/output error. I already disabled the DEBUG flat in settings.py by setting DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' What would be the best approach to troubleshooting this? Is there any obvious part of the deployment that I overlooked? My nginx conf.d file looks as follows: server { listen 80 default_server; server_name rafalkukawski.tech; root /var/www/; location / { proxy_pass http://localhost:8000; } location /img/ { } location /static/ { autoindex on; } } The views affected by this are: # called like: http://rafalkukawski.tech/todo/new?todo_name=new&due_date=2021-03-25&importance=0&required_time=1 def new_item(request): todo_name = request.GET.get('todo_name', '') #todo_auth = request.GET.get('todo_auth', '') due_date = request.GET.get('due_date', '') importance = request.GET.get('importance', '0') required_time = request.GET.get('required_time', '1') #this in particular is highlightet as the faulty line of code item = todo_item(todo_name = todo_name, todo_auth = request.user.username, due_date = due_date, importance = importance, required_time = required_time) item.save() return HttpResponse(item.due_date) or #called like: http://rafalkukawski.tech/ap/painting/1 #not sure what line exactly is causing this since the error only displays "<source code not available>" def template_painting(request, painting_id): painting = Painting.objects.get(pk=painting_id) images = Imgs.objects.filter(painting=painting_id) lang_code = request.LANGUAGE_CODE template =loader.select_template(['ap/'+lang_code+'/painting.html','ap/en/painting.html']) #template = loader.get_template('ap/'+lang_code+'/painting.html') … -
how to insert paragraph after codeblock with <pre> in summernote
i want to insert tag after i use codeblock with ext-highlight below is my code <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- default css --> <link href="{% static 'css/reset.css' %}" rel="stylesheet"> <link href="{% static 'css/layout.css' %}" rel="stylesheet"> <!-- use Prism --> <link href="{% static 'css/prism.css' %}" rel="stylesheet"> <!-- bootstrap cdn --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- fontawsome --> <link href="{% static 'fontawesome/css/all.css' %}" rel="stylesheet" type="text/css"> <!-- summernote --> <link href="{% static 'summernote-0.8.18-dist/summernote-bs4.css' %}" rel="stylesheet"> <script src="{% static 'summernote-0.8.18-dist/summernote-bs4.min.js' %}"></script> </head> <body> <textarea id="id_content></textarea> <script> $(document).ready(function() { $('#id_content').summernote({ toolbar: [ ['style', ['style', 'add-text-tags']], ['font', ['bold', 'underline', 'clear']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['highlight', 'link', 'picture', 'video']], ], width: '100%', height: '380px', lang: 'ko-KR', prettifyHtml: false, placeholder: '질문을 입력하세요.', dialogsInBody: true, tabDisable: true, }); }); </script> <script src="{% static 'js/summernote-ext-highlight.js' %}"></script> </body> now insert codeblock <p></p> + <pre></pre> but i want <p></p> + <pre></pre> + <p></p> now my page like this but i want like this How can I make the features I want? I don't know if I asked the question correctly because I couldn't speak English well. Please understand this. -
Connecting 2 unconnected tables but are connected to the same table via many-to-many relations
I have the following setting in a django project A model describing "Person", this model includes 2 many-to-many relation fields a. The first unit field connects to a Unit model (m2m) b. The second tool field connects to a Tools model (m2m) Unit and Tools are not directly connected, but I want to list all the tools used in a given unit. I'm not sure how this can be done, since the two tables are not connected? class Person(models.Model): name = models.CharField(max_length=100) unit = models.ManyToManyField(Unit, blank=True) rtools = models.ManyToManyField(Rtool, blank=True) class Tool(models.Model): tool_name = models.CharField(max_length=100) tool_description = models.TextField( blank= True) class Unit(models.Model): unit_name = models.CharField(max_length=250) -
Django TypeError expecting str or binary, how to satisfy?
here is the traceback Building a simple Django blog application, had it working on virtual dev server at first but after integrating summernote editor into admin side, front end site wont launch and this TypeErorr is displayed. Has anyone encountered this before and is able to point me in the right direction? Django version 3.1.7. -
django objects.filter() issues
My django project contains an application called: app_1 It stores models.py file wich contains a django models called: client I cannot filter my models throw client.objects.filter(nom=something), django search into a wrong relation it just add my app name with my model's name and search into "app_1_client" (it should be in "client") ERREUR: the relation « app_1_client » doesn't exist I can access my data with client.objects.raw(""" query """) from django.db import models # Create your models here. class client(models.Model): nom = models.CharField(max_length = 100, null=False) prenom = models.CharField(max_length=100, null=False) tel = models.CharField(max_length=12, primary_key=True) views.py from .models import client def modify_client(request, client_phone): c = client.objects.filter(pk=client_phone) context = {'clients': c} -
different number of records in django pagination pages
I make a news blog. I want 5 news to be displayed on the first page. In the order below. And on the next ones, 6 were displayed (all squares with areas are the same). .news-container { margin: 0; display: grid; grid-template-columns: 50fr repeat(2, 25fr); grid-auto-rows: 40vh; grid-column-gap: 20px; grid-row-gap: 20px; } .news-element:nth-child(1) { background:red; grid-column: 1 / 2; grid-row: 1 / 3; } .news-element:nth-child(2) { background:red; grid-column: 2 / 3; grid-row: 1 / 2; } .news-element:nth-child(3) { background:red; grid-column: 3 / 4; grid-row: 1 / 2; } .news-element:nth-child(4) { background:red; grid-column: 2 / 3; grid-row: 2 / 3; } .news-element:nth-child(5) { background:red; grid-column: 3 / 4; grid-row: 2 / 3; } <div class="news-container"> <div class="news-element"> 1 </div> <div class="news-element"> 2 </div> <div class="news-element"> 3 </div> <div class="news-element"> 4 </div> <div class="news-element"> 5 </div> </div> How can you make sure that 5 news are displayed on the first page in pagination and 6 news on the rest? pagination is done on django like this class NewsView(ListView): model = News template_name="mysite/news.html" paginate_by = 5 context_object_name = "all_news" queryset = News.objects.all().order_by("-date_news") -
Deployed Dockerized Django app with GitLab CI/CD can't find static files
Deployed django application using Docker and Gitlab CI can't find static files on the server when I am trying to access admin page, swagger or browsable-api. I checked static files for their existence and they do in the location /srv/data/public/static/ . I tried to change nginx location but it didn't help. Here is mine production docker-compose.yaml version: '3.1' services: postgres: container_name: postgres image: postgres:12.0-alpine logging: driver: none volumes: - ./data/postgres:/var/lib/postgresql/data:rw ports: - 5432:5432 environment: POSTGRES_DB: baysai POSTGRES_USER: user POSTGRES_PASSWORD: pass redis: container_name: redis image: redis:6.0-alpine logging: driver: none volumes: - ./data/redis:/data api: image: registry.gitlab.com/example/example-api:master container_name: api hostname: api command: bash -c "python /app/manage.py collectstatic --noinput && python /app/manage.py migrate --noinput && gunicorn -b 0.0.0.0:8000 config.wsgi:application" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env ports: - "8000:8000" depends_on: - redis - postgres celery: image: registry.gitlab.com/example/example-api:master container_name: celery hostname: celery command: bash -c "cd /app && find . -type f -name 'celerybeat.pid' -exec rm -rf {} \; && find . -type f -name 'celerybeat-schedule' -exec rm -rf {} \; && celery -A config worker -l info" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env depends_on: - redis - postgres nginx: … -
Credential error when trying to preserve data
I am developing an api in Django Rest Framework, which at the moment only registers new users, but I have a problem and that is that now I am adding a bit of security, which is being controlled by means of tokens, but at the time of entering the token of an authenticated user for the creation of users generates an error of The authentication credentials were not provided, but I send the token as follows: This is plugin rest client visual studio code My authentication: ### Login user POST http://localhost:8000/auth-token/ Content-Type: application/json { "username": "hamel", "password": "contraseña" } This return a token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 My register of user: ### Create User POST http://localhost:8000/api/v1/users Authorization: Token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 Content-Type: application/json { "first_name": "Carlos", "last_name": "Carlos", "username": "carlos", "email": "correo@rgrgr.com", "password": "contraseña", "password2": "contraseña" } My setting.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } -
how can i set two for loop in django template for send and receive chats?
im trying to set receive and send message in django template with to for loop like this : <div class="border px-2 chat-box "> {% for box in message1 %} <div class=" my-4 border bg-light "> <span class=" p-2 my-5">{{ box.msg_content }}</span><br> <span class="date text-muted ">{{ box.whenpublished }}</span> </div> {% endfor %} {% for box2 in message2 %} <div class=" border bg-danger" style="" > <span class=" p-2 my-5" >{{ box2.msg_content }}</span><br> <span class="date text-muted">{{ box2.whenpublished }}</span> </div> {% endfor %} </div> but when i send and receive message Each of them comes separately like this: hello(user1) how are you(user1) hello(user2) im fine thnaks(user2) but i want when i send one message its show after receive message hello(user1) hello(user2) how are you(user1) im fine thnaks(user2) -
could not create unique index, key is duplicated django postgres
I got following user table with same uuid . I want this uuid to be unique . but while changing the uuid from my user model with unique=True and editable=False While executing migrate command , I am getting "psycopg2.errors.UniqueViolation: could not create unique index" error with Key (hnid)=(8c0bc4a2-165a-47d5-8084-8b87600c7fe8) is duplicated. Note: I am using postgres How can I solve this issue -
Saving Serializers with Foreign Key (django rest framework)
I have two models which is Task and Batch that are related to each other by Foreign Key field. When creating a Task Object, I want to check first if a Batch Object is available in database (batch is just the current date, so I can group each task using batch). If not, create a Batch object and then pass the newly created batch object to the Task that is being created. views.py @api_view(['POST']) def taskCreate(request): batch = Batch.objects.filter(batch = datetime.date.today()).first() serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save(commit=False) if batch is None : batch = Batch.objects.create(batch = datetime.date.today()) serializer.batch = batch serializer.save() return Response(serializer.data) models.py class Batch(models.Model): batch = models.DateField(auto_now_add=True) class Meta: ordering = ['-batch'] verbose_name = 'Batch' verbose_name_plural = 'Batches' def __str__(self): return self.batch.strftime("%B %d, %Y %A") class Task(models.Model): title = models.CharField( max_length = 256, ) completed = models.BooleanField( default = False, ) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' depth = 1 this is how I handle my form in frontend: var form = document.getElementById("form") form.addEventListener('submit', function(e){ e.preventDefault() var url = "{% url 'api:task-create' %}" if(activeItem != null ){ url = `http://localhost:8000/api/task-update/${activeItem.id}/` activeItem = null } var … -
Python Django __init__() takes 1 positional argument but 2 were given
Hi i started to make django and started with simple Hi app. But when i want to access on /hi/ i give error called "init() takes 1 positional argument but 2 were given" Here is code #urls.py from django.contrib import admin from django.urls import path from hi.views import hiView urlpatterns = [ path('admin/', admin.site.urls), path('hi/', hiView), ] #views.py from django.shortcuts import render from django.http import HttpRequest def hiView(request): return HttpRequest('Hi.') #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hi', ] im adding my directory list https://imgur.com/N3uJG1f -
Empty QuerySet for Django Multi-Table Inheritance Subclass
I have the following models: APP 1: class User(AbstractBaseUser): # custom fields etc # NOT ABSTRACT APP 2: class SecondaryUser(User): # other custom fields When I do SecondaryUser.objects.create(...) I get an instance as expected: In: SecondaryUser.objects.create(first_name='test', last_name='test', email='test@etest.com') Out: <SecondaryUser> This has an id and populated fields as expected. I can also query the base class and use the django-generated 1-1 field for the inheritance to access the subclass's fields: User.objects.get(email='test@etest.com').secondaryuser.<some_field> However when I do SecondaryUser.objects.all() it returns an empty queryset. And the model admin for the SecondaryUser shows an empty list view (even when I create a new instance of SecondaryUser in the admin create view). I feel like I'm missing something obvious, I need to be able to list the SecondaryUser instances in the admin. The User class cannot be abstract. -
django apache :WSGIPythonHome cannot occur within <VirtualHost> section
i have a server with ubuntu-server that run apache2 and where i have my django project. i'm having trouble deploying the app. this is my /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName HIVE.localhost ServerAdmin webmaster@localhost DocumentRoot /home/leo/HIVE/src # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for … -
Django & Celery - Domotic Project with Raspberry
I started a new project with Raspberry Pi that controls a series of sensors and activates relays when certain conditions occur. The script runs well stand alone but I need to integrate it into a django app to control certain cases (e.g. temperatures, humidity, manual switches, etc.) So, I have pip installed celery and redis and configured it. What I need to understand is how to make the while scrip start contextually to the app and not block it when the app starts. The script is very simple def startdomo() stuffs = Stuffs.objects.get(pk=1) while True: do some stuffs I try to put it into url.py at the end urlpatterns = [ url(r'', include('FBIsystem.urls')), ] startdomo() In this case startdomo run but django app not run. The goal is to use Celery to run startdomo async respect to the app. Thanks in advance.