Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I merge grpc client and http request?
I want to merge http request and grpc client that means: I have a request for create some object. my service is gateway that means it sends data in celery task and grpc client sends a request and receive stream responses. when should i run this client? should i run the client in same function that sends data in celery task or not? I am really confused. -
Django - How to redirect back to search page and include query terms?
My pages/views are structured as follows: index.html => search_results.html => object_details.html, in which user can make a POST request in object_details.html. I am trying to redirect back to search_results.html after the POST request, but also keep both query strings. The url of search results shows as follows, and can have 1 or both queries made: www.example.com/search-results/?search_post=xxxxx&search_author=xxxxx The closest I am able to get what I want is using: return redirect(reverse('search-results') + '?' + 'search_post={{search_post}}'+'&'+'search_author={{search_author}}') however this would actually show "{{search_post}}" and "{{search_author}}" in each of the 2 fields of the search form in search_results.html Also, my search_results view has the following: search_post = request.GET.get('search_post') search_author = request.GET.get('search_author') How can I do this? Thank you -
Django admin panel model in main page
I have few admin models, how can I display one of the admin models in the admin panel main page so the fields of such model show without having to click on the model in admin panel homepage. Similar to the image below, a model field inside a box showing in the main admin page is what I need. -
WebSocket connection to 'ws://127.0.0.1:8000/ws/iphone/' failed:
Whenever I'm visiting http://127.0.0.1:8000/rooms/iphone/, I'm getting the below error: WebSocket connection to 'ws://127.0.0.1:8000/ws/iphone/' failed: I'm developing a DJango chat web application but facing this issue from past many days but didn't got any solution, if anyone has some knowledge in this domain, then please help me to get out of this issue. index.html <h1>List of Rooms</h1> {% for chatroom in chatrooms %} <a href="{% url 'chatroom' chatroom.slug %}">{{ chatroom.name }}</a> </br> {% endfor %} consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name= 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.channel_layer, self.room_group_name ) room.html {{ chatroom.name }} <form method="post"> {%csrf_token%} <input type="text" name="message" placeholders="Enter message"> <button type="submit">Send</button> </form> {{ chatroom.slug|json_script:"json-chatroomname" }} <script> const chatRoomName = JSON.parse(document.getElementById('json-chatroomname').textContent) console.log(chatRoomName) const chatSocket = new WebSocket( 'ws://' +window.location.host +'/ws/' +chatRoomName +'/' ) console.log(chatSocket) chatSocket.onmessage= function(e){ console.log('This is a message') } chatSocket.onclose = function(e){ console.log('Socket closed' + " " + e) } </script> routing.py from django.urls import path from .import consumers websocket_urlpatterns=[ path('ws/<str:room_name>',consumers.ChatConsumer.as_asgi()), ] I tried a lot to solve this problem but didn't got the solution from past few days. Plz help me to solve this issue. … -
Chatbot Frontend for Django Backend API
I made a simple backend API using Django REST and I wanted to make a chatbot using React js. I asked ChatGPT (lol) for an overview of how I could do that and it recommended making a separate Github repository for the React.Js environment as it could mess with my Django Virtual environment. I'd rather not use 2 repositories because this is a project for my resume and I wanted everything on one repository just for simplicity. Is that still possible or should I listen to Chat GPT? Thank you -
Chrome browser can't get csrf from cookie
I copy the code from Django official site to get csrftoken from cookie. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } csrftoken = getCookie('csrftoken'); It originally works well, but in some days it can't work for Chrome anymore. But it still works for Firefox. -
NoReverseMatch at /food/1/ Reverse for 'delete_item' with arguments '('',)' not found. 1 pattern(s) tried: ['food/delete/(?P<id>[^/]+)/\\Z']
[enter image description here](https://i[enter image description here](https://i.stack.imgur.com/SYkkd.png).stack.imgur.com/eGkw2.png) so im getting error in noreverse match found -
Pass a .zip file to a Docker container using python
I am using the Docker SDK to try and push a file from a Django web request method of POST to a Docker container. In my use case, the .zip file cannot touch the local machines file directory or load into memory. The file must go straight to the Docker container. This is the code I have so far but I cannot seem to find a way to get a file to passthrough to the container and get back command output from the commands I am running. Any help would be greatly appreciated. import docker client = docker.from_env() # start the container container = client.containers.run( image='myimage:latest', command='mkdir /tmp/upload', remove=True, detach=True, network_mode='none', ) try: # write the uploaded file to the container's file system container_id = container.id container_exec_command = f'cat > /tmp/upload/{zipfile.name}' _, stream = container.exec_run(cmd=container_exec_command, stream=True) with zipfile as f: for chunk in f.chunks(): stream.write(chunk) # perform the rest of the processing inside the container container_exec_command = f""" cd /tmp/upload # unzip the file echo y | unzip -P {filePassword} {zipfile.name} # get the filename of the other file in the directory filename=$(find . -maxdepth 1 -type f ! -name '*.zip' -printf "%f\n") # run sha256 sum against it, then … -
Pass an argument to a url with hx-get
I'm using HTMX to render different partial templates in a 'group-detail' page. The get requests are triggered by click event, and rendered in a tag. However, I'm trying to pass the group information so I can render the correct information in the partial template, but the data isn't being rendered. <li><a hx-trigger="click" hx-get="{% url 'groups:info' group.slug %}" hx-target="#group-content" class="btn btn-outline btn-rounded btn-tertiary btn-with-arrow mb-2">Info<span><i class="fas fa-chevron-right"></i></span></a></li> Here I'm passing the slug argument so it can know which group data render. This is the partial view: def group_info(request, slug): group = Group.objects.filter(slug=slug) context = { 'group' : group } return render(request, 'groups/partials/info.html', context) And I'm trying to render {{group.name}} in the info.html template for example, but nothing gets shown (the correct slug is being passed, the correct template is being rendered, but not the {{}} tags). Not getting any error neither. Am I missing something on passing URL arguments with htmx? -
Creating an event driven architecture using Django
I would like to create an event driven architecture in Django. Every time a database record is created, updated or deleted, i would like to create and event, posting it to a queue ( like kafka, sqs, or something similiar). I know that Django has a post_save method, that I could use to capture the record and post it in a queue, but I suppose that I could suffer for a dual write problem, i.e., update the database, but fails to post message in the queue. Does Django have any different mecanism? Does Django retry the post_save method? Should I use a outbox pattern or process database bin log instead? -
Why is timezone.now showing a future date when being applied as a default value to DateField in django
Here are the relevant settings in my project: settings.py TIME_ZONE = "US/Mountain" USE_TZ = True models.py (using timezone.now) class Submission(models.Model): date_created = models.DateField( default=timezone.now, blank=True, ) datetime_created = models.DateTimeField( default=timezone.now, ) If I create a Submission at 5PM MST on 03/01/2023 these are the values I get: date_created: "2023-03-02" datetime_created: "2023-03-01 17:00:00-07:00" Why would date_created be using the date of the following date? -
Using Django DecimalField with Select Widget
I'm not sure if there is something special I should be doing but I have a model and form similar to the following; # models.py from django.db import models class ObjectModel(models.Model): object = models.DecimalField(max_digits=10, decimal_places=2) # my_settings.py from decimal import Decimal object_choices = [ (Decimal('1'),'1'), (Decimal('1.5'),'1.5'), (Decimal('2'),'2'), (Decimal('2.5'),'2.5'), (Decimal('3'),'2.5'), ] # forms.py from django import forms from my_settings import object_choices from models import ObjectModel class ObjectForm(forms.ModelForm): object = forms.ChoiceField(choices = object_choices) class Meta: model = ObjectModel fields = ['object'] The form renders fine, and saves the object without any problem. I can see in the Django Admin that the value I select on the form gets saved to the model, and all the other fields (not shown above) render and work fine. When I load a form to edit the model rather than create a new one, e.g views.py from forms import ObjectForm ... form = ObjectForm(instance = obj) ... The select widget which renders doesn't have an initial value. If I delete the definition for 'object' in the form definition and let it render with the default text input, everything works as expected and I can see the correct value, the same as I can see in the Django … -
Remote desktop as a website host (VPN access only)
Networking is not a strong skill of mine and I'm currently working on making an internal website for my company and I don't want to make this website available publicly. Basically, we have a remote desktop that we can solely access via VPN and I wonder if it's possible to make that remote desktop as the website host so that no one can access the website except for the ones who are in the VPN? I'll be building the site via Django and python and any guidance would be much appreciated. -
stylesheet only rending for my 'core' app, and not for the rest of my apps in the same directory
For some reason, my stylesheet isn't loading for my other apps. . When I GET http://127.0.0.1:8000/static/style.css, it returns .container { width: 50vw; margin: 50px auto; padding: 25px 10px; background-color: #ffffff; border-radius: 3px; text-align: center; box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0, 0, 0, 0.22); } I loaded this for all my templates: {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> This loads fine for all my templates in website (this was the first app i created, not sure if that changes anything) When I try to do this for my other apps (chat/friend/accounts) it doesn't apply at all. Does anyone know why this is happening? I don't get any console error for the stylesheet on my other pages.. settings.py: # static STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Referencing more than one field on a Django Model
I am trying to reference 2 fields from a particular django model but it keeps giving me error. The models are displayed below, i want to reference 'building_type' and 'location' from property table to client table class Property(models.Model): location = models.CharField(choices=Property_Location, max_length=120) building_type= models.CharField(choices=Property_Type, max_length=120) initial_quantity= models.IntegerField(null= False, blank= False) quantity_in_stock= models.IntegerField( null= False, blank= False) quantity_sold = models.IntegerField( null= False, blank= False) def __str__(self): return self.location class Client(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.IntegerField() email = models.EmailField(max_length=130) building_type= models.ForeignKey(Property,null= False, blank= False, on_delete=models.CASCADE) location= models.ForeignKey(Property, null= False, blank= False, on_delete=models.CASCADE) def __str__(self): return self.first_name + ' '+ self.last_name -
virtual env in django
While I was trying to execute the mkvirtualenv command on the command prompt, I was getting this error: 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file python 3.10 windows 11 Expecting to create a virtual env -
(fields.E300) Field defines a relation with mode which is either not installed, or is abstract. many to many Model
I have the error message "recipes.Recipe.categories: (fields.E300) Field defines a relation with model 'Catego ry', which is either not installed or is abstract. "I am at a complete loss, even though in my eyes I did everything by the book. Nor am I really any the wiser after analysing my code. The Model Recipe from backend.apps.categories.models import Category class Recipe(models.Model): title = models.CharField( db_index=True, max_length=256, unique=False, null=False, verbose_name=_("Titel") ) lang = models.ForeignKey(Language, on_delete=models.RESTRICT, verbose_name=_("Sprache")) categories = models.ManyToManyField(Category, default=None) settings.py - INSTALLED_APPS "backend.apps.categories", "backend.apps.cookbooks", "backend.apps.cookparty", "backend.apps.customer", "backend.apps.dashboard", "backend.apps.hints", "backend.apps.home", "backend.apps.lexicon", "backend.apps.masterdata", "backend.apps.seo", "backend.apps.service", "backend.apps.user", "backend.apps.recipes", "backend.apps.importer", The Model Category class Category(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey( to="Category", on_delete=models.SET_NULL, default=None, null=True, blank=True ) is_active = models.BooleanField(default=False) slug = models.SlugField(default=None, blank=True, unique=True) In the debug, all apps are listed under 'INSTALLED_APPS'. For me, the error is completely irrational. Does anyone have a tip for me as to which screw I need to turn? -
Django - No such column: rowid when migrating Spatialite database
I am trying to create a database using GeoDjango, but when I try to migrate the database I get "error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid". I have added the right database engine and included 'django.contrib.gis', in settings.py. Any ide what the problem might be? from django.contrib.gis.db import models # Create your models here. class Bus(models.Model): busID = models.IntegerField(primary_key=True) route = models.CharField(max_length=20) operator = models.SmallIntegerField() latitude = models.DecimalField( max_digits=8, decimal_places=6) longitude = models.DecimalField( max_digits=8, decimal_places=6) location = models.PointField(srid=4326, blank=True, null=True) updated = models.DateTimeField(blank=True, null=True) lastStop = models.IntegerField(blank=True, null=True) def __str__(self): return self.busID settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': BASE_DIR / 'db.sqlite3', } } Error: python3 ./manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: Applying admin.0002_logentry_remove_auto_add...Traceback (most recent call last): File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 22, in <module> main() File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
Display Username when request is set declined
class PendingRequest(models.Model): book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True) approved = models.BooleanField(default=False, verbose_name="Approved") declined = models.BooleanField(default=False, verbose_name="Declined") request_date = models.DateTimeField(auto_now_add=True) approval_date = models.DateTimeField(auto_now=True, null=True) I have a view function that loop through this above model and displays the status of every request in database and renders it out in a table in template. Whenever the request is approved, it displays True and whenever it is declined, it display False. The problem i am facing is that whenever all the request for a user is set to False, it doesn't display the username of the user in member datacell of the table Here is the template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <table border="1"> <thead> <tr> <th>Member</th> <th>Book</th> <th>Request Date</th> <th>Approval Date</th> <th>Status</th> </tr> </thead> <tbody> {% for username, requests in user_requests.items %} {% with num_requests_approved=requests.approved_requests|length num_requests_declined=requests.declined_requests|length %} {% for request in requests.approved_requests %} <tr> {% if forloop.first %} <td rowspan="{{ num_requests_approved|add:num_requests_declined }}"> {{ username }} </td> {% endif %} <td><a href="{{request.book.book.url}}">{{ request.book }}</a></td> <td>{{ request.request_date }}</td> <td>{{ request.approval_date }}</td> <td>{{ request.approved }}</td> </tr> {% endfor %} … -
ResourceWarning: unclosed file <_io.BufferedReader name=
I have used with open but no luck but I still get this error : ResourceWarning: unclosed file <_io.BufferedReader name='/home/idris/Documents/workspace/captiq/captiq/static/docs/CAPTIQ Datenschutzhinweise.pdf'> attachment=customer_profile.get_attachments(), ResourceWarning: Enable tracemalloc to get the object allocation traceback below is my function which the error points to : def get_attachments(self): files = None cp = ( self.cooperation_partner.get_cooperation_partner() if self.cooperation_partner else None) # TODO: improve implementation: too many conditions if cp and cp.custom_attachments.exists(): files = [f.attachment for f in cp.custom_attachments.all()] elif cp and cp.pool.default_b2b_attachments.exists(): files = [ f.attachment for f in cp.pool.default_b2b_attachments.all()] else: files = self.get_default_attachments() if not files: path_one = finders.find( 'docs/file_1.pdf') path_two = finders.find('docs/file_2.pdf') with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments So the issue is here with this section : with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments -
pipenv install fails in Django project
i have a django project and when i tried to run python manage.py migrate i git this error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. and i knew i had to run pipenv install so here is my pipfile and below the error ocures when i try to run pipenv install Note : I tried to open pipenv shell first then install and it didnt work pipfile-> [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django-admin = "*" django = "*" djangorestframework = "*" djangorestframework-simplejwt = "*" drf-yasg = "*" django-cors-headers = "*" django-multiupload = "*" twilio = "*" django-redis = "*" psycopg2-binary = "*" python-dotenv = "*" dj-database-url = "*" django-storages = "*" boto3 = "*" gunicorn = "*" pillow = "*" django-filter = "*" ipdata = "*" pip = "*" install = "*" [dev-packages] black = "*" [requires] python_version = "3.11"` and here is the error I get when i run pipenv install `Loading .env environment variables... Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 … -
Migrate Custom Field Renderer from Django 1.8 to Django 3.2
I am trying to migrate a custom field renderer in a Django 1.8 form to Django 3.2. The form looks like this: class SomeEditForm(forms.ModelForm): job_uuid=forms.CharField(widget=forms.HiddenInput()) class Meta: model=Job fields=('status',) widgets={'status': forms.RadioSelect(renderer=BSRadioFieldRenderer)} So as it seems there is no Rendermixin anymore which accepts a renderer in its def init(). I have read the new source code and see that RadioSelect is now a subclass of ChoiceWidget. I cant get my head around to inject my old renderer into the new structure. Can someone please point me into the right direction? Thanks for your help! :) -
How to auth users with JWT in django microservice-like project?
I already have JWT from external auth service and want to use it in my django (DRF actually) project, I also want to populate user model basing on this jwt. How can I implement this? most of libs are about django as auth service, not just client -
Django Rest Framework api: bulk_create assigning a str to the primary key and a number to my str field
I'm creating a basic Pokemon API for practise purposes, where my models include: Card, Expansion and Type (fire, water, bug, ice, etc.) I'm trying to run a script to populate the "Type" database table but I get weird results, where the type name field actually seems to contain the primary key value and the ID field contains the actual name, when it should be the other way around. When I use Type.objects.all() to print the table contents (I set __repr__ to print the primary key (ID) and the name only) I can see this: <QuerySet [Type( ID: Normal; NAME: 1), Type( ID: Fighting; NAME: 2), Type( ID: Flying; NAME: 3), Type( ID: Poison; NAME: 4), Type( ID: Ground; NAME: 5), Type( ID: Rock; NAME: 6), Type( ID: Bug; NAME: 7), Type( ID: Ghost; NAME: 8), Type( ID: Steel; NAME: 9), Type( ID: Fire; NAME: 10), Type( ID: Water; NAME: 11), Type( ID: Grass; NAME: 12), Type( ID: Electric; NAME: 13), Type( ID: Psychic; NAME: 14), Type( ID: Ice; NAME: 15), Type( ID: Dragon; NAME: 16), Type( ID: Dark; NAME: 17), Type( ID: Fairy; NAME: 18)]> Also, when trying to run Type.objects.all().delete() to clear the table records, I get "ValueError: Field … -
Submit form with only two clicks on Submit Django
I created a page with questions to the phone, I need that when, when a person clicks on the submit form, he must submit the form with one click, and change the same form with one click too. But for now, it can be done with just two mouse clicks. my models.py: class Items_buy(models.Model): class Meta: db_table = 'items_buy' verbose_name = 'Телефон который покупаем' verbose_name_plural = 'Телефоны которые покупаем' image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона') model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ') text = models.TextField(max_length=500, verbose_name='Текст') max_prise = models.FloatField(verbose_name='Максимальная цена telefoha') image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy') def __str__(self): return self.model_produkt class Question(models.Model): class Meta: db_table = 'question' verbose_name = 'Вопрос к телефону' verbose_name_plural = 'Вопросы к телефону' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) titles= models.CharField(max_length=150,verbose_name='Заголовок вопросa') question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text') #max_prise_qustion = models.FloatField(verbose_name='Максимальная цена') def __str__(self): return self.titles class Choice(models.Model): class Meta: db_table = 'choice' verbose_name = 'Выбор ответа' verbose_name_plural = 'Выбор ответов' question = models.ForeignKey(Question, on_delete=models.RESTRICT,related_name="options") title = models.CharField(max_length=1000, verbose_name='Заголовок выбора') price_question = models.FloatField(verbose_name='Цена ответа') #lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа') def __str__(self): return str(self.price_question) class Answer(models.Model): class Meta: db_table = 'answer' verbose_name = 'Ответ на вопрос' verbose_name_plural = 'Ответы на вопросы' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) question = …