Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
.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(){ … -
httpx.ConnectError: [Errno 111] Connection refused
I'm trying to generate api client from my custom api with this package I have generated the api client: openapi-python-client generate --path example_api_client.yaml Built the package with: cd example_api_client/ poetry build -f wheel Copied and installed: pip install ./example_api_client-1.0.0-py3-none-any.whl But when i try to do a request throw the error: httpx.ConnectError: [Errno 111] Connection refused The script is Django custom command: from example_api_client.api.authentication import authentication_user_list from example_api_client.models.user import User from example_api_client.client import Client class Command(BaseCommand): def handle(self, *args, **kwargs): BASE_URL = 'http://0.0.0.0:8002' client = Client(base_url=BASE_URL, verify_ssl=False, raise_on_unexpected_status=True) response: User = authentication_user_list.sync(client=client) Anybody could help me please ? Thanks in advance. -
Python Django Rest Framework serializer to representation, can I return list of Ordered dicts into one dict, ex., return data in one curly brackets?
I have a task where I need to combine the data of multiple serializers into one level and return all the data in one json array. The problem I encountered is that the data keys are the same but values change so I am stuck in how to remove the curly brackets, but don't change the data. For example my code looks like: serializers.py class OneSerializer(serializers.ModelSerializer): spec = DifferentSerializer(many=True) service = Different2Serializer(many=True) class Meta: model = models.SomeModel def to_representation(self, instance): data = super(OneSerializer, self).to_representation(instance) for s in data['spec']: s.update({"form": instance.form}) s.move_to_end('form', last=False) for s in data['spec']: s.update({"appointment": instance.appointment}) s.move_to_end('appointment', last=False) for s in data['spec']: s.update({"d_appointment": instance.d_appointment}) s.move_to_end('d_appointment', last=False) for s in data['spec']: s['service'] = data['service'] data.pop('service') specialist = data.pop('spec') return specialist I have removed most of code but the principle is I combine data of other serializers into one and using data.pop, I get the data in one level. The return looks like this: [ { "form": null, "appointment": false, "d_appointment": false, "service": [] } ], [ { "form": null, "appointment": false, "d_appointment": true, "service": [] } ], [ { "form": null, "appointment": true, "d_appointment": false, "service": [] } ], Which returns data correctly except for the fact that each … -
Django & JQuery: Submit button is not working after JQuery replaceWith a html file
I have a formset where users can save the data in forms 1 at a time, with an overall Submit button at the bottom, which is disabled. When all forms within the formset are saved, I want to make the overall Submit button not disabled. Each form save button sends an AJAX request, which replaces some of my HTML divs, including one with the button. The replace works, the button is updated and not disabled, however it does not work. I have also tried using jquery html instead of replaceWith but it results in the same thing Here's my code: formset.html {% for form in formset %} <thead> <th>Header 1</th> <th>Header 2</th> </thead> <tr> <td>{{form.instance}}</td> <td> <div class='btn-group mr-1 mb-1'> <button id='{{ form.instance.id }}-save-button' action="{% url 'results:save_variant_class' %}" type='button' class="btn btn-warning save-variant-classification" value='Save' </div> </td> </tr> {% endfor %} </table> {% include "analyse_sample_button.html" %} analyse_sample_button.html {% if stuff_to_do %} <button type="submit" name="submit" value="Analyse sample" class="btn btn-danger float-right" disabled>There are forms to for this sample</button> {% else %} <button type="submit" name="submit" value="Analyse sample" class="btn btn-success float-right">Analyse sample</button> {% endif %} views.py def save_variant_class(request, **kwargs): data = dict() if request.method == 'POST' and request.is_ajax(): obj = MyModel.objects.get(id=request.POST['id']) form = VCForm(data=request.POST, instance=obj) if … -
How do I delete the django cache database table?
I have been using django's database caching as shown here: https://docs.djangoproject.com/en/4.1/topics/cache/#database-caching Recently I have migrated to redis caching, but I still have the cache table in my database from the command python manage.py createcachetable. How can I safely delete this table? -
How to ,centralize deselect search box in django crispy form
I created a searchable dropdown box in django with crispy forms using dselect() like so: form.html {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1 class="mt-2">Form for Update</h1> <hr class="mt-0 mb-4"> <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form |crispy}} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> <script> dselect(document.querySelector('#id_app'), { search: true }); </script> {% endblock %} But the problem is that the resulting searchbox is not centralized, the searchbox comes to the lower left corner. It ends up like so: And I want something more like this: Does anyone know how to change that ?