Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is impossible to add a non-nullable field 'name' to table_name without specifying a default
I have added a following field in my already existing model: name = models.CharField(max_length=128, unique=True) But it is giving following prompt when applying migrations: It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. I cannot set it's attributes to blank=True, null=True as this field is must. I cannot set it's default value as the field has to be unique. If I try to set it's default value in command prompt, it says plz select a valid option. How to fix it? -
CheckConstraint checking that the sum of fields do not exceed a value
How should one approach writing a CheckConstraint for model that triggers when the sum of two fields exceeds the value of another? I am able to do a CheckConstraint that triggers when the value of one field exceeds another. How do I adapt that to include summation? (i.e. to modify check=models.Q(entry__lte=models.F("limit")), to something like check=models.Q(F('entry') + F('extra') <= models.F("limit")) -
How to create Amazon Clone using Django or DRF?
I want to create a Amazon clone what should I use Django or DRF(Django Rest Framework) for it what process should i follow to create this project. What will be more feasible for this project Django or DRF? -
Django websocket how to send message from server immediately
I has a long time task in django, then I want to use channels instead of loop http request. I create a asgi server follow the tutorial. It can work but i don't know how to send a message twice. I want the server send 'msg1' ===> then sleep 3s ===> then send 'msg2' Here is my consumer code import datetime import json import time from channels.generic.websocket import AsyncWebsocketConsumer class MessageConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = 'BUILD' async def connect(self): # Join group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] if message == 'build': await self.build() async def sendMsg(self, data): # Send message to group await self.channel_layer.group_send( self.group_name, { 'type': 'sender', 'data': data } ) # Receive message from group async def sender(self, event): event.pop('type') # Send message to WebSocket await self.send(text_data=json.dumps(event)) print('send', datetime.datetime.now()) # takes long time async def build(self): await self.sendMsg('msg1') # it doesn't send right now time.sleep(3) # simulate long time await self.sendMsg('msg2') # frontend get two message but when i create a break point, it doesn't print anything … -
How to read additional data posted by form in django forms.py
I'm trying to write kind off bussiness mail management. In simple world, it'll have bunch of mail templates that will use un mailmerge operation There will be 2 kind of user: those who create mail templates, let's call them 'tc' (template creator) thoise who will issueing mails by term of triggering a mail merge. In this post I will only ask about the tc part. The work sequnce will : TC make a MS docx, upload to this web app web app will get all variable names from docx ( I use docxtpl library), and save it on MailTemplate model class. here is my MailTemplate model class class MailTemplate(models.Model): name = models.CharField(max_length=20) tfile = models.FileField(upload_to='uploads/mailtemplate', null=True, blank=True) schema = models.CharField(max_length=256, blank=True, null=True, editable=False) # conto: ['{"name": "kepada", "label": "Kepada", "type": 2, "format": ""}'] def __str__(self) -> str: return self.name all variables gathered by docxtpl, is combined in the form as list-of-dicts and saved in MailTemplate.schema example: [{"name": "date", "label": null, "type": 2, "format": ""}, {"name": "invoiceNumber", "label": null, "type": 2, "format": ""}, {"name": "company", "label": null, "type": 2, "format": ""}, {"name": "total", "label": null, "type": 2, "format": ""}] When TC first update new template, MailTemplate.schema is still empty. I make … -
How to run midee doctr in python file?
When I was trying to run the below code with python file : import os os.environ['USEA-TF'] ='1' from doctr.io import DocumentFile from doctr.models import ocr_predictor model = ocr_predictor(pretrained=True) document = DocumentFile.from_images('IM.jpg') result = model(document) result.show(document) json_response = result.export() print(json_response) Getting this error :- ImportError: cannot import name 'OrderedDict' from 'typing' (c:\users\shubham nagar\appdata\local\programs\python\python37\lib\typing.py) How will I able to run in .py file -
dockerizing django,nginx,gunicorn return exited code 3
Im new to learn this django in docker. Im following this guide: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ In my lab ubuntu server 22.04, all working well until nginx part, i up and build the docker-compose.prod.yml and result the "web" services is exited by code 3. And when i browse http://localhost:1337, it show me 502 Bad Gateway. What is this issue? I cant found any relate error about this. Tried to google but no luck. -
How to keep deleted rows from table in variable in Django
I want to delete all the rows in a tables but before that I want to store the old data and do some operation between old and new data. This is what I have tried. old_data = Rc.object.all() Rc.object.all().delete() # Now I fetch some api and apply saving operation on table I have noticed that data in old_data is updated to the new data. To test this I have done some thing like this for rows in old_data: check = Rc.object.filter(Q(id=dt.id)&Q(modified_date__gt=rows.modified_date)).exist() print(check) I found check is always false But when I print each rows in old_data just after old_data = Rc.object.all(), old_data remains same and does not updated to the new data. Is there something I am missing? How can I store all rows in the variable and then delete the rows ? Please help. -
How to add an optional page at the end of url route as part of query string
I have a django view as follow: @route(r'^nz/(?P<region>[\w\-]+)/(?P<town>[\w\-]+)/(?P<suburb>[\w\-]+)/$') def get_suburb_details(self, request, region=None, town=None, suburb=None, page=1): context = self.get_context(request) context['details'] = get_details(region, town, suburb, page) return render(request, 'res.html', context) The above route works with the following url: domain.com/wellington/wellington/karori/ Now I want to add an optional page at the end of this url (as part of the query string). How can do this? -
I can't open Django admin on browser after I tried apache
So, I am working with aws ec2. I have two projects going on. one is Django server which I use docker-compose to run, another is Yourls URL shortener and it uses Apache. I used to run Django and had domain point to it so that I can see it on chrome. But after running Yourls once and even deleting its docker image, I still cannot see django admin page on browser. it is showing this. enter image description here I have deleted all docker images to make sure nothing else is intefering. But still the same. ps aux result is as follows: Proto RefCnt Flags Type State I-Node Path unix 3 [ ] STREAM CONNECTED 15681 /run/systemd/journal/stdout unix 3 [ ] STREAM CONNECTED 23538 /run/containerd/containerd.sock.ttrpc unix 3 [ ] STREAM CONNECTED 22661 unix 2 [ ] DGRAM 17831 unix 3 [ ] STREAM CONNECTED 22633 /run/docker.sock unix 3 [ ] STREAM CONNECTED 24310 /run/containerd/containerd.sock.ttrpc unix 3 [ ] STREAM CONNECTED 18192 /run/systemd/journal/stdout unix 3 [ ] STREAM CONNECTED 22664 unix 3 [ ] STREAM CONNECTED 21460 unix 3 [ ] STREAM CONNECTED 24045 unix 3 [ ] STREAM CONNECTED 21430 /run/systemd/journal/stdout unix 3 [ ] STREAM CONNECTED 17792 unix 3 … -
DRF - overwriten serializer's create method but the is_valid returns erros
I am currently figuring out how to make my post request update the data of the entry if the id already exists in the database: I've overwriten serializer's create methods like this: class AttributeValueSerializer(serializers.ModelSerializer): class Meta: model = AttributeValue fields = ("id", "hodnota") def create(self, validated_data): id = validated_data.get('id') instance = AttributeValue.objects.filter(id=id).first() if instance: for key, value in validated_data.items(): setattr(instance, key, value) instance.save() return instance return super().create(validated_data) But the view which calls the serializer: serializer = AttributeValueSerializer(data=item[key], partial=True) if serializer.is_valid(): serializer.post() else: print(serializer.errors) returns an error {'id': [ErrorDetail(string='attribute value with this id already exists.', code='unique')]} I am not sure what should I be doing here. Should I somehow overwrite the is_valid method? -
Why response time with postgres is 15x higher than with sqlite?
Simple get request (django + django-rest-framework) with sqlite3 database takes 2ms. Using postgres, response time extends to over 30ms. Why is that, how to make postgres faster? Settings with sqlite: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Settings with postgres: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'drf-test', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } class Product(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150, blank=True) price = models.DecimalField(max_digits=5, decimal_places=2, default=0) class Meta: verbose_name = ("Product") verbose_name_plural = ("Products") def __str__(self): return self.name class ProductListAPIView(ListAPIView): queryset = Product.objects.all() serializer_class = ProductModelSerializer class ProductModelSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' -
deploy django on self server
hi I'm kind of new on server things and i have ready django project and want to setup server my self do it what step I should do ? i have try install negix and git and postgresql also some control panel name ajenti but got bugs and i try another but can't do the jab for djang and woork for wordpress and I try to install env on another try but dont know how to point my DNS server domain i use ubunto and connect to server via ssh and should i use python manage.py runserver to test on ssh or there are other methods -
Solidjs library rollup configuration: unresolved dependencies
I try to build a solidjs npm lib using rollup to provide some components. I intend to build esm and cjs module using the following rollup.config.js: import commonjs from "rollup-plugin-commonjs"; import typescript from "rollup-plugin-typescript2"; import babel from "@rollup/plugin-babel"; import postcss from "postcss"; import nodeResolve from "@rollup/plugin-node-resolve"; export default { input: "./src/index.ts", output: [ { file: "dist/index.cjs.js", format: "cjs", }, { file: "dist/index.esm.js", format: "esm", }, ], external: [ "@suid", "@suid/icons-material", "@suid/material", "solid-js", "solid-js/web", ], plugins: [ nodeResolve(), resolve(), commonjs(), postcss({ autoModules: true, plugins: [], sourceMap: true, extract: true, minimize: true, }), typescript(), babel({ babelHelpers: "bundled", exclude: "node_modules/**", extensions: [".ts", ".tsx"], }), ], }; Unfortunately, i cannot build this. Here's the error message: (!) Unresolved dependencies https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency ~/MonthPicker.module.css (imported by "src/MonthPicker.tsx") ~/DatePicker.module.css (imported by "src/DatePicker.tsx") @suid/icons-material/ExpandLess (imported by "src/MonthPicker.tsx") @suid/icons-material/ExpandMore (imported by "src/MonthPicker.tsx") created dist/index.cjs.js, dist/index.esm.js in 849ms If I understood correctly, nodeResolve() is supposed to help here, but i guess i have misconfigured it. EDITS: added postcss as @snnsnn proposed removed babel from this post (it seems this is a rollup issue) -
How do I create modifiable forms in Django?
What’s the current best practice approach to create a databases associated form with Django with fields that can be modified by the Admin or depending on the context (e.g. user group and other variables). I would like to use a Django native solution. This might be a very simple question. I’m new to Django, and I find it very hard to figure this out. Any help would be greatly appreciated! All the best Hans -
Django - Edit User Form and Profile Form To change Information and User Profile Picture
So In my Django Admin I have a User section (that comes default) and I made a profile section in my forms.py file. I want to add an option when you click in the profile page to redirect to and 'edit' profile page where a user can change their user/profile info including their picture. I'm still pretty knew to Django so I don't know where I need to begin. I have snippets of my code from different parts of my Django app to show because currently I don't know where to start. Models.py File: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # User Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False, blank=True) profile_pic = models.ImageField(default='static/chat/images/default-profile-photo.jpg', null=True, blank=True, upload_to='images/profile/') def __str__(self): return self.user.username # Create Profile When New User Signs Up def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() post_save.connect(create_profile, sender=User) fourms.py file: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): … -
Updating a Django webpage by calling itself in Ajax
In the example code below, Ajax calls (in the page.html) the same Python function (page()) which Django used to create the page in the first place. It gets a HTTPResponse object, which contains the page as it should look after the Ajax call. But the possibly modified page in the HTTPResponse object is not applied to modify the actual page. Is it possible to do so, or am I thinking something not doable? page.html $( document ).ready(function() { $.ajax({ url: "", success: function(data) { //Here to make the webpage determined by this page.html //to look like how it is rendered in the HTTPResponse object "data" } }) }) views.py def page(request): //... return render(request, page.html) urls.py urlpatterns = [ path('', views.page, name="page"), ] -
Gunicorn with django giving 500 with no extra information
I am trying to run django 3.2.16 with gunicorn, I get this output in console: [2023-01-15 23:45:39 +0100] [210935] [INFO] Starting gunicorn 20.1.0 [2023-01-15 23:45:39 +0100] [210935] [DEBUG] Arbiter booted [2023-01-15 23:45:39 +0100] [210935] [INFO] Listening at: http://0.0.0.0:8000 (210935) [2023-01-15 23:45:39 +0100] [210935] [INFO] Using worker: sync [2023-01-15 23:45:39 +0100] [210936] [INFO] Booting worker with pid: 210936 [2023-01-15 23:45:39 +0100] [210935] [DEBUG] 1 workers Everything looks like working, but when I go to localhost, I get Internal Server Error. It kinda behaves like if I had DEBUG = False, but I have DEBUG = True and there is also nothing in console. Django setup finishes and I also verify, that settings.DEBUG is indded true: My wsgi.py file: application = get_wsgi_application() print(settings.DEBUG) And of course runserver works fine. What else could that be? How to get some kind of error output? I tried capture-out and all the log files and levels that gunicorn provides but got nothing useful from the console. -
Processing an get request
I am trying to process a get request coming to my resource from an external server, from which I need to get the access_token parameter. The difficulty lies in the fact that the server sending me this request uses "#" instead of "?". So instead of getting mydomain.com/?access_token=12345 I get mydomain.com/#access_token=12345 x = equest.GET.get('access_token', '123') # I usually use get print(x) # 123` Pls help how I can get the value 12345 in my view function My Django version 4.1.4 I tried to process this string as mydomain.com/<path:slug> in order to get it in str() and use find() to get the necessary parameters. But because of the # sign, I didn't succeed. As if it doesn't get into slug at all -
Django Path.home() giving servers directory instead of users home directory
I am on a Django Project. Using version 4 and Python 3.10. I want to download file and my code is : downloads_path = str(Path.home() / "Downloads").replace('\\','/') if not os.path.isdir(f"{downloads_path}/{str(row['CUSTOMER NAME'])}"): os.makedirs(f"{downloads_path}/{str(row['CUSTOMER NAME'])}") pdf.output(f"{downloads_path}/{str(row['CUSTOMER NAME'])}/document.pdf") downloads_path = str(Path.home() / "Downloads").replace('\\','/') Giving me PermissionError : [Errno 13] Permission denied: '/var/www/Downloads' Its working on my local server but not in my live server. It is looking for my server's home location instead of my computers home directory. -
Django refuses to connect
I created my Django website, whenever I try to go on the website, it says 127.0.0.1 is not responding. I tried troubleshooting it and it says 127.0.0.1 is refusing connection. everywhere it says that there's a firewall issue how do I fix -
Why is Django's FileField giving me an encoding error?
I have a FileField that saves the file to my file system (Mac) for development, and retrieving this file works with its url, but I get an encoding exception when I try to read it; here's my code: View: def download_database(request, id): try: project = Project.objects.get(id=id) with project.database.open('r') as db: response = HttpResponse( db.read(), content_type="application/vnd.sqlite3, application/x-sqlite3") response['Content-Disposition'] = f'inline; filename={project.database.name}' return response except Project.DoesNotExist: raise Http404 HTML template: <a href="{{ project.database.url }}">Download</a> <a href="{% url 'download_database' project.id %}">Download</a> Again, the browser downloads the file correctly with the 1st version, but fails with the 2nd, with: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfb in position 106: invalid start byte ... contained in the exception trace: Internal Server Error: /project/download_database/54553950-15e5-4ea1-999e-8a6ec2a84ffb Traceback (most recent call last): File "/Users/csabbey/code/survey_server/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/csabbey/code/survey_server/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/csabbey/code/survey_server/survey_server/views.py", line 70, in download_database db.read(), content_type="application/vnd.sqlite3, application/x-sqlite3") ^^^^^^^^^ File "<frozen codecs>", line 322, in decode UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfb in position 106: invalid start byte [15/Jan/2023 20:33:01] "GET /project/download_database/54553950-15e5-4ea1-999e-8a6ec2a84ffb HTTP/1.1" 500 90923 This reading works when reading from Google Cloud Storage, which we use for production systems, but not when … -
Error during template rendering: 'set' object is not reversible after installing django-debug-toolbar
I created a new fresh django project. I created an app inside the django project and then tried to install django-debug-toolbar. I followed the instructions from the official docs. When I point to the app url I got Error during template rendering: 'set' object is not reversible The files from the base project urls.py and settings.py were modified as follows: #urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('meetings/', include('meetings.urls')), path('__debug__/', include('debug_toolbar.urls')) ] #settings.py #... DEBUG = True #... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'meetings', 'debug_toolbar' ] #... MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] #... INTERNAL_IPS = [ '127.0.0.1' ] The config files for the app "meetings" have the following configuration: #urls.py from django.urls import path from . import views urlpatterns = { path('hello/', views.say_hello) } #views.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return render(request, 'hello.html', {'name': 'PE'}) <!--template/hello.html--> <html> <head> <title>Welcome</title> </head> <body> {% if name %} <h1>Hello {{ name }}</h1> {% else %} <h1>Hello … -
Django GPU model deployed in Nivdia/Cuda container consumes all GPU memory
I'm using an Nvidia/Cuda container to host my Django website. It's a new deployment of an old website that used to utilize CPU scored models. The rationale for using the Nivida/Cuda docker is to accelerate scoring speed when requesting an analysis through the Django interface. The difficulty I am running into is that my docker-compose build is generating memory errors. I hadn't anticipated that Celery / Django would load the models directly into CPU in advance of an actual scoring call. Accordingly, the GPU memory is quickly consumed and my website is not launching appropriately. My question is whether there are ways that I could manage the GPU memory more effectively. Presently, I am loading the Tensorflow models in my Django settings.py invocation. Since I am using Celery, it is effectively doubling the GPU memory demand. At runtime, most models (but not all) are using Celery-based scoring mechanisms. Some options I am considering: Ways to eliminate non-scoring components of the Tensorflow model that take up unnecessary space; Passing an environment variable to identify Celery vs Django to conditionally load models; Limiting my Tensorflow model complexity to reduce size. Any other possibilities that others have used? -
unable to print the username onto console in JavaScript
I have a html file with a linked js <script type="text/javascript" src="{% static 'js/cart.js' %}"> var user= '{{request.user}}' </script> and in cart.js i am trying to print the user variable but i keep getting an error saying uncaught ReferenceError user is not defined. any ideas on how to resolve this?