Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to install python packages locally inside virtual environment
I am trying to install packages from my requirements.txt file but I am getting this error, it's interesting because I don't have any project dependency as such and I have already ran pip install -r requirements.txt error I am getting File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_sass' I want to install these dependencies such that they should be local only to the project I am working on, any idea how to achieve that ? -
Django run durable transaction via gunicorn
I have a django (3.2v) application with an atomic based transaction which uses durable option @transaction.atomic(durable=True) def get_account(): ... I'm able of running my project via python manage.py runserver and everything works fine. But when I run my project via gunicorn --bind :8000 --workers 3 myapp.wsgi:application I get the following error: TypeError: atomic() got an unexpected keyword argument 'durable' after removing durable=True param from atomic decorator like the code below, everything works like a charm. @transaction.atomic def get_account(): ... why this happens? how can I make this work? -
linebreaks not working properly in djagno
My linebreaks are not working when i try to use a custom filter and safe in my web site for publishing post. html: <p>{{ text|striptags|linebreaks|mention|safe }}</p> mention is my custom filter and my templatetags is: @register.filter(name='mention',is_safe=True) @stringfilter def mention(value): res = "" for i in value.split(): if i[0] == '#': if len(i[1:]) > 1: i = f'<a href="/recommendation/?q=%23{i[1:]}&submit=Search">{i}</a>' res = res + i + ' ' return res at the end i am using 'safe' so that the user can see the link.it is working but when i type linebreaks i am not seing the linebreaks inside my html.What am i doing wrong ? do i have problem in ordering my filter ? -
How to show Language code in field label in Django translated fields
i used django translated fields to create some monolingual fields in my models. It works good, but in admin page, in add page, there is two same fields for every translated fields i created. How can i show language code for each field? What it is showing now What i want it to be -
Select a valid choice. 6da87c51321849bdb7da80990fdab19b is not one of the available choices
I'm using answers field in form for just test purpose to see if it is returning the selected id of the value in post request when form is submitted, also I'm passing choices dynamically to the from views using get_form_kwargs(), On frontend it shows me proper choices but when one selected and submitted it shows me the error mentioned in Subject of this question Also FYI i have not included "answerss" field in models because i just wanted to test if it returns correct id on POST request. This is my Dynamically passed List from views.py to forms.py to fill the choices of "answerss" field created in init . This list keeps changing after every submission Also FYI this is a Quiz app so after every submission i redirect it into the same page where next question is rendered and different options are rendered in choice field [('d5730fbb3b1742d183d0968802859c7d', 'Africa'), ('6da87c51321849bdb7da80990fdab19b', 'Asia'), ('e0d084ff6e7544478523149186835132', 'North America')] This is my model.py class userAnswer(models.Model): answer_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id= models.ForeignKey(CustomUser,on_delete=models.CASCADE) question_id = models.ForeignKey(question,on_delete=models.CASCADE) text_ans = models.CharField(max_length=100) remaining_time = models.TimeField(default='23:00:00') correct_Answer_id = models.ForeignKey(correctAnswer,on_delete=models.CASCADE) This is my views.py class Start_Game(FormView): model = userAnswer template_name = 'test_template.html' form_class = Useranswer success_url = 'game' context_object_name = 'questions' … -
Foreign Key field is not registering in Database
I add a new foreign key in my model but it gives an error once I migrate. Field 'id' expected a number but got 'XD'. MODEL: item_tool= models.ForeignKey(Tools,default='XD', on_delete=SET_DEFAULT) CLASS: class Tools(models.Model): name = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Tools' def __str__(self): return self.name -
как сохранить картинку через URL в модель django
Необходимо разработать сервис, на основе фреймворка Django, который позволит загружать изображения с компьютера пользователя, или по ссылке, а затем изменять их размер используя библиотеку Pillow. Изображения должны сохраняться на диск. У меня получилось реализовать загрузку с компьютера, а вот по ссылке URL не получается. Моя модель: from django.db import models class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') def __str__(self): return self.title Моя форма: from django import forms class ImageForm(forms.Form): title_image = forms.CharField(max_length=200, label='Заголовок') url_image = forms.URLField(max_length=255, label="URL файла", required=False) image_image = forms.ImageField(label='Файл ', required=False) Моя вьюха: from urllib.request import urlopen import requests from django.core.files.base import ContentFile, File from django.core.files.temp import NamedTemporaryFile from django.shortcuts import render, redirect from .forms import ImageForm from .models import Image def image_upload_view(request): """ Загрузка файлов пользователем и обработка""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): if request.POST['url_image']: print('НЕ ПУСТАЯ УРЛА!') url = request.POST['url_image'] img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(url).read()) img_temp.flush() print(img_temp) resp = requests.get(url).raw print(ContentFile(resp)) # all_data['image'] = File(img_temp) image_save = Image(title=request.POST['title_image'], image=resp) image_save.save() img_obj = image_save return render(request, 'upload_app/index.html', {'form': form, 'img_obj': img_obj}) # # url = request.POST['url_image'] # # # # # try: # # resp = requests.get(url) # # result = urllib.request.urlretrieve(url) # # print(result) # # image_save = Image(title=request.POST['title_image'], image=ContentFile(resp.content)) … -
Declare Name/Variable with Docker Compose
Currently I am experimenting with Docker Compose but I want to declare a variable or something and some parts of my code and my Foldername get changed when I run docker-compose run ... Is that even possible with Docker? I cannot find something in the Web or on Stackoverflow. Thank you! -
Django .defer() for removing value from queryset
def get_client_queryset(query=None): queryset = [] queries = query.split(' ') for q in queries: details = clients.objects.filter( Q(name__icontains=q) | Q(number__icontains=q) | Q(email__icontains=q) ).distinct().defer(unique_num) for client in details: queryset.append(client) return list(set(queryset)) the .defer('unique_num') is still being returned and displayed in the queryset. The provided function is a search function -
django celery shows the error -- Process "ForkPoolWorker-1" pid:41 exited with "exitcode 70"
I have a celery scheduled task in my django which runs at 4 PM. After the implementation of this scheduled task it worked smoothly and doesn’t shows any error. Yesterday my celery task was failed due to below error Process "ForkPoolWorker-1" pid:41 exited with "exitcode 70" Task handler raised error: WorkerLostError('Worker exited prematurely: exitcode 70 Job: 1.')` I don’t know why this error is coming. I am using Django==3.2.4 celery==5.1.2 Some depreciation warning is also showing version 6.0.0. Use the accept_content instead The 'CELERY_TIMEZONE' setting is deprecated and scheduled for removal in alternative=f'Use the {_TO_NEW_KEY[setting]} instead') can any one help me to solve the above.My celery task is not a long running task. -
Export data from mongodb collection to excel with openpyxl
I want to export my mongodb collection to excel file using openpyxl but I can not figure out how to do this... I want to have something like the picture below can anyone help me? -
How would you design django app with multiple alerts
I have an app that tracks bitcoin and other cryptocurrencies, now let's say that each user can create multiple alerts against that price, for example buy cryptocurrency A when it reaches price X or sell B when it reaches price Y, and the database must be a SQL most likely Postresql. Now I had some architectures in my mind but all of them are non efficient means they use more resources than they should so I'm looking at the most optimum design for that kind of apps. -
How to change forms datefield from Gregorian calendar to Persian calender in django forms?
I want to get date from user with form without using models, But django DateField only have Gregorian calender. How can i change that to Persian(Jalali, Farsi, Solar) calender? forms.py class filterForm(forms.Form): month = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) -
I am having a problem with Django logging in a user
I am getting a problem with the login, I am following a tutorial class from Dennis on Django and for some reason I have getting this type error? What does it mean. Thank you TypeError at /login/ 'bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 3.2.6 Exception Type: TypeError Exception Value: 'bool' object is not callable Exception Location: C:\Users\inter\OneDrive\Django_Course\devsearch\users\views.py, line 48, in loginUser Python Executable: C:\Users\inter\OneDrive\Django_Course\devsearch\env\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\inter\OneDrive\Django_Course\devsearch', 'c:\users\inter\appdata\local\programs\python\python39\python39.zip', 'c:\users\inter\appdata\local\programs\python\python39\DLLs', 'c:\users\inter\appdata\local\programs\python\python39\lib', 'c:\users\inter\appdata\local\programs\python\python39', 'C:\Users\inter\OneDrive\Django_Course\devsearch\env', 'C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages'] Server time: Sat, 11 Sep 2021 17:25:14 +0000 Traceback Switch to copy-and-paste view C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▼ Local vars Variable Value exc TypeError("'bool' object is not callable") get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x000002CD3D1F8F10>> request <WSGIRequest: GET '/login/'> C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\inter\OneDrive\Django_Course\devsearch\users\views.py, line 48, in loginUser if request.user.is_authenticated: … ▶ Local vars -
How does gevent ensure that the same thread-local variables are not shared between multiple coroutines
I have a Python 2 django project, which was started with gunicorn, and write a lot of threading.currentThread().xxxxxx ='some value' in the code. Because the coroutine reuses the same thread, I am curious how gevent guarantees that the currentThread variable created in coroutine A(Thread 1) will not affect coroutine B (same Thread 1). After all, the writing on the code is: import threading threading.currentThread().xxxxx ='ABCD' Instead of import gevent gevent.currentCoroutine().xxxxx ='ABCD' (simulate what it looks like) thanks for your help -
Dynamic menu from database in Django
I am looking to store my nav links from a standard navigation menu in my database. Ideally, this would allow some specific (non-technical) users the ability to maintain links on the webapp. Today, my nav menu is a 'static' page included into my base.html and is the same across all pages served up. Any changes requires me to manually update the nav static file and re-deploy. My struggle (and it could be my limited django experience) is how to be able to generate the data and render it from within the base.html/nav include without having to literally generate the menu items on every single rendering of a page (e.g. getting the menu list and sending to all rendering calls). I have dozens of pages so this isn't really an option to do manually. I've searched for this and it looks like i'm not the only one, but the closest solution is from like 2006 and I'm sure there's been some likely advancements in this area over the past 15 years. Appreciate any info that can point me in the right direction. Cheers! -
Can't see code (every function and class block shows 3 dots ) in django modules when open with ctrl+click in vscode
enter image description here i try to uninstall and reinstall vscode and also try different python version(3.8 & 3.6) interpreter can't fix my issue -
Django 'featured' field? ModelName.objects.filter(featured=True)
ModelName.objects.filter(featured=True) I saw it. I looked it up. I didn't find any answer. I assumed it's mean featured like it's name and pretend I didn't have any question at all. But now I saw it again. WHAT IS THIS? How do Django model decide an objects is "featured". Is it true by default? Is it true when all property is not null or blank? Why is it true? Please someone give me the answer or I'll pretend I've already known it again. -
Multiple django server with a database server
I'm trying to create an application with the python3 Django web framework. and each of the features will be separated by docker container with different Django. The reason I'm trying to separate each feature is because to provide stable service even if one of the features is down or not functioning properly. for example, the app has a content web page. once client clicks the web page, then it shows content to the customer. btw the content is collected by the admin user manually with a specific URI. once it requests the URI, then django starts to collect the data from the API server and the data stored in MySQL database. However, while collecting the contents via API server, the web contents are not functions properly since django app still being progressing to collect bunch of data from API server. Therefore, I'd like to separate each function in the different Django webserver which running on docker container indivisually. To do that, multiple Django server will be running on each docker container, but, the database will be using the same single MySQL server. ex) models.py are defined by Django main server: class Menu(models.Model): school_name = models.CharField(max_length=120, null=True) Year = models.DecimalField(max_digits=65, decimal_places=0, … -
Which is better for blockchain Flask or django?
My app is a web app where the UI logic is from react JS and blockchain code is written in python, but I am having trouble in understanding which framework to choose for my backend , can somebody help me? -
Django MultiValueDictKeyError handling media
I am working on a django application in which i must store uploaded media to root/media and am getting the following error: 'media' Request Method: POST Request URL: http://127.0.0.1:8000/home Django Version: 3.2.6 Any help or pointers would be greatly appreciated! views.py code: def home(request): form = PostForm() signupform=SignupModelForm() comments=CommentForm() post=Post.objects.all() commentall=Comments.objects.all() member = Member.objects.all() user = User.objects.all() if request.method == "POST": form = PostForm(request.POST,request.FILES) comments=CommentForm(request.POST) if form.is_valid() and request.POST['action']=='posting': data=form.save(commit=False) data.user = request.user data.media = request.POST['media'] data.save() print("posted status") return redirect("/home") home.html code: <form method="post" enctype="multipart/form-data" style="float:left; width:100%; margin-left: -10%;"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="action" value="posting">Post</button> </form> Thank you! -
Deploying app fails with nginx and react/django
I've been trying to deploy a React+Django app in development but without success. So everything works fine locally using Django's python3 manage.py runserver In deployment, I am using gunicorn+nginx. When I set gunicorn and test it everything works fine. However, when I add nginx on top, the website works but it has lots of bugs, server calls fall 1 in 3 times, and the app is not stable. For example, I have a counter to count the numebr of visits in each page and it just keeps giving the sums of different combinations of visits each time I change the page, in short, the app is not stable. Here is my nginx configuration file /etc/nginx/sites-enabled/myapp server { listen 80; server_name myip; client_max_body_size 700m; client_body_buffer_size 16k; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/app; } location /media/ { root /path/to/app; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myapp/myapp.sock; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; try_files $uri /index.html; } location /api { include proxy_params; proxy_pass http://unix:/home/ubuntu/myapp/myapp.sock; } } I have no clue what's going on. Does nginx have to be configured specifically to allow React's api/ urls? -
Is there a simple way to check if a mail backend is valid in Django without sending a mail?
In my tool the users can provide a mail backend using certain keys and send their mails via the backend. This all works, but I would love to have a quick check if the provided backend actually will work. Using something like this check_mail_connection doesn't work as this actually returns False even though I entered a valid connection. from django.core.mail import get_connection class User(models.Model): ... def get_mail_connection(self, fail_silently=False) return get_connection(host=self.email_host, port=self.email_port, username=self.email_username, password=self.email_password ... ) def check_mail_connection(self) -> bool: from socket import error as socket_error from smtplib import SMTP, SMTPConnectError smtp = SMTP(host=self.email_host, port=self.email_port) try: smtp.connect() return True except SMTPConnectError: return False except socket_error: return False I don't want to send a test mail to confirm, as this can easily get lost or fail on a different part of the system. -
How can I resolve IndexError: list index out of range
I am trying to cal a django model function but i am getting list index error. This is the User model. ......................... fields ......................... def performance(self, start_time, end_time): actual = Sum("scores", filter=Q(status="completed")) q = self.taskassignt.filter( due__gte=start_time, due__lt=end_time ).annotate(actual=actual, total=Sum("scores")) return (q[0].actual / q[0].total) * 100``` ```user.performance(timezone.now() + timedelta(days=-7), timezone.now())``` is how I used it in my view.py. why am I getting this error? -
How to make a search method in django app
I have three models. How to do a search method to browse my three models together. For example if i search for the word "bluebird" in the search bar, i want it to browse through the three models to return the result to me. I saw on a forum the chain method that can be imported from itertools but i don't know how to use it ! models.py class Category(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=250) photo = models.ImageField(upload_to='pics/authors/', default='pics/default-author.jpg') biography = models.TextField(blank=True) def __str__(self): return self.name class Book(models.Model): author = models.ManyToManyField(Author) editor = models.CharField(max_length=250, blank=True) title = models.CharField(max_length=250) description = models.TextField(blank=True) date_added = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg') pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf') categories = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title