Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a Django model field that refers to another field in the same model?
I have a model called booking with two foreignkeys: artists and venues. Artist can request to book venues but venues can also request to book artists. I want to save in the model who tries to book who. How would I go about doing this? class Booking(models.Model): name = models.CharField(max_length=100) #relationships artist = models.ForeignKey(Artist, related_name="events", on_delete=models.CASCADE) venue = models.ForeignKey(Venue, related_name="events", on_delete=models.CASCADE) requester = # Either artist or venue (preferablly pointing to the object) How do I write this? I thought about creating another foreignkey, but that would have to be conditional as it could be either artist or venue. And that would lead to duplication in the database. I also thought about creating a simple boolean "booked_by_artist", but that would not point to which artist. Any help is appreciated! -
environment variables doen't work in django
I tried to connect to postgres in django. My env variables: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv("NAME"), 'USER': os.getenv("USER"), 'PASSWORD': os.getenv("PASSWORD"), 'HOST': os.getenv("HOST"), 'PORT': os.getenv("PORT"), }, } But I got this error: File "/home/ghost/full_stack_projects/e-commerce/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) " to address: Name or service not known not translate host name "localhost Here one of my env variables: export HOST="localhost" If i paste data directly, it works -
Is there any way to suggest to user's browser, where to start browsing for an upload ( FileField, <input type="file" ...> )
I have a Filefield, which is exposed to the user via a Modelform and which displays a Browse... (no file selected) button. I can click it, browse to a file and upload it. One anoyance is how browsers initialize the file selection window when one clicks "Browse". Firefox offers the folder from which the last file was uploaded. Chrome offers a list of recent uploads. Both are far from ideal. "Filesystem" or "Computer" would be better, but I can compute a better suggested path for typical workflow from inside Django. Is there anything I have missed whereby I can suggest to the browser what folder it should open in the first instance? JavaScript? Or is it simply not controllable from server-side? (It's an intranet application, so the app has a much better idea of a user's typical / expected filestore, than something exposed to anyone on the net). -
Form input calls file from database for manipulation in django
I am trying to to have a option menu or input field which takes input using a POST request then the python calls a database entry of the same name. I am having issues getting the data back to the Django application. The Output doesn't show in my VS code terminal or the browser console. in my views.py file from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Navbar, Hero from django.http import JsonResponse from core.forms import BuildForm def index(request): if request.method == 'POST': form = BuildForm(request.POST) if form.is_valid(): nav = form.cleaned_data['Nav'] hero = form.cleaned_data['Hero'] my_object = get_object_or_404(Navbar, id=nav) my_object2 = get_object_or_404(Hero, id=hero) return render(request, 'core/index.html', {'my_object': my_object}) else: form = BuildForm() return render(request, 'core/index.html', {'form': form}) my forms.py file from django import forms class BuildForm(forms.Form): Nav = forms.CharField(max_length=100) Hero = forms.CharField(max_length=100) Index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"></link> <title>Atom | {% block title %} {% endblock %} </title> </head> <body> {% block content %} {% endblock %} <script src="{% static 'js/form.js' %}"></script> </body> base.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' … -
Is it possible to do arithmetic in a template conditional?
Basically I'd like to do this but the syntax is not valid. {% if index in widget.row_starts %} <div class="row"> {% elif index+1 in widget.row_starts %} </div> {% endif %} I tried using index|add:1 but I think that is actually incrementing the value permanently... -
.all() on ManyToMany field in Django returns empty QuerySet
I have a model "CustomUserGroup" which has a ManyToMany field with Django's User object passed: class CustomUserGroup(models.Model): custom_group_name = models.CharField(max_length=50,unique=True) users= models.ManyToManyField(User) class Meta: verbose_name_plural = 'Custom Groups' ordering = ['custom_group_name'] def __unicode__(self): return self.custom_group_name def __repr__(self): return self.custom_group_name def __str__(self): return self.custom_group_name Here is the corresponding form: ... from ajax_select.fields import AutoCompleteSelectMultipleField class GroupForm(forms.ModelForm): class Meta: model = CustomUserGroup fields = ['custom_group_name','users',] users = AutoCompleteSelectMultipleField('users', required=True, help_text=None) I wanted all users to be able ot create a new CustomUserGroup object: def index(request): groups = CustomUserGroup.objects.all() if request.method == 'POST': form = GroupForm(request.POST) if form.is_valid(): new_group = form.save(commit=False) new_group.save() return render(request, 'chat/new_group_created.html', {'group_name': new_group.custom_group_name}) else: return HttpResponse('A group with such name already exists. Please return and change the group name.') else: form = GroupForm() return render(request, 'chat/index.html', {'form': form, 'groups': groups}) My problem is that I think I haven't configured this field correctly, because every time I run the "room" view in my views.py, I get HttpResponse('You shall not pass'), no matter which users have been added to the group before. def is_member(user,group): # a function to check some of the parameters print(user) print(group) print(group.users.all()) return user in group.users.all() # and return T/F based on whether the current user is … -
Pass Info from next template if I click in on item of my catalog
Im doing a web app, where I have a catalog of products, and I want when I click in one of this items the next template have info about the Item was I clicked (product name, img and news for this item) but idk how to do without doing a template for each product in my db I hope u can help me ITS MY FIRST POST IN STACK-OVERFLOW, SORRY IF I MISSED AN ESSENTIAL INFO My models.py class products_menu(models.Model): name = models.CharField(max_length=30) img = models.ImageField(upload_to= '', default="../media/digi_flex.png" ) slug = models.SlugField() mfq = models.CharField(db_column='MFQ', max_length=30, choices=ENGEENER_CHOICES, blank=True) parent = models.ForeignKey('self', blank=True, null=True,on_delete=models.CASCADE, related_name='children') My views.py def catalog(request): prods = products_menu.objects.all().order_by('mfq') return render(request, 'home.html', {'prods':prods}) And part my home.html where I show my dump of items home.html <div class="container-fluid tm-container-content tm-mt-60"> <div class="row mb-4"> <h1 class="col-6 tm-text-primary" align="center"> Productos </h1> </div> <div class="row"> {% for products_menu in prods %} <div class="col-sm-2"> <div class="panel panel-turquoise"> <div class="panel-heading"> <h3 class="panel-title" align="center">{{products_menu.name}}</h3> </div> <a href="{% url 'fail' %}"> <img src="{{products_menu.img.url}}" width="280" height="200" ></a> <span class="tm-text-gray-light" align="">Ing.{{products_menu.mfq}}</span> </div> </div> {% endfor %} </div> I want to if I click in one product img, redirect to 'fail' template with info about the item I clicked -
Django database connection error while saving data or updating it
This is my Model class CompanyIdentifier(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) identifier_type = models.CharField(max_length=20) identifier = models.CharField(max_length=20) company = models.ForeignKey( Company, on_delete=models.PROTECT) date_updated = models.DateTimeField(auto_now=True) class Meta: indexes = [models.Index(fields=['identifier', 'company'])] whenever i call .save() or .create() on this Model i get this error ConnectionError(<urllib3.connection.HTTPConnection object at 0x00000258D3D2C6A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x00000258D3D2C6A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed) i can extract data using .get() or .filter() from this model easily there is no issue in that but only if i try to create or update a row it throws an error this is my Database setting , i'm using postgres DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'root1234', 'HOST': 'LOCALHOST', 'PORT': 5432 } } i have other models as well in the same file where this model is saved , they dont give any issue on using .create() on .save() method I tried to change the 'LOCALHOST' in database setting to '127.0.0.1' but it didnt work -
Django: is it possible to login a user with sessions? [closed]
I'm creating a unique login and a client app and im curious about sessions. When a user uses the login, we return him to the app where he's coming from with his personal info. The question is: is it possible to create a session and login the user in the client app as well with the information that came from de login? Having in mind that we don't have the password because is hash when he created his account. I just reed about it but i didnt found anything about if its possible to do it or not. -
How can I return a custom response for non-existent endpoints?
how can I return JSON response for queries to non-existent endpoints? For example: query to /api/rock?q=123, but the api have /api/paper only, and then the server return {'error': 'endpoint not found'} or something. I'm using Django Rest Framework 3.14.0, Django 4.1.7, help please. I checked exception_handler in views.py, but how can I return a custom response for non-existent endpoints? I've read the documentation, but I can't get this done. Returns the default response for Django resources not found. -
Django KeyError while integrating with Neo4J
I am trying to integrate Django with Neo4J. To save the node I will provide the form and will add the node in the graph in the graph. For creating model I am using neomodel's StructNode. models.py from neomodel import (StructuredNode, StringProperty, IntegerProperty, RelationshipTo, OneOrMore) class Male(StructuredNode): print('Class for male nodes') name = StringProperty(unique_index=True, required=True) surname = StringProperty() age = IntegerProperty() country = StringProperty(default='India') class Female(StructuredNode): print('Class for female nodes') name = StringProperty(unique_index=True, required=True) surname = StringProperty() age = IntegerProperty() country = StringProperty(default='US') ratings = RelationshipTo('Movie', 'HAS_RATED', OneOrMore) class Movie(StructuredNode): print('Class for movie nodes') movieName = StringProperty(unique_index=True, required=True) forms.py from django import forms from .models import Male class MaleForm(forms.ModelForm): class Meta: model = Male fields = '__all__' views.py from django.shortcuts import render from .forms import MaleForm def index(request): form = MaleForm() if request.method == 'POST': print(request) # context = {'form':form} return render(request, 'crud/index.html', {'form':form}) index.html <h3>Customer Form</h3> <hr> <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit"> </form> After running the application I am getting below error. F:\django\graph_project> python manage.py runserver Class for male nodes Class for female nodes Class for movie nodes Class for male nodes Class for female nodes Class for movie nodes Watching for file changes with … -
Local server is not running on python
I'm trying to run a local python server with Django, but all I see is thisenter image description here I did not find a solution to this problem on the Internet -
Making a character selector using bootsrap carousel and django forms
I am trying to create a character selector screen for a web game and want to have a carousel-style character selector. I am using Django as the backend and am currently using a bootstrap carousel to display all the character types. Is there any way to find the currently active carousel item so that I can pass it to the Django form as input? I currently have a dropdown input field petType which I was planning to hide which will take the input from the carousel. Thanks in advance <form method="post" id="login"> {% csrf_token %} {{ form.as_p }} <div id="myCarousel" class="carousel slide" data-interval="false"> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="{% static 'Images/hedge-hog-normal.png' %}" alt="Hedgehog Zumi" width="50%"> </div> <div class="item"> <img src="{% static 'Images/badger-normal.png' %}" alt="Badger Zumi" width="50%"> </div> <div class="item"> <img src="{% static 'Images/frog-normal.png' %}" alt="Frog Zumi" width="50%"> </div> <div class="item"> <img src="{% static 'Images/bat-normal.png' %}" alt="Bat's Zumi" width="50%"> </div> <div class="item"> <img src="{% static 'Images/weasel-normal.png' %}" alt="Weasel Zumi" width="50%"> </div> <div class="item"> <img src="{% static 'Images/rabbit-normal.png' %}" alt="Rabbit Zumi" width="50%"> </div> </div> <div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> <!--Code along the lines of: … -
React + Django Azure application security
My goal is to deploy to the Azure, cloud application that conists of React frontend and Django backend. I would like my frontend to be publicly accessible, but available only behind some authentication mechanism (I found password protection in Static Web Apps in Azure), maybe Microsoft SSO. My Django API should not be accessible publicy (I want my frontend to the be only source of REST queries). I have created React as Static Web App and Django as Web App, but I did not manage to find a way to exclusively connect them together. I have tried backend to be secured with Microsoft SSO, but as I assume, it requires additional changes in fronted (with authentication). My question is: what is the proper solution to deploy such application (maybe it should be just deployed as one virtual machine)? Should I use any other resource types? Thanks in advance! -
Change order of countries depending on user language
I have a Django app which django-countries. I would like to alter the order of the countries shown based on the user's language. For example if the user is using French, I will bring France, Belgium, Luxumburg, Switzerland etc to the top, whereas if they select German I will bring up Germany, Austria, Switzerland etc. I can set COUNTRIES_FIRST = ['FR','BE','LU','CH'] within settings, but that ordering is then used for all user languages. Is there a way to base the order on the user's language? I have tried modifying the COUNTRIES_FIRST within a view, for example if self.administration_instance.study.instrument.language == 'French': settings.COUNTRIES_FIRST = ['FR','CH','BE','LU'] translation.activate(self.user_language) But this clearly doesn't work -
Send a message in while loop in Django Channels
hi i want to send a message like real-time report. reports make from Django model instances. i want to show this data in real-time using Django-Channels. so i start research about best way to do this. after a little a found Django-Channel. i make a sample chat app using it. but now i want to send data in loop but when i tried it app crashed. while True: self.send(text_data=json.dumps(data)) time.sleep(1) how can i do this? please help me about that -
Django Serializer - Support Multiple Field Types
I want my serializer to support multiple types of serialized lists. For example, in the BundleSerializer below, I want the identifier to support two or more types of identifiers, that can be a list of IdentifierSerializer objects. class BundleModel(models.Model): fullUrl = FHIR_DATATYPE_URI() # IdentifierSerializerA and IdentifierSerializerB has two different models and corresponding serializers class BundleSerializer(serializers.ModelSerializer): identifier = IdentifierSerializerA(many=True, required=False) || IdentifierSerializerB(many=True, required=False) class Meta: model = BundleModel fields = "__all__" How can I make this work? Also, the identifier property can host a list of both type of objects from IdentifierSerializerA and IdentifierSerializerB. -
How to remove "limit_choices_to={'offer_type': "Voucher"}" from my oscar models?
I try to remove from oscar core apps but when i try to do migrations it is showing no changes detected i just want to show all "offer_types" to the user offers = models.ManyToManyField( 'offer.ConditionalOffer', related_name='vouchers', verbose_name=_("Offers")) -
When im sending email with multiple attachments via smtplib in django. Only the last one can be opened
Im creating django app which sends uploaded files to other users of the app. But only the last file which is attached to the email is readable, rest is corrupted and I don't know why. Here is the code which I'm using to create email and add the attachments. When it is only one file everything works perfectly. attachments = request.FILES msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = EMAIL_ADDRESS msg['To'] = ', '.join(recipients) msg.attach(MIMEText(body,"html")) if len(attachments.getlist('attachment')) != 0: for attachment in attachments.getlist('attachment'): attach_file = attachment.file payload = MIMEBase('application', attachment.content_type) payload.set_payload(attach_file.read()) encoders.encode_base64(payload) payload.add_header('content-disposition', 'attachment',filename=attachment.name) msg.attach(payload) smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465) smtp_server.login(EMAIL_ADDRESS, PASSWORD) smtp_server.sendmail(EMAIL_ADDRESS, recipients, msg.as_string()) smtp_server.quit() I also tried django class EmailMessage, but the result was completely same. -
Django calculating field depending on selection with manytomany field
I am writing a web application using django rest. I have a problem that i am struggling with for a few days now. So i created a payroll model that calculates the gross value based on the number of hours worked and hourly rate by the employee and its working perfectly. The main problem is that i want to calculate net value based on taxes and fixed costs (which are seperated models) choosen by user. Actually i made function that use post_save signal and it works, but i have to save object twice to calculate it correctly because if i save for the first time it sees old selections (i think its happening because function is called too fast and there is no time to create a relation between models).Earlier i used the function with m2mchanged signal, but there was a lot of code and if statements besides it didnt work well. Models: PERCENTAGE_VALIDATOR = [MinValueValidator(0), MaxValueValidator(100)] class Taxes(models.Model): tax_name = models.CharField(max_length=100) tax_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=PERCENTAGE_VALIDATOR) class Meta: verbose_name = 'Tax' verbose_name_plural = 'Taxes' def __str__(self): return f'{self.tax_name} - {self.tax_percentage}%' class FixedCosts(models.Model): name = models.CharField(max_length=100) value = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Meta: verbose_name = 'Fixed Cost' verbose_name_plural = … -
how to show each image when clicked and show them in a modal
What I am looking for is that the user, when clicking on any image, opens a modal with that same image in a large size. What I have achieved so far is that only the first image is displayed, because clicking on the others does not interact with anything. image gallery only image that is activated this image is from image gallery code in django gallery code This image is of the modal code that is displayed when clicking on an image modal image zoom and this image is of the js code modal image zoom js From now on, sorry for my bad English. I hope you can understand me and help if you can, thank you! -
Is there any kind of documentation updated to these last years on the integration of django with keycloak?
I'm starting to develop with django and I would like to manage authentication with keycloak to be able to authenticate emails from different domains, but the documentation I find is not compatible with DJANGO 4..1... Has anyone currently worked with django and keycloak? I need to know how to configure it to be able to connect my keycloak server (located in a docker) with my django application -
django apache2 [wsgi:error] internal server error 500
I've been stuck in this django apache deployment. When I try to access some pages my website keeps showing this 500 Internal Server error. and Some pages work well i found this in error.log your text [Wed Feb 22 09:01:49.177572 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] [Wed Feb 22 09:01:49.177576 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] During handling of the above exception, another exception occurred: [Wed Feb 22 09:01:49.177580 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] [Wed Feb 22 09:01:49.177586 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] Traceback (most recent call last): [Wed Feb 22 09:01:49.177602 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] File "/var/www/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 1027, in find_library [Wed Feb 22 09:01:49.177606 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] return parser.libraries[name] [Wed Feb 22 09:01:49.177617 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] KeyError: "'static'" [Wed Feb 22 09:01:49.177624 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] [Wed Feb 22 09:01:49.177627 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] During handling of the above exception, another exception occurred: [Wed Feb 22 09:01:49.177631 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] [Wed Feb 22 09:01:49.177636 2023] [wsgi:error] [pid 99825:tid 140583099365056] [remote 152.89.196.211:60712] Traceback (most recent call last): [Wed Feb 22 09:01:49.177715 2023] … -
Django MySql not writing to the database
I am working on a Django project that records bets placed by lotto vendors from mobile phone devices. The environment is: Ubuntu 20.04, Django==4.0.8, MySql Ver 8.0.32, Python 3.8.10. The transactions are mostly placing bets, but can also be cancelling bets, refunding bets (very rarely) or pay-out of bets. Detail record keeping is essential to ensure an accurate cash-up for each vendor. The transaction volume is remarkably high (plus minus two million bets per day) and during peak times, the number of bets per second is around two hundred per second. It is a regular requirement to get the summary information for a specific vendor (or group of vendors). Since the bet information table grows rapidly, it becomes time consuming to obtain this information. Hence, we keep daily summarised information for each vendor. I refer to it as 'Fingertip data'. So, every time a bet is placed, a row is created in the bet info table. immediately thereafter a Fingertip row is either created or updated to accumulate the transaction amount and the number of the specific transaction, for the vendor, for the financial day and from the device from which the bet was placed. This happens in the same … -
Using jquery POST request to save form in django
here my form.html in this form I'm use Django model form. <div class="container"> <form action="{% url 'add_product' %}" id="product_form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-sm-12"> <label for="">{{form.code.label}} :</label> {{form.code}} <span id="error">{{form.code.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.company_id.label}} :</label> {{form.company_id}} <span id="error">{{form.company_id.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.item_id.label}} :</label> {{form.item_id}} <span id="error">{{form.item_id.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.name.label}} :</label> {{form.name}} <span id="error">{{form.name.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.price.label}} :</label> {{form.price}} <span id="error">{{form.price.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.pro_image.label}}</label> {{form.pro_image}} <p style="color:red">{{form.pro_image.help_text}}</p> <span id="error">{{form.pro_image.errors | striptags }}</span> </div> <div class="col-sm-12"> <label for="">{{form.desc.label}}</label> {{form.media}} {{form.desc}} <span id="error">{{form.desc.errors | striptags }}</span> </div> </div> <div class="row"> <div class="col-sm-12"> <label for="">{{form.status.label}}</label> {{form.status}} <span id="error">{{form.status.errors | striptags }}</span> </div> </div> <div class="row"> <div class="col-sm-4 mt-2 mb-2"> <button type="submit" class="btn btn-success"> <i class="{{btn_type}}"></i> </button> <a href="{% url 'product' %}"> <button type="button" class="btn btn-primary"><i class="fa fa-long-arrow-alt-left"></i></button> </a> </div> </div> </form> {% if img_object %} <img src="{{ img_object.pro_image.url}}" alt="connect" style="max-height:300px"> {% endif %} </div> **jQuery code I can't find the error because browser status=200 but when I'm check the Django terminal it's showing error. jQuery serialize Django support or not ?? ** var frm = $('#product_form'); frm.submit(function(){ …