Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change model field value after button click
I do really know that is a common topic but I've already checked every solution i could find and it did not work for me. I would like to add user points using button click. views.py def add_points(request): if request.GET.get('mybtn'): profil = get_object_or_404(Profile, created_by=request.user) profil.points += 10 profil.save(update_fields=["points"]) return render(request, 'users/profile.html') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to="profile_pics") points = models.PositiveIntegerField(default=0) people = models.PositiveIntegerField(default=0) html file <div> <form method="POST"> {% csrf_token %} <input type="submit" class="btn" value="+10 pkt" name="mybtn"/> </form> </div> I have tried diffrent solutons but nothing really worked out for me. -
Input type range and input type text as the one input
while i was writing an app in django I've found small problem. I want to put range slider and text input as one input. I've joined them with small js script and it works well, no problems there, but still. There are two inputs instead of one. Is it possible to merge them somehow? Only one of them send any variables trough form. -
Single Sign On between Django and VueJS applications
The old part of the website was built using django templates. For the new modules, we plan to use drf and a front-end framework, and nginx for routing the urls between the old modules and new modules. How do we share authentication between the two different apps? -
Apache, mod_wsgi and virtualenv : How to configure apache to use several mod_wsgi modules simultaneously
I have two Django projects : one using Python2.7 and the other using Python3.6 (together with the appropriate version of Django). I am working on Ubuntu 18 and each project have its own virtualenv. /etc/host and Apache are configured so that mysitePython2.localhost and mysitePython3.localhost are sent to each website. Until now, I have been unable to make both project work simulatenously on port:80. If I want the Python2.7 one to work, I have to reinstall the package libapache2-mod-wsgi ; then, if I want the Python3.6 project to work, I have to reinstall the package libapache2-mod-wsgi-py3. I have looked into mod_wsgi-express but it seems I cannot have both a mod_wsgi for 2.7 and 3.6 enabled. Is there any solution which allows me to access on port:80 of the same server two wsgi websites with different python versions? -
Django if image is empty
I created an article creation form. There is also have image upload button. I used Pillow for resize to uploaded image. But when I say Save form without upload image take this error; forms.py in clean_image, line 19 'NoneType' object has no attribute 'name' There is no problem when I save the article with the image. But I can't save without image. how do I say, if don't upload any picture "skip this section "(def clean_image (self):)"? forms.py from django import forms from .models import Article from django.core.files.base import ContentFile from django.utils.translation import ugettext_lazy as _ from PIL import Image import hashlib import io class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ["title", "content","image"] def clean_image(self): image = self.cleaned_data.get('image') md5 = hashlib.md5() md5.update(repr(image.name).encode('utf-8')) **#19.line is here!!!** file_name = md5.hexdigest() if image.size > 30 * 1024 * 1024: raise forms.ValidationError(_('File is too big.'), code='invalid') image = Image.open(image) if image.size[0] < 600 or image.size[1] < 600: raise forms.ValidationError(_('Your image needs to be at least 600x600.')) if image.format not in ('BMP', 'PNG', 'JPEG', 'GIF'): raise forms.ValidationError(_("Unsupported image type. Please uplod a bmp, png, jpeg, or gif."), code='invalid') image.thumbnail([1024, 1024], Image.ANTIALIAS) image_io = io.BytesIO() image.save(image_io, format=image.format) image_name = '{}.{}'.format(file_name, image.format) image = ContentFile(image_io.getvalue(), … -
Docker: TypeError: You must specify a directory to build in path [3074] Failed to execute script docker-compose
I am trying to add Dockerize my Django Rest Framework project However When I try to do a migrate command I get a TypeError: You must specify a directory to build in path [3074] Failed to execute script docker-compose Below is Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt Below is my docker-compose-file version: '3' services: web: build: .gitignore command: python src/genomic_project/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres Below is the change I made in my django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'GenomicPostgres', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', } } Below is the Traceback This is the command I ran samir@VB:~/PycharmProjects/genomic_prediction$ sudo docker-compose run web python src/genomic_project/manage.py migrate Below is the error [sudo] password for samir: Creating network "genomic_prediction_default" with the default driver Pulling db (postgres:)... latest: Pulling from library/postgres f17d81b4b692: Pull complete c1f213be5edb: Pull complete 9c79723dc510: Pull complete 603a66804109: Pull complete b4f1b901e523: Pull complete 99d9650419de: Pull complete 02d87bb25bad: Pull complete 333a24caa91e: Pull complete 2ace4c87570a: Pull complete 3add70ce5596: Pull complete 947f7d36d500: Pull complete 5e194c53f09f: Pull complete e0d520465b2d: Pull complete 97f206959126: Pull complete Digest: sha256:76ff79d72ef95b7c136037c0e8ab629914a8d5e430a3a2aef7d959b5da9a33c5 … -
Django on ManyToMany insert adds null key
I have a Django project with two models for which there is a many-to-many relation. When I try to add one entry to the relative table, Django should create unique identified for this entry but instead it set a null id, therefore i get a integrity error. Here is the code i use: models.py: class Activity(models.Model): id_att = models.AutoField(primary_key=True) ... types = models.ManyToManyField( Type, related_name='att_type', through='att_type', through_fields=('id_att', 'id_type'), ) class Type(models.Model): id_type = models.AutoField(primary_key=True) descr_type = models.CharField(max_length=30) class att_type(models.Model): id_att = models.ForeignKey( Activity, on_delete=models.CASCADE, related_name='att_type' ) id_type = models.ForeignKey( Type, on_delete=models.CASCADE, related_name='type_att' ) forms.py def save(self, id_att=None, usr=None, commit=True): ... for t in types: att_type.objects.create( id_att=att, id_type=t ) ... This is the error I get: IntegrityError at /persport/att/1029/ null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 1029, 8). I ran this code on my machine with ubuntu 16.04, and it worked as expected, but when try to run this on a VPS with ubuntu 16.04.5 I get the error above. Before I ran the code on the server I dump the database on my machine and I restore it on the server. If that can help I have on the server Django 2.0.3 and Postgres … -
Integrating webpack into a Django project
I have a pretty standard Django package layout for a package named wptst, with Python source in wptst/wptst/..., and Javascript sources in wptst/js/*.js: wptst `-- js | `-- wptst-source.js |-- package.json |-- webpack.config.js `-- wptst |-- static | `-- wptst | |-- wptst.js | |-- wptst.min.af2dc5001a126702513d.js | `-- wptst.min.af2dc5001a126702513d.js.map `-- templates `-- wptst `-- include-script.html Django wants compiled resources under wptst/wptst/static/wptst/.. The problem is the last file include-script.html. I want to include it in other templates {% include "wptst/include-script.html" %} so I don't have to manually edit the hash-value in the generated .js files. For this to work I'd like it to contain: {% load staticfiles %} <script src="{% static "wptst/wptst.min.af2dc5001a126702513d.js" %}"></script> I've almost gotten it to work with the following in webpack.config.js entry: { wptst: './js/wptst-source.js' }, target: 'web', output: { path: path.resolve(__dirname, 'wptst/static/wptst'), filename: 'wptst.min.[contenthash].js', library: 'wptst', libraryTarget: "var" }, plugins: [ new HtmlWebpackPlugin({ filename: path.resolve(__dirname, 'wptst/templates/wptst/include-scripts.html'), inject: false, template: 'wptst/templates/wptst/include-template.html' }) ] and the following in include-template.html: {% load staticfiles %} <% for (var jsfile in htmlWebpackPlugin.files.js) { %> <script src="{% static "wptst/<%= htmlWebpackPlugin.files.js[jsfile] %>" %}"></script> <% } %> but it generates <script src="{% static "wptst/../../static/wptst/wptst.min.af2dc5001a126702513d.js" %}"></script> I can get rid of the ../../ if I output … -
Django ORM How to use annotated field in filter
I have a queryset: Event.objects.annotate(event_date=Func(F('start_date'), F('end_date'), Value('1 day'), function='generate_series')) Now i want filter all my events where event_date >= value but when i try do queryset.filter(event_date__gte=value) I get error: argument of WHERE must not return a set LINE 1: ..., '1 day') AS "event_date" FROM "api_event" WHERE generate_s... I think its because when i try filter event_date__gte the ORM set again Func and dont use already calculated value event_date Do you have idea how to use event_date in filter.? -
share huge memory object between gunicorn processes
I am running django app on nginx webserver, running 5 gunicorn workers (aka processes) i need to initialize large dataset (AI model) into memory, so the API calls can get data from it. the set is around 200MB. the problem is that if each gunicorn process will init this dataset, then the memory usage (only for this dataset) is 1GB (200mb * 5 processes). what is the best approach to avoid it? so less memory will be used on my webserver for this dataset? -
Edit record before delete. Django DeleteView
I have the follow models: class Category(models.Model): .... posts = models.PositiveIntegerField(_('numero post'), default=0) .... class Post(models.Model): .... categories = models.ManyToManyField(Category, blank=True, verbose_name=_('categorie')) .... the Category.posts field counts the number of the posts related to it's own category. I increase the counter into the CreateView in the following way: class CreatePostView(LoginRequiredMixin, CreateView): model = Post ... def form_valid(self, form, **kwargs): ... categories = self.object.categories.all() for category in categories: category.posts = category.posts + 1 category.save() self.object.save() return super(CreatePostView, self).form_valid(form) Whene i delete the blog post i need to decrement the counter when the Post is deleted. I've tried to do in this way: class DeletePostView(LoginRequiredMixin, DeleteView): model = Post ... def form_valid(self, form, **kwargs): ... categories = post.categories.all() for category in categories: if (category.posts - 1) > 0: category.posts = category.posts - 1 category.save() return post But it doesn't work, because the record is deleted before that this method is called. How can i do this operation before that the record is deleted? -
Django passenger_wsgi.py issue
I run Django on an A2 Hosting Linux shared hosting account. Previously, I was using an old version of Django and Python. I was also using FCGI. I recently changed to a new server and am now using Django 2.1.2, Python 3.6.0. and Phusion Passenger. I can't get the passenger_wsgi.py to load my website and I can't find the error log to try and resolve the problem. The .htaccess file is in the public_html directory. My app files are stored in: /home/username/example.com/ The folder/file structure in the example.com directory is: -media -mysite --- init.py --- settings.py --- urls.py --- wsgi.py -public -tmp -manage.py -passenger_wsgi.py # The contents of the passenger_wsgi.py file: import os import sys import mysite.wsgi application = mysite.wsgi.application cwd = os.getcwd() sys.path.append(cwd) #sys.path.append(os.getcwd()) sys.path.append(cwd + '/mysite') SCRIPT_NAME = os.getcwd() class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI since Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = PassengerPathInfoFix(application) The site produces an error (image below). I've been trying to fix it all day … -
Locking rows in Django
I'm trying to implement this awsome solution about row locking in order to assert atomic insertions conditioned by row counts in Django while using PostgreSQL as DB backend. I've tested the solution in the PostgresSQL shell like this: BEGIN; SELECT * FROM teams WHERE id = 3 FOR NO KEY UPDATE; -- other stuff COMMIT; and it worked as a charm: while executing the same code in another shell, it got blocked (exactly what I'm looking for) till I run COMMIT; in my first shell. However, I can't get it working in Django. I've tried differentet approaches, like: 1- Executing the whole algorith as raw SQL: with connection.cursor() as cursor: cursor.execute("BEGIN;") cursor.execute("SELECT * FROM app_team WHERE id = 1 FOR NO KEY UPDATE;") #other stuff cursor.execute("COMMIT;") 2- Wrapping that with a with transaction.atomic(): statement instead of the raw BEGIN; and COMMIT; queries 3- Using the default Django's select_for_update: with transaction.atomic(): team = Team.objects.select_for_update().get(id=1) Which is the best way to implement such a mechanism in Django? -
Filling a Django admin form from an API request
I am currently learning Django (v2.1) and I am wondering what is the best way to populate an admin form from an API request. For example, if I am adding a new user in the admin and I enter a "zip code/postcode", the system should do a call to a remote address lookup API and based on the result, should populate the rest of the address fields in the admin form. How do I add a button in the admin section next to the "zip code" field and how do I link that button to an action to fill the other fields? Do I use JS or do I extend an admin template or do I override an admin view? Links to example code and/or docs would be great. Thanks. -
How to cache a FK lookup
I find myself using model property methods to access fields based on an FK lookup, such as: @property def platform_id(self): return self.item.platform_type_id if self.item else None @property def runtime(self): return self.item.video_length if self.item else None However, the issue with the above is, each time I call the item from a template, it does an FK lookup. Is there a way around this, other than doing it in the view, like this: item = self.item platform_id = item.platform_type_id video_length = item.video_length -
Scheduling (cancellable) django tasks in future
I have a Django site which allows users to create events that will start at a particular time on a particular date. Crucially, they can also change the start date/time of the event whenever they like, right up the time it is due to start. When the event starts, I need to run a particular task which will set up the next event. Idea 1 - APScheduler My initial thought was that I could use APScheduler for this but this isn't scalable because APScheduler runs in the same process as the web process so if I scale it up, the task is run more than once. Idea 2 - celery/redis Then I changed to using celery (and redis) but that has the problem that the only way to cancel an event (when the user changes the start time of an event, for instance) is to flag it as revoked in the celery worker, causing it not to be executed when redis kicks it off. This would be fine but it needs me to use the statedb argument to celery (to ensure the list of revoked tasks is maintained when the worker is restarted) and I can't do that as I'm … -
Django TemplateSyntaxError For loop
I'm having some problem with Jinja in Django. I mean I'm getting error like this when I'm trying add some for loop inside my template TemplateSyntaxError at /personal/ Could not parse the remainder: '(3)' from 'range(3)' Request Method: GET Request URL: http://127.0.0.1:8000/personal/ Django Version: 2.1.3 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(3)' from 'range(3)' There is a snip of code where I'm using this loop 43 <div class="dropdown-menu" aria-labelledby="navbarDropdown"> 44 45 {% for i in range(3) %} 46 {{ i }} 47 {% endfor %} 48 <a class="dropdown-item" href="#">ASD</a> 49 <div class="dropdown-divider"></div> 50 51 </div> A tried as well send some data from view to template but still the same error. I use Jinja 2 and Django 2.1 -
NOT NULL constraint failed when running test
I'm receiving the error; django.db.utils.IntegrityError: NOT NULL constraint failed: boards_topic.starter_id when running my unit test; def test_new_topic_valid_post_data(self): url = reverse('new_topic', kwargs={'pk': 1}) data = { 'subject': 'Test title', 'message': 'Lorem ipsum dolor sit amet' } response = self.client.post(url, data) self.assertTrue(Topic.objects.exists()) self.assertTrue(Post.objects.exists()) The line of the error is; response = self.client.post(url, data) My views.py class looks like; from django.contrib.auth.models import User from django.shortcuts import render, redirect, get_object_or_404 from .models import Board, Post from boards.forms import NewTopicForm def home(request): boards = Board.objects.all() return render(request, 'home.html', {'boards': boards}) def board_topics(request, pk): board = get_object_or_404(Board, pk=pk) return render(request, 'topics.html', {'board': board}) def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) user = User.objects.first() # TODO: get the currently logged in user if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.board = board topic.starter = user topic.save() post = Post.objects.create( message=form.cleaned_data.get('message'), topic=topic, created_by=user ) return redirect('board_topics', pk=board.pk) # TODO: redirect to the created topic page else: form = NewTopicForm() return render(request, 'new_topic.html', {'board': board, 'form': form}) and my models.py from django.db import models from django.contrib.auth.models import User class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.TextField(max_length=100) def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete=models.CASCADE) … -
Assign default group to new user Django
I'm trying to assign a group to every new user registered into the system. I've already read something about it in another questions but I don't really know where to add the necessary code to make it work. I'm using Django 2.1.3 and I'm logging users using allauth (social login, but it shouldn't make any difference as a new instance in the User table is created) -
Media files in Django for Google Cloud development - how do I enable media storage on Google Cloud?
I am running and a Django webpage on Google Cloud standard app engine and I have a hard time figuring out how to use Django media auth transfers to and from Google Storage buckets. I have tried to implement the package django-storages for Google Cloud, but the documentation and solution does not mention a crusial part of Django, namely the media transfers. Link to package documentation: https://django-storages.readthedocs.io/en/latest/backends/gcloud.html Neither does the Google Cloud documentation mention anything about this issue. I have then tried to follow https://github.com/jschneier/django-storages/issues/491 and Configure Django and Google Cloud Storage? but the solutions are outdated. Can someone give an up-to-date explaination of the implementation of authendticated media in Django for Google Cloud solutions (Gcloud appengine and Gcloud storage)? Or at least point the missing links in the posted outdated solutions? -
How to create query in django with query in url, and return the filtered result based on the url?
I found several similar answers, but I could not solve the problem (maybe I searched wrong) anyway. I'm trying to do the following: Filter a result by getting the value of "q" where is the input containing the value to search Add the "q" value in the url, like "/search?q=test" Copy the url above and from there get the filtered result My problem so far is: The value of "q" is only added in the url after another search, ie the url contains "q" with the previous search value, which is bad I can not access the url and have the results filtered, since when I enter this url, a new request object with no value for "q" is created, so I get a ValueError So far what I've done is: template <form method="POST" action="{% url 'blog:post_search' %}?q={{ query }}" class="form-inline"> <div class="md-form my-0"> <input name="q" class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Pesquisar" aria-label="Search"> </div> <button class="btn btn-outline-white btn-sm my-0" type="submit">GO</button> {% csrf_token %} </form> urls.py urlpatterns = [ # .... path('search', views.post_search, name='post_search'), ] views.py def post_search(request): template = "blog/post_search.html" query = request.POST.get('q') if query: posts = Post.objects.filter(title__icontains=query) else: posts = Post.objects.all() context = {'posts': posts, 'query': query} return render(request, … -
Why django does not create an app as a subfolder?
I run into problem of creating an app in python, django framework. Before, in command promt, I run C:\Users\(username)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.7\py manage.py runserver which works perfectly, after that I run C:\Users\(username)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.7\py manage.py startapp myapp and it does not create any folder "webapp" at all. Please, help. My OS is Windows 10, Python version 2.7.8, Django version 2.1.3, pip version 10.0.1 Also, when running pip install -U django getting Requirement already up-to-date When running django-admin.py startapp myapp getting Permission denied -
How can I initialize django web server whenever I submit values from template?
I'm new in django web development. Now, I construct web app with ete3 toolkit (using pyqt to generate tree image). The problem is my app works fine only at first time but after re-submit values from template, it doesn't draw image. (just make empty images) When I restart django web with manage.py runserver, it works again only in first time. error message looks like this image : error message related to QThread QObject::startTimer: Timers can only be used with threads started with QThread I think there is a program(maybe... ete3) start QThread at first time and it still running while I re-submit another value. Is there any way to init django web server or terminate QThread without objects? -
Getting a 301 instead of 200 on my production environment because of a redirect from '/' to 'https://testserver/'
I have the following test on my home page : def test_homepage_is_available(self): url = reverse('home') response = self.client.get(url) self.assertEqual(response.status_code, 200) On my dev server, this works fine and the test passes. On my production server, I get an error. The response.status_code is 301. The url from reverse('home') is /. The response['location'] is https://testserver/. And so it looks like Django is redirecting from / to `https://testserver/. But why ? And why does it do it only on my production server ? How can I fix this error ? -
Mathematical operations in templates
In a layout I have a predefined number of placements/spaces. I want to populate this with images, but there are cases where there is no image, are not enough: When have all of them occupied, this works: {% for placement in placement_list %} <a href="{{ placement.url }}"> <img src="{{ MEDIA_URL }}{{ placement.image }}"/> </a> {% endfor %} But I want to show a default when are empty spaces. I know that the length I can check with {{ placement_list|length }} I want to have something like: for i to (MAX_NR_placements - {{ placement_list|length }}) <img src="default" />