Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Can't access django admin [closed]
I cannot open django admin. What is the solution? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]``` [enter image description here][1] [1]: https://i.stack.imgur.com/EGt75.png -
How to insert a search engine instead of a list in the Django model
I am creating a model and a field is presented as a list, I would like it not to be a list but a search engine, this in the administrator when I want to insert new data in my table, I would like the author part to be a search engine and not a list. from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title enter image description here I don't know if this can be done in the model. -
javascript frontend received error 414 request URI too long when fetching an image from Django backend
I have a front end application, and that sends a string to backend. The backend then fetches an image, and returns it back to frontend as a jsonresponse. From the front end, I can console.log the image, and I know that I have received it. However, I still gets the 414 URI too long error from both frontend and the backend that sends the image to frontend. The frontend request is a POST but if I change it to GET, I get the same error. Also, everything worked as expected and I do see the image being inserted inside the img tag. Still I don't get the error message. async logoDropSelect (event) { //Fetch logo from backend and display it on front end img tag const response = await fetch(`getLogo/${this.newsletterLogoDropdown.value}`, { method:'POST', credentials:'same-origin', headers:{ 'Content-Type': 'application/json', 'Accept' : 'application/json', }, redirect: 'follow', body: JSON.stringify({}), }); const responseJson = await response.json(); this.newsLetterLogo.src = `data:image/png;base64,` + responseJson['image']; this.writeTemplateToIframe(this.hiddenHTML.innerHTML); } The code on the backend class FetchLogo(NewsletterViewPermissionMixin, View): def post(self, request, restaurantLogo, *args, **kwargs): data = dict() if restaurantLogo == 'restaurant1': image = Image.open('path_to_logo1.png') image = self.resizeImage(image = image, width = 300) if restaurantLogo == 'restaurant2': image = Image.open('path_to_logo2.png') image = self.resizeImage(image = … -
Is there a difference in authentication\authorization in Django and Django Rest Framework?
I am learing Django and Django REST Framework for project I recently added authorization/authentication in the Django project, and after that created API for the app, and for that I installed DRF. -
when I export posts from django I get <django_quill.fields.FieldQuill object at 0x7f0746389840>?
I'm working on Django blog and I want to export posts and I made it work but I have a problem when exporting text because I used Quill - rich text editor. body = QuillField() And when I export posts in excel, I got this <django_quill.fields.FieldQuill object at 0x7f0746389840>. excel is looking like this, image This is resources.py from import_export import resources from .models import Post class PostResource(resources.ModelResource): class Meta: model = Post This is views.py def export_data(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['file-format'] post_resource = PostResource() dataset = post_resource.export() if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'JSON': response = HttpResponse(dataset.json, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="exported_data.json"' return response elif file_format == 'XLS (Excel)': response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return render(request, 'dashboard/export.html') Any idea how to get the text in this body column? Thanks in advance! -
How to increase django/nxginx/uwsgi page load size limit?
I am using nginx and uWsgi with django (using daphne) to serve a simple one page site. I have reached a point where if I put more html objects on the page it loads to a certain point and does not load the rest. For example if I add a table with 60 rows the site loads the table up to 30 rows and nothing after that table loads. Or if I put 30 cards with text on it on the page, it loads a certain number of cards and does not load the rest of the site. If I only put 15 cards it loads the entire site. It is literally the html objects after the x amount of cards or rows that don't load. If I tap F-12 the rest of the site is just missing after the x cards or x rows. There are no errors or anything. This is what my nginx config looks like: # build_check_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///path/to/build_check.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 80; # … -
how to install all packages in the pipfile with pipenv in django project?
i want to install all python packages exist on the pipfile but when i run pipenv install command i received An error occurred while installing wcwidth==0.2.5 --hash=sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83 --hash=sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784! Will try again. An error occurred while installing whitenoise==6.2.0 ; python_version >= '3.7' --hash=sha256:8fa943c6d4cd9e27673b70c21a07b0aa120873901e099cd46cab40f7cc96d567 --hash=sha256:8e9c600a5c18bd17655ef668ad55b5edf6c24ce9bdca5bf607649ca4b1e8e2c2! Will try again. Installing initially failed dependencies... [pipenv.exceptions.InstallError]: Collecting appnope==0.1.3 [pipenv.exceptions.InstallError]: Using cached appnope-0.1.3-py2.py3-none-any.whl (4.4 kB) [pipenv.exceptions.InstallError]: Collecting asgiref==3.5.2 [pipenv.exceptions.InstallError]: Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) [pipenv.exceptions.InstallError]: Collecting asttokens==2.0.8 how can i fix this?