Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy flutter web with Django?
when I build flutter web app : flutter build web I want to deploy this with dango server, what should i do? thanks !! -
Django FileResponse through nginx error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
django use FileResponse and runserver in 8000 port. # this add Content-Disposition header in response response = FileResponse(file, filename="file.txt", as_attachment=True) nginx proxy_pass to django: location /api/v1/download { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-Real_IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } when I access django directly, I download file successfully, but when I access django through nginx, chrome throw error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION. Use curl to send request to django directly: curl -v http://django:8000 < HTTP/1.1 200 OK < Server: WSGIServer/0.2 CPython/3.9.2 < Content-Type: application/octet-stream < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Connection: close Use curl to send request to nginx, it shows duplicate Content-Disposition response header: curl -v https://nginx < HTTP/1.1 200 OK < Server: nginx/1.20.1 < Date: Mon, 04 Oct 2021 16:39:01 GMT < Content-Type: application/octet-stream < Transfer-Encoding: chunked < Connection: keep-alive < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Content-Disposition: “attachment” # nginx add Why nginx auto Content-Disposition: "attachment" In response header? Is there some way to avoid this? -
How to do nested Group By with django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count the number of books published by each author in a single object. I want to get the following result: {publisher: New Age Books, titles: {Life Without Fear: 2, Sushi Anyone?: 1}}, {publisher: Binnet & Hardley, titles: {The Gourmet Microwave: 1, Silicon Valley: 1, Life Without Fear: 1}}, {publisher: Algodata Infosystems, titles: {But Is It User Friendly?: 3}} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result. -
multiple websocket instances for chat application
I'm building a Django-Vue chat applicaton, I already builded the core functionallity of the app. When the SideBar component is mounted a HTTP request is maded to get all rooms that the user is a participant, when some room is clicked a WebSocket instance is created on the Chat component. My doubt is, if I send a message to that room but the others users are not connected in the same room (suposse that they are connected in other room) they will not receive the message right? So how I send him a notification about the new message? like Whatsapp sidebar notifications. I was thinking in create two WebSocket connections, one on the SideBar that will be the user endpoint (ws:127.0.0.1:8000/chat/$Username) and other for the actually chat room (ws:127.0.0.1:8000/chat/$ChatId), is that a good approach? My django models => from django.db import models from account.models import CustomUser class Message(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='messages') message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'message from {self.sender.username}' class Chat(models.Model): name = models.CharField(max_length=24) participants = models.ManyToManyField(CustomUser, blank=True) messages = models.ManyToManyField(Message, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Can you break a for loop in django?r
{% if user.is_authenticated %} {% for robot in object_list %} {% if user.id == robot.username.id %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><a href="{% url 'robot-detail' robot.pk %}"><h1>{{ robot.name }} - Current Status: {{ robot.current_status }} - Current Path: {{ robot.path_options }}</a></li> </ul> </ul> <hr> </div> {% else %} <h1>You have no robots.</h1> {% endif %} {% endfor %} {% else %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><H1><a href="{% url 'login' %}"> Log in </a> to get started.</h1></li> </ul> <hr> </div> {% endif %} where it says you have no robots. it runs the the amount of robots there are in object_list, i was thinking that i could break the for loop right after the any suggestions? -
How to retrieve the ids from the array of objects using python and django?
Hi i have an array of objects like below, const arr_obj = [ { 'id': 1, 'items': [ { 'id':'1', 'data': { 'id': 3, } }, { 'id': '2', 'data': { 'id': 4, } } ] }, { 'id': 2, 'items': [ { 'id':'3', 'data': { 'id': 5, } }, ] }, ] I want to retrieve the id property of items array and put it an array so the expected output is ['1','2','3'] below code works in javascript arr_obj.map(obj=>obj.items.map(item=>item.id)).flat() how can i do the above in python and django. could someone help me with this. I am new to python and django thanks. -
django "Field 'id' expected a number but got 'yoavlv'."
I want to create a page where the user can see the details he posted on the site. The problem I get "Field 'id' expected a number but got 'yoavlv'." I already searched for solution and try to solve it with "slug" but it didn't work.. def my_items(request, user): user_items = get_object_or_404(Add_Item, user=user) items = Add_Item.objects.filter(user =user_items) return render(request, 'my_items.html',{"items":items,}) model : class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices=all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) header_img = models.ImageField(null=True, blank=True, upload_to='img/') more_img = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) -
Django admin form raises IntegrityError for model with conditional UniqueConstraint
I was asked to add some logic to model uniqueness. Each Payment must have either transaction_id or payment_id filled. Each Payment is identificated by (transaction_id, operation, payment_created_date) or (payment_id, operation, payment_created_date). On database level this works fine. Inserting Payment with same transaction_id, operation, payment_created_date twice causes unique constraint violation. For this model i created admin page. But inserting same row with admin page causes IntegrityError at /admin/finance/payment/add/ duplicate key value violates unique constraint "unique_finance_payment_without_payment_id" DETAIL: Key (transaction_id, operation, payment_created_date)=(dasdasd, Refund, 2021-10-04) already exists. instead of simple user-friendly admin error Please correct the error below. Payment with this Transaction id, Operation and Payment created date already exists. How to make Django admin catch this IntegrityError and show it in admin form? here is my models.py class ReportName(DiModel): name = CharField( max_length=50, blank=False, null=False) def __str__(self): return self.name class Payment(DiModel): class Meta: unique_together = ('transaction_id', 'payment_id', 'operation', 'payment_created_date') constraints=[UniqueConstraint(fields=['transaction_id', 'operation', 'payment_created_date'], condition=Q(payment_id=None), name='unique_finance_payment_without_payment_id'), UniqueConstraint(fields=['payment_id', 'operation', 'payment_created_date'], condition=Q(transaction_id=None), name='unique_finance_payment_without_transaction_id'),] OPERATION_TYPE = [ ('Refund', 'Refund'), ('Charge', 'Charge'), ] CURRENCY_CODE = [ ('EUR', 'EUR'), ('RUB', 'RUB'), ('USD', 'USD'), ('GBP', 'GBP'), ('AUD', 'AUD'), ('PLN', 'PLN'), ('SGD', 'SGD'), ('MYR', 'MYR'), ('RON', 'RON'), ('ZAR', 'ZAR'), ] report_name = ForeignKey(ReportName, on_delete=models.PROTECT, blank=False, null=False, help_text="Processor and report type") operation = … -
Django show image list in table from ManyToMany field
I have created a model to have details of job vacancy. The job model has the following fields: class Job(models.Model): job_position = models.ForeignKey(Position, on_delete=models.PROTECT, related_name='job_position') applicants_to_hire = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1), MaxValueValidator(15)], default=1) hiring_team = models.ManyToManyField(Employee, related_name='hiring_team') class JobListView(LoginRequiredMixin, ListView): model = Job template_name = 'recruitment/job_list.html' context_object_name = 'job_list' I want to use the hiring_team in a template to show image of each employee (circle avatar), and those images come from the employee model: class Employee(models.Model): image = models.ImageField(blank=True, default='blank_profile_picture.jpg') I've managed to display all images, but they are not in the same table cell, and they add additional table columns: <tbody> {% for job in job_list %} <tr> <td><span class="employee-table-name"><a href="{% url 'recruitment:job_detail' pk=job.pk %}">{{ job.job_position }}</a></span></td> <td>{{ job.applicants_to_hire }}</td> {% for team in job.hiring_team.all %} {% if team.image %} <td><img src="{{ team.image.url }}" class="rounded-circle img-fluid-80" alt="{{ team }}"></td> {% endif %} {% endfor %} <td>{{ job.job_priority }}</td> <td>{{ job.job_status }}</td> <td>{{ job.created|date:"M d, Y" }}</td> </tr> {% endfor %} </tbody> How can I "concatenate" them to display something like the screenshot below: -
Why am I getting TypeError string indices must be integers in this API call? (seeding Django DB)
I am trying to seed a django DB from an external API using this guide (https://medium.com/@chilinski.a/how-to-seed-a-django-api-with-data-from-an-external-api-b577b6e6ad54). I have replicated the code accurately for my own project, I think, but get a TypeError: string indices must be integers when i run python manage.py seed and am not sure why. Here's my code: import requests from django.core.management.base import BaseCommand from nrel_app.models import Nrel def get_nrel(): url = 'https://developer.nrel.gov/api/utility_rates/v3.json?api_key=DEMO_KEY&lat=35.45&lon=-82.98' r = requests.get(url, headers={'Content=Type': 'nrel_app/json'}) Nrels = r.json() return Nrels def seed_nrel(): for i in get_nrel(): Nrels = Nrel( utility_name = i['utility_name'], company_id = i['company_id'], utility_info =i['utility_info'], residential = i['residential'], commercial = i['commercial'], industrial = i['industrial'], ) Nrels.save() class Command(BaseCommand): def handle(self, *args, **options): seed_nrel() print("Completed.") -
Create new RT table in Django SphinxSearch
I have a django site running with sphinxsearch and am having trouble creating a new RT table. I have previously added columns to RT tables using the steps: sudo service sphinxsearch stop Delete the data in var/lib/sphinxsearch Add the field to sphinx.conf sudo service sphinxsearch start After that the new column appears in mysql, and I can confirm it by connection to the DB directly. However, I have now created a full new table, but when I run the same steps, the data file for the new table as well as the table itself are not being created. I have tried to manually go into Mysql to create the table but have had no luck. Most of the sphinx documentation is not RT table based and I'm having trouble finding how to create this... When I try to run a logdebug following, I receive an error saying that the "table_name.lock" file does not exist. The formatting can't be wrong because when it was I received errors simply running sudo sphinxsearch start...so am not sure where to go from here. Thank you! Additional detail: This new table is also part of a new django app, so the sphinx.py file in the … -
Connect ZKTECO device from hosted django Site gives an error
I have created a site that connect ZKTECO K40 device. The connection Method is pretty simple from zk import ZK, const zk = ZK('192.168.1.13', port=4370, timeout=5) conn = zk.connect() This makes a connection while running from a local host connecting in the same network But after hosting the site. The site is not able to ping to the device and can't connect the device. How can i connect to the device connected on pc local network from hosted django site. I have hosted my site on Cpanel. enter image description here -
Sending emails with EmailMessage does not work when I deploy my application
I am developing an application with django. When I send emails locally with EmailMessage it works, but after deployment on heroku it doesn't work anymore. Here is the code in views.py from django.template.loader import render_to_string message = render_to_string("elec_meter/activate_email.html", { "user": user, "domaine": request.META['HTTP_HOST'], "uid": urlsafe_base64_encode(force_bytes(user.id)), "token": default_token_generator.make_token(user), "password": password,"matricule": agent.matricule } ) email_to_send = EmailMessage("Activation du compte", message, to=[email]) email_to_send.send() in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "my_email" EMAIL_HOST_PASSWORD = "password" EMAIL_USE_SSL = False I need help please -
Saving previous date and adding new date in Django
I have been working on an application where user adds his tasks which he is supposed to perform, once the task is added he can update the progress. In my model I have a date field, where user is supposed to enter the estimated completion date. My task model """Creating KRA Based on Institutional Objectives""" class KraBasedOnIo(models.Model): io = models.ForeignKey(InstitutionalObjectives, on_delete=models.CASCADE, related_name='kra_io') kra_title = models.CharField(max_length = 200) kra_description = models.TextField() kra_target = models.CharField(max_length=200) kra_added_date = models.DateTimeField(auto_now_add=True) estimated_date = models.???? While updating the progress, if the user wants to extend his timeline, I am looking for an option where I can save his current estimated completion date and add the new date also. And when I am displaying his progress I want to show his defined completion date and also the extended completion date in the template. I have tried a work around with model.JSONField() but couldn't reach there. There is no ListField or DictionaryField so what could be a better solution for this? -
How can I Restrict Users on OTT Platform (Like 3 Stream/Account) [Device Limitation]
I'm working on a OTT Platform For API using Django Rest Framework & for Website React & for App React Native. I'm trying to add Device limitation on account like 3 user can watch at a same time per account. How can I do it? -
Django DetailView getting values of ManyToMany relationship
I want to get post tags with ManyToMany relationship, to display related posts with the same tags. The problem is that I don't know how to access the tags of the current post. model class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) # author = tags = models.ManyToManyField(Tag, related_name='post_tags') date_created = models.DateTimeField(auto_now_add=True) time_to_read = models.PositiveIntegerField(blank=True) text = models.TextField() image = models.ImageField(upload_to='photos/%Y/%m/%d') is_published = models.BooleanField(default=True) view class GetPost(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data() post_tags = Post.tags.all() incorrect #context['related'] = Post.objects.filter(tags__in=post_tags)[:3] am i need to override get_object?? or i can get it in context_data? ty -
Django admin: the most proper way to limit choices of dropdown window?
I am trying to customize dropdown for one of my models named Recipe. The problem is I do not want duplicates appear. Say, administrator selected choice X from the first dropdown, then he or she clicks on the second one but there are the same choices though. Because of it admin can create a recipe with two identical tags, for example, so I would want to deprecate this logic. -
Django Can you please explain my code why if statement not working?
I am using signals where I am using this logic for update user data. author = MyAuthors.objects.filter(user=instance) if not author and instance.is_blog_author and instance.email: MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author,first_name=instance) if I remove not from if statement then user data not updating. Can you please explain why user data not updating if I use if author and instance.is_blog_author and instance.email ? -
Sending Outcome of Javascript Calculations to Django Backend
I have an HTML form where users type in the name of items and value corresponding to it in an input form, which is reflected when the form is submitted to Django backend. In my HTML form I have included some Javascript so that the total of these values are reflected instantly without refreshing and even before submitting the form. My goal is to send the total amount reflected in the HTML to the related class Model after submitting. Note that the reason for the question is that the total values are not manually added they are directly calculated using Javascript. Here is a sample to make things more clear. Here is the HTML Template: <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" class="form-control" name="item_1" id="item_1" {% if form.is_bound %}value="{{ form.item_1.value }}"{% endif %}/> {% for err in form.item_1.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> <td> <h6 style="float:left; margin-right:5px; margin-top:7px">$</h6> <input type="number" class="form-control w-25 subtotal-group subtotal-group-1" name="item_1_amount" id="item_1_amount" {% if form.is_bound %}value="{{ form.item_1_amount.value }}"{% endif %}/> {% for err in form.item_1_amount.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> </tr> <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" … -
ValueError at /plants/plants/ too many values to unpack (expected 2) when using django_filters
Hej! I'm having trouble with my django filter. When I put {{myFilter}} in the template I only get an ObjectNumber and when I put {{myFilter.form}} I get the error: ValueError at /plants/plants/ too many values to unpack (expected 2) Does anyone have an idea what's going on? # views.py def plants_view(request): plants = Plant.objects.all() myFilter = PlantFilter(plants) context = {"plants": plants, "myFilter": myFilter} return render(request, 'plants/search_table.html', context) # filters.py class PlantFilter(django_filters.FilterSet): class Meta: model = Plant fields = ['name',] it doesn't matter if I use fields = [ ] or fields = '__all__' . template.html {% extends "landing/base.html" %} {% load static %} {% load i18n %} {% load admin_urls %} {% block page-title %} {%translate "View Plants" %} {% endblock %} {% block head %} <link href="{% static 'landing/vendor/tabulator/dist/css/tabulator.min.css' %}" rel="stylesheet"> <link href="{% static 'landing/vendor/tabulator/dist/css/bootstrap/tabulator_bootstrap4.min.css' %}" rel="stylesheet"> {% endblock %} {% block content %} <br> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{myFilter.form}} <button class="btn-primary" type="submit">Search</button> </form> </div> </div> </div> </br> # models.py class Plant(models.Model): name = models.CharField( max_length=200 ) def __str__(self): return f"{self.name}" def serialize(self): return { "Name": self.name } -
SQL AND PYTHON EXPRESSION MEANING
Hello i found this expression on some source code i was reading. what does the comma sign mean (between order_item and created). Is 'created' a reserved word in sql? Also if you have any source to learn using sql with python would be great thanks. Heres the expression: order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) -
Passing a list of strings (uuids) back and forth between django views and template
On one of the pages of my django project I have a check box to select uuids corresponding to a model. This is what I have on the views.py page and it works well to create a checkbox. def template_page(request, uuid_selects=None, option_1=False): ... class uuidCheckBox(forms.Form): uuid_selects = forms.ModelMultipleChoiceField(queryset=uuid_model, widget=forms.CheckboxSelectMultiple) uuid_select_field = uuidCheckBox() args.update({'uuid_select_field': uuid_select_field}) ... render(request, landing.html, args) On my template page I have this: <form action='get_uuid_selects' method='GET'> {{ uuid_select_field }} <input type='submit' value='Submit' /> </form> Which redirects back to this view: def get_uuid_selects(request): uuid_selects = request.GET.getlist('uuid_selects') return landing_page(request, uuid_selects) This all works fine however when I try to pass this list of uuids back to the template as a hidden value and return it when the user accesses another form the list doesn't work. For example I pass the list as an argument following the approach here This is the views.py for template: def template_page(request, uuid_selects=None, option_1=False): ... if uuid_selects: args.update({'uuid_selects': json.dumps(uuid_selects)}) ... render(request, landing.html, args) Then I pass this list of uuids back to the template page so that it is a hidden value in another form on the template.html page. <form action='to_option_1' method='GET'> <button type='submit'>Option 1</button> {% if uuid_selects %} <input type="hidden" value= {{ uuid_selects }} name="uuid_selects"> … -
Should I use build APIs for my POS web application?
I'm building a POS(Point of sale) web application using Django for my client. This is a single instance web app. I just want to know, should I build APIs to separate Backend and Frontend? Whare are the benefits to build the APIs? -
Soft Delete. Move records or create "deleted" column
I am a little confused about which is better for soft delete. There are two ways for Soft Delete. create table for deleted records.(In this way we will make copy for the records in the table of deleted records, then delete it from its table) create extra column called deleted,(In this way we will only change the status of this field to true , then at display records we will filter according to this extra field) -
How to do nested group by with annotation in django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count how many books of the same titles are published by each author. I want to get the following result: {publisher: New Age Books, title: Life Without Fear, count: 2}, {publisher: New Age Books, title: Sushi Anyone?, count: 1}, {publisher: Binnet & Hardley, title: The Gourmet Microwave, count: 1}, {publisher: Binnet & Hardley, title: Silicon Valley, count: 1}, {publisher: Binnet & Hardley, title: Life Without Fear, count: 1}, {publisher: Algodata Infosystems, title: But Is It User Friendly?, count: 3} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result.