Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any tool which could help me convert a raw sql query to django ORM query?
I am looking for a tool to convert my raw SQL query to Django ORM query Or could someone help me with the conversion? Raw Query: select coalesce(v1.Value1 - v2.Value2, 0) as sent from ( select sum(catch_attempt) as Value1 from test_statsbatch sb where sb.process_id = test_process.id ) as v1 cross join ( select total_skipped as Value2 from processes_processaggregatedstats sca where sca.id = test_process.process_stats_id ) as v2 -
TypeError at /candidate/1/
I used positional parameters and it is showing that Position is not Iterable as Position is Object so anybody please try to help me out of this ASAP.. views.py def candidate_view(request,pos): obj = get_object_or_404(Position,pk=3) if request.method == "POST": print("You are in ") return HttpResponse("Voted") else: return render(request, 'poll/candidate.html', {'obj': obj}) Urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from . import views urlpatterns = [ path('',views.home,name="home"), path('register',views.register,name="register"), path('login',views.view_login,name="view_login"), path('logout',views.view_logout,name="view_logout"), path('candidate/<int:pos>/',views.candidate_view,name="candidate_view"), path('positions',views.position_view,name="position_view"), path('result',views.result,name="result"), ] Position.html {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <h2>Available Position For Vote</h2> <ul> {% for i in obj %} <li><a href="{% url 'candidate_view' i.id%}">{{i.title}}</a></li> {% empty %} <p>No Positions Available</p> {% endfor %} </ul> {% endblock %} Models.py class Position(models.Model): title = models.CharField(max_length=30) def __str__(self): return self.title #This is model of candidate class Candidate(models.Model): full_name = models.CharField(max_length=30) pos = models.ForeignKey(Position, on_delete=models.CASCADE) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.pos.title) -
How a change a dash size?
I have a small size of dash How I can change a dash size or a parent div size? I used a simple usage from example and it worked normal. But I have size problem with new dash [enter image description here][1] dash app import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample') # replaces dash.Dash app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'}, ], 'layout': { 'title': 'Dash Data Visualization' } } )]) if __name__ == '__main__': app.run_server(debug=True) views.py from django.shortcuts import render from django.http import HttpResponse from . import plotly_app def index(request): return render(request, "index.html") some important from settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newtry', 'django_plotly_dash.apps.DjangoPlotlyDashConfig',] -
Is it posible to route requests for specific domains to different URL schemes in Django?
Is it possible to route requests for specific domains to different URL schemes in Django? For example I have domains: example.com ans secret.com. Is it possible to handle different URL schemes for different domain names? -
Comparing Between datetime field in django
I have a model named Assignment in my project This is how the Assignment model looks like class Assignment(models.Model): user = models.ForeignKey( Teacher, on_delete=models.CASCADE, related_name='assignments') unique_code = models.CharField(max_length=11, default=assignment_uniqe_id) title = models.CharField(max_length=250) deadline = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) subject = models.ForeignKey( All_Subject, on_delete=models.CASCADE, related_name='assignment_subject') classes = models.ManyToManyField(Classes) submitted_by = models.ManyToManyField(Student, blank=True) description = models.TextField(blank=True) def __str__(self): return str(self.user) + " : " + self.title And I want to check weather if the current date is greater then the deadline. Please help me out -
Overriding/extending Django Admin Login page with django-suit
I've been working on adding Okta integration to django admin and tried to extend the login page to add a new button (the okta integration itself works fine if a go to /admin/login), but when i do this: {% extends 'admin/login.html' %} {% load i18n %} {% block extrastyle %} {{ block.super }} <style> #content-main { float: none !important; } .okta_login_container { margin-top: 15px; display: flex; justify-content: center; } </style> {% endblock %} {% block content %} {{ block.super }} <div class="okta_login_container"> <a href="some-url">Or Login With Okta</a> </div> {% endblock %} Starting the server fails the following error maximum recursion depth exceeded while getting the repr of an object as it seems to not find the login.html page. overriding other pages like base.html work fine. Other important facts, django-suit is being used and it already overrides the style of the login page. -
Django: Why the User model contains custom fields declared in UserCreationForm
I was going through a django tutorial on registration and I feel like this particular code doesn't make sense. First of all, instead of writing a custom email field, which does nothing different than User email field, shouldn't we just add email to the list of fields? But my main question is about writing password1 and password2 in the fields. Now I know that these are custom fields of UserCreationForm, and are passed to the UserRegistrationForm by inheritance. And indeed, the password and re-enter password fields are visible on the html page, even if I delete those from the fields. What I don't get is why leaving them there doesn't result in an error? The user model only has a password field, which will equate the password1 field of the form through the save method: user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user But the model itself shouldn't have those fields, but yet I'm not getting an error. Any thoughts? -
Vue JS widgets in hybrid application
I have a hybrid Django/VueJS application. I combine Django templating pages with VueJS widgets because that allows to take best of the 2 different worlds. However, I face an issue when I need to place multiple VueJS widgets. When I need to embed only 1 widget, I just use to embed it. But when I have multiple widgets, I don't know what to do. Do I need to mount multiple widget separately? Is this a good practice? Here's how my main.js looks like: import Vue from "vue"; import vuetify from "./plugins/vuetify"; import router from "./router"; import AccountApp from "./AccountApp.vue"; import store from "./store/index.js"; import i18n from "./i18n"; Vue.config.productionTip = false; const accountApp = new Vue({ vuetify, router, store, i18n, render: (h) => h(AccountApp), }); accountApp.$mount("#app"); -
How to fix error in Django serializers.py fields
I'm trying to send a post request from django app using rest framework but I keep having the following output: { "user_name": [ "This field is required." ], "email": [ "This field is required." ], "company": [ "This field is required." ], "state": [ "This field is required." ], "city": [ "This field is required." ], "address": [ "This field is required." ], "phone_number": [ "This field is required." ], "password": [ "This field is required." ], "password_2": [ "This field is required." ] } I have the following blocks of code: urls.py urlpatterns = [ path("register_user/", account_register, name="register") ] models.py from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.db import models from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField from django.core.mail import send_mail class CustomManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, password, **other_fields) def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, … -
How can I use django rest Framework's search filter to search in multiple models
I want to search in multiple models. what can I do to achieve that. like we can do this to search in a single model. class ArtistListView(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer filter_backends = (SearchFilter, OrderingFilter) search_fields = ('artist_name', 'born', 'albums__album_name') but what i want to do is that like if I search for "taylor", I want to get results from artist model, album model and playlist model. with same term. how can I specify multiple and models and their fields to filter in. please help me. -
how to connect postgresql to aws RDS using Django
I am unable to connect my postgreSQL database to AWS RDS while using Django. I am not sure what i am doing wrong but i have the configuration below: Django docker-compose postgres #DJANGO Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "dbtest", 'USER': "mastername", 'PASSWORD': "somepassword", 'HOST': 'dbtest.zmrHnee2mhLunL.us-east-2.rds.amazonaws.com', 'PORT': 5432 } } docker-compose version: "3.7" services: backend: build: ./backend container_name: backend stdin_open: true tty: true restart: "on-failure" env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - db_network db: image: postgres:11.5-alpine container_name: db restart: always environment: - POSTGRES_DB=dbtest - POSTGRES_USER=mastername - POSTGRES_PASSWORD=somepassword volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - db_network networks: db_network: driver: bridge volumes: postgres_data: after starting the container docker-compose up -d --build Now when i check docker-compose logs I see the traceback below: File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect backend | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) backend | django.db.utils.OperationalError: could not translate host name "dbtest.zmrHnee2mhLunL.us-east-2.rds.amazonaws.com" to address: Name or service not known security group I have been trying to debug for hours, any help would be really helpful -
ImportError : Couldn't import Django
I have installed django==3.1.4 and activated Venv on my windows machine and it works fine in myBlog project. But today when I try to run the server, got this error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? but venv is already activated and when I do pip freeze > requirements.txt It shows asgiref==3.3.4, Django==3.1.4, django-crispy-forms==1.11.2, Pillow==8.2.0, pytz==2021.1, sqlparse==0.4.1, I also checked sys.path, It shows ['', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32', 'C:\Users\user\Desktop\myBlog\venv', 'C:\Users\user\Desktop\myBlog\venv\lib\site-packages'] Please Help to fix this -
load an app from another reusable app in django
Let's say we have this file structure as in the Django tutorial website: mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py Where the polls app is not the entry point of the Django project. Instead, it's an app that is intended to be reusable, so that if we copied the polls folder to another Django project, all we will have to do to get it to work is only to add polls.apps.PollsConfig to the INSTALLED_APPS in mysite/settings.py and then do the database migration. My question is, what if, the polls app depends on another app, let's say, django_ace. In this case, the polls app will not work properly unless I add 'django_ace' as well to the INSTALLED_APPS in mysite/settings.py. But it's very inconvenient for a reusable app to require that you manually add its dependencies. So, is there any way I can load the django_ace app from within the polls app itself so that it remains reusable such that including the polls app will implicitly include the django_ace app as well? -
How to update text of the document file in the queryset?
def corrections_fn(request, file, selected_words, corrections): parser = GingerIt() user = request.user document = Document(file.file) text = '' for line in document.paragraphs: matches = parser.parse(line.text) for obj in matches['corrections']: misspelled_word = obj['text'] if misspelled_word in selected_words: correction = selected_words[misspelled_word] line.text = line.text.replace(str(misspelled_word), str(correction)) else: if corrections == 'auto': line.text = line.text.replace(str(obj['text']), str(obj['correct'])) document.save(file.file) return file In the file variable, i'm sending the Queryset which contains file(.docx). resumes = Resume.objects.filter(user=user) for resume in resumes: corrections_fn(request=request, file=resume, selected_words=selected_words, corrections="show") When i try to rewrite the file. It is showing "Unsupported Operation write" error. I searched on internet and i'm not able to find the right document to deal with this type of issue. can any help me on how to solve the issue? Thank you in advance -
Model Fields in Django
I am implementing a Custom User interface by adding two new fields in the built in User model. class CustomUser(AbstractUser): is_employee = models.BooleanField(default=False) is_contractor = models.BooleanField(default=False) I want to create two new profiles based on the values in these two fields. class Employee(models.Model): pass class Contractor(models.Model): pass if is_employee is True then create an employee and if is_contractor is True then create a contractor. In django documentation django signals are used to create this link between models using pre_save and post_save function but how can I access the field value from the user model? -
How do I display Django Rest Framework Foreign Key in Angular?
DISCLAIMER: This is gonna be a pretty long description of a problem, to which I can't seem to find sources for that could help me. So any piece of information is appreciated! I might add that I am fairly new to Angular and text script. I have set up my backend with Django and set up the Rest Framework. These are my models: models.py class Person(models.Model): name = models.CharField(max_length = 250, blank = True) job = models.ForeignKey('Job', on_delete = models.CASCADE, null = True) def __str__(self): return self.name class Job(models.Model): job_name = models.CharField(max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0, unique = True) def __str__(self): return self.job_name In the backend I have set up different job names (Doctor, Teacher, etc...). So when I create a new Person, I get to choose from one of the different jobs, which have been created prior to this. (This is exactly how I woukd want my frontend to work) Here are my serializer.py, views.py and urls.py files: serializer.py class PersonSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('id', 'name', 'job') class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ('id', 'job_name') views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer def list(self, … -
How to get random number every x second from python to template? Django
Ok so this may sound foolish but I know how we can generate random number in javascript every x seconds, but actually I just want to receive a value from my custom template tag which is frequently updating, but when I do so by calling it repeatedly through my javascript it just gives the same value, so I think template tags just calls the function on start and store the value, however I need to get updated value every time I call my tag. My custom_tags.py - @register.simple_tag def getTest(): verification_code = str(randint(100000, 999999)) return verification_code And in my javascript - window.setInterval(function(){ let temp5 = "{% getTest %}" console.log(temp5) }, 5000); This returns me same number everytime, so is there any fix or workaround for this ? PS I dont want to reload every x seconds so it should be done using custom template tags only. Any help is appreciated -
Django | I'd like to delete a product and all of its related data from the database
I have a shopping cart with some items in it. If I delete a product from the basket, I also want to remove it from the orderitem. I am now unable to delete the orderitems and quantity. class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) class OrderItem(models.Model): Quantity_Choices =( ('one', '1'), ('Two', '2'), ('Three', '3'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.CharField(max_length=22, choices=Quantity_Choices, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) The code for adding an item to the cart is as follows. def cart_update(request): product_id = request.POST.get('product_id') print(product_id) if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("No product") return render("cart_home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added= False else: cart_obj.products.add(product_obj) added =True request.session['cart_items'] = cart_obj.products.count() if request.is_ajax(): print("ajax request") json_data = { "added":added, "removed": not added, "cartItemCount":cart_obj.products.count() } return JsonResponse(json_data) return redirect("cart_home") orderitem cart -
Django seems to import packages from global installations rather then from my Virtual Environment(venv)
I have created a Virtual Environment using Python's built-in venv. Activated the environment & installed the necessary packages. But cannot import Pandas in the Django project. Later I figured out that Django might be importing packages from the global packages installed before, where pandas was not installed. Do I have to change anything in my Django project settings or in my Virtual Environment? Activated Virtual Environment(venv) Pandas installed in the venv This is when I echo path while venv activated This is when I try to import Pandas -
Django Content-Disposition - Ordering and Sorting
I have created a Django/python web app that saves meter readings entered, into the database. This app also has a button that exports the readings along with the unit number for the model that it's in. It is working up to standard, however, when the file is exported, it is exported in the order that the readings have been entered in. How would I sort the export from smallest to largest, through the Django code? Views.py: import csv def Avonleacsv(request): data =AvonleaClass.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Avonlea_file.csv"' writer = csv.writer(response) writer.writerow(['Unit', 'Number of Units' ]) for avonleaclass in data: writer.writerow([ avonleaclass.unitNumber, avonleaclass.newReading, ]) return response -
Django video analysis on background
I'm trying to build a webpage that analyze real-time video with Django. I succeeded in showing the analyzed results on a specific link(I added a few lines to add image analysis). However, the analysis is started when I open the link and when I close the link, the video analysis will be stopped. Opening multiple links also causes a problem. I need the video analysis to be started when I add a camera object and keep running until the server is closed. Also, analysis from multiple cameras need to be done in parallel. I'm searching for some solutions and bumped into "Celery" and "django-background-apps". Could they be a solution to my problems? Or are there any suggested solutions? Thank you :) from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livefe(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it … -
How to display all chat conversations using Django Channels?
When the conversations page is loaded, it should display a list of all active conversations. When a user send a message in a chat, this should be updated in the conversations list. How is it possible for the user to open a connection to the websocket, fetch the chats and listen for new messages? I use Django channels on the backend and Flutter on the frontend. -
Django - How to properly create a related Object on data Import?
I'm currently writing a Python script that allows me to read all metadata from media files like mp3, mp4 etc. and write it into a Database. The problem is that each "Media" object has x MediaStreams objects and I don't really understand how I can properly run trough all streams (index) and create the relation between my Media and MediaStream class/table. new_object = Media.objects.create(...) should work fine but how to get my streams related to it? See my current state of parsing madness down below: import ntpath import subprocess from shlex import join import json import xmltodict from App.models import Media def meta_single(descriptor): """Takes a single media file as argument from disk or http/https (descriptor="/path/to/file.mp4") and scrapes it for metadata. A utf8 encoded JSON object will be returned""" def get_plist_names(name_dict): return [o["string"] for o in (name_dict if isinstance(name_dict, list) else [name_dict])] def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) scrape_cmd = join(['./ffmpeg_binaries/ffprobe', '-print_format', 'json', '-show_streams', '-show_format', '-loglevel', 'quiet', '-hide_banner', descriptor]) scrapped_assets = subprocess.getoutput(scrape_cmd) clean_result = json.loads(scrapped_assets) #metadata = json.dumps(clean_result, indent=4, ensure_ascii=False, sort_keys=True).encode('utf8').strip().decode() #print(metadata) # General Meta filename_value = None bitrate_value = None duration_value = None size_value = None nb_streams_value = None media_type_value = None title_value = None artist_value … -
How to change title/label menu in django admin
Can i change the title/label menu in django admin? let say i wanna change "POLLS" to "MASTER" and "QUESTIONS" to "ALL QUESTIONS"? -
Django urls.py setup
I'm getting a ModuleNotFoundError: No module named admin from django.urls import include, path from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', include('admin.site.urls')), path('learning_log/', include('learning_logs.urls')), ]