Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django manage.py runserver returns a list of subcommands
How do I use "manage.py" instead of "python manage.py"? It used to work, but now it just returns a list of subcommands. Windows 10; PyCharm; Python 3.9; Environment variables are set: "PYTHONPATH": "\Python\Python39; \Python\Python39\DLLs; \Python\Python39\Lib;" manage.py has shebang: "#!/usr/bin/env python" venv in PyCharm is set to: "...\<project_folder>\venv\Scripts\python.exe" -
Django REST filering result
Is there some auto filtering feature in Django REST? Some build in functionality to filter using parameters in url? Or maybe is there some handy way to use optional parameter? -
HTML changes not reflecting on website in Django app using Ubuntu 20.0, Nginx, and Gunicorn
I'm hosting my Django website with Digital Ocean using Ubuntu 20.0. I deployed my app successfully. I have now been making changes to my HTML files. After running git pull origin master, I restarted both Gunicorn and Nginx. The changes are reflected in development but not in production. What could be the problem? -
how do i create a csv file, upload it to database and make it downloadable for users using django? [closed]
i'm an absolute beginner in django so please help me. i am working on a data quality management app, basically a user uploads their csv file, i evaluate it then fix the errors and let the user download the file again, but in order to not modify their original file, after the evaluation, i need to create another csv file where i only copy the good data. but when i create it, it ends up in the current folder with my views and urls etc files which i don't want, also i don't know how to upload it to my sqlite database and how to render it to my html page. -
I can't send embedded images in mail with django
i'm trying to send an email confirmation after an user created an account on my website. The problem is that, the email doesn't contains the images that i setted up on .html file and i don't know how am i supposed to send them: In view function: link = "http://localhost:3000/verify/" + user.verifyToken html_messages = render_to_string('emailTemplate.html',{"nume":request.data['nume'], "prenume":request.data['prenume'], "verifyLink":link}) plain_message = strip_tags(html_messages) mail.send_mail( 'Activate your account', plain_message, settings.EMAIL_HOST_USER, [request.data['email']], html_message=html_messages ) That's how i loaded the images in emailTemplate.html: <td style="padding:0;Margin:0;font-size:0px" align="center"><img class="adapt-img" src="images/34711630659742615.png" alt style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" width="428"></td> <td style="padding:0;Margin:0;font-size:0px" align="center"><img src="images/90241630659912039.png" alt style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" width="200"></td> If i open the .html file in my browser it looks fine but when i send it to e-mail it doesn't contains any image. Does anyone know what am i supposed to do? Thank you! -
Can't connect Postgres container with Django container on Docker
I have two images: 1. PostgreSQL, 2. Django application. I am trying to connect django with postgres via networking Here is my DATABASE_URL DATABASE_URL=postgres://postgres:somepassword@0.0.0.0:5432/music and my docker-compose.yml version: "3.1" services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: qweytr21 POSTGRES_DB: music ports: - 5432:5432 web: build: music-releases/ ports: - 8000:8000 depends_on: - db command: pipenv run python manage.py migrate So when i run docker-compose up. Postgres shows that it is listening this address listening on IPv4 address "0.0.0.0", port 5432 But Django (psycopg2-binary) shows error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? As you can see psycopg searchs true host and port and postgres also is listening on that host and port. I have already searched for another answer but they don't work. Any help PLEEEASE!!! -
How to find all dates between 2 dates in django?
I want to find all dates between 2 dates the first date is unique_dates[0] the value of unique_dates[0] is 2021-08-30 and the second date is datetime.date.today() unique_dates = list({a.date for a in attendances}) date = datetime.date.today() How to do this ? -
Insert large data into Django database
How do I optimally add large datasets to Django? My current workflow looks like this: Scrapy -> DRF -> Celery -> (Transform data) -> Django ORM -> PostgresQL I was thinking of using something like this: Scrapy -> Kafka -> (Transform data) ? -> Python Consumer (Spark?!?) -> PostgresQL I care about the high efficiency of the solution. Up to 20 million upserts (update if exists else intest) are made daily. -
Dynamically creating tables using SQLite and django
I am given a task for a web im developing currently. The task is to dynamically create tables as long as the 'save' button is pressed in my web. I am using SQLite for my database. Currently, my codes allow me to do the necessary saving to the existing tables but I am unsure of how to do the following task. Example: I have the fields of 'name' and 'something'. So user type Test for name field and Hello for something field. Upon saving, this name is stored in a existing table and register under a id of 1. At the same time, i want to be able to create a new table with its own field. This table will be named as example_(id). So in this case it will be example_1. Im a beginner in Django and SQL so if anyone can guide/help me in any way, thank you! -
Is there a way to perform django admin like list filtering in django generic ListView?
I'm trying to add filtering for a django list view something like Here is my view class SaleView(ListView): model = SaleBill template_name = "sales/sales_list.html" context_object_name = "bills" ordering = ["-time"] paginate_by = 10 and my template {% extends "base.html" %} {% load widget_tweaks %} {% block title %} Sales List {% endblock title %} {% block content %} <div class="row" style="color: #ea2088; font-style: bold; font-size: 3rem;"> <div class="col-md-8">Sales List</div> <div class="col-md-4"> <div style="float:right;"> <a class="btn ghost-blue" href="{% url 'new-sale' %}">New Outgoing Stock</a> </div> </div> </div> <br> <table class="table table-css"> <thead class="thead-inverse align-middle"> <tr> <th width="10%">Bill No</th> <th width="15%">Customer</th> <th width="15%">Stocks Sold</th> <th width="10%">Quantity Sold</th> <th width="10%">Total Sold Price</th> <th width="15%">Sale Date</th> <th width="25%">Options</th> </tr> </thead> {% if bills %} <tbody> {% for sale in bills %} <tr> <td class="align-middle"> <h3>{{ sale.billno }}</h3> </td> <td class=""> {{ sale.name }} <br> <small style="color: #909494">Ph No : {{ sale.phone }}</small> </td> <td class="align-middle">{% for item in sale.get_items_list %} {{ item.stock.name }} <br> {% endfor %}</td> <td class="align-middle">{% for item in sale.get_items_list %} {{ item.quantity }} <br> {% endfor %}</td> <td class="align-middle">{{ sale.get_total_price }}</td> <td class="align-middle">{{ sale.time.date }}</td> <td class="align-middle"> <a href="{% url 'sale-bill' sale.billno %}" class="btn ghost-pink">View Bill</a> <a href="{% url 'delete-sale' sale.pk … -
Limiting file types for a specific DocumentChooserBlock() Block in Wagtail Steamfield
I'm trying to limit query results for a specific DocumentChooserBlock inside of a wagtail stream field block. I already know that you can limit file types for DocumentChooser for a page type by using hooks, but I would like to avoid limiting possible file types page wide in case I need them for other StreamField blocks. Are there any possible ways to implement what I am trying to achieve here? -
How i read the django log.debug() output and store in variable for display in my templates?
In logging setting i have set the output in console, and i want to read the console output for example a = log.debug("hello") print(a) But i tried this its return None -
Django ckeditor - How to create thumbnail of uploaded images by default
In settings.py I have CKEDITOR_IMAGE_BACKEND = 'pillow' but a thumbnails have not been created automatically. In docs v.6.1.0: Set CKEDITOR_IMAGE_BACKEND to one of the supported backends to enable thumbnails in ckeditor gallery. By default no thumbnails are created and full size images are used as preview. Supported backends: pillow: Uses Pillow How should I do it? Thanks! -
Django Filters NameError: name 'group' is not defined [closed]
When i am trying to render a view,i try to check by filter if the group is null or not. I already defined "group" in models as Foreignkey but it gives me the error.How can i solve it? Error File "/root/server/accounts/filters.py", line 33, in filter_queryset group == null NameError: name 'group' is not defined Views.py class GrouppArticleViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-timestamp') serializer_class = ArticleSerializer filter_backends = [GroupArticlesFilterBackend] Filters.py class GroupArticlesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.exclude( group == null ).filter( group__groupmembers_set__author=request.user ).distinct() Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True,blank=True,related_name='grouparticle') caption = models.CharField(max_length=250) -
Django Form - How to create a custom form template with a loop for one field?
I'm creating a web app which uses Django's templating engine. Having said that, one of my models is called Order. The Order model, aside from the other models, also uses a model Food - this is a ManyToMany relationship. Food model uses model Category to define food categories (which should contain food categories like Pizza, Burgers, Wine, Beers, etc.) - this is a ManyToMany relationship, as well. Now, I'm trying to create a form where the user will be shown a form with separated categories. As of now, all of the foods from the Food model are just shown one by one, one below another one. They are not categorized in the form template. Currently, they are shown by default, as a simple list of foods where user can choose any of them. I want the user to choose any foods they want, but display them categorically (all of the pizzas under the Pizza category, all of the burgers under the Burgers category, etc.). My models.py looks like this: class Category(models.Model): """ Model for food categories """ name = models.CharField(max_length=100) description = models.TextField(max_length=300) date_created = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.name} / {self.description[0 : 50]}..." class Food(models.Model): """ Model … -
How to limit number of clients in django channels' room
I wish to limit the number of users in a room to 2 because I am making a socket game were two palyers can play a tic-tack-toe or a connect-4 game so I a trying to find some way of limiting only 2 players in one room. Down below is my comsumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class GameRoom(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = 'room_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() I have removed some of the less necessary methods from this question -
django database bug inccorect printing choice field
so i am trying to take data from admin panel and one field is choice field (male and female). when i registered users with female and male type in my dashboard everyone have only 1 value which is female so i need to fix it but how i dont know here is my code about views models and dashboard. models.py class Id(models.Model): first_name = models.CharField(max_length=100, null=True) CHOICES = [('Male', 'Female'), ('Female', 'Male')] gender = models.CharField(max_length=30, choices=CHOICES) def __str__(self): return self.first_name this is views def home(request): context = { 'posts': Id.objects.all(), 'title': 'Home' } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html', {'title': 'About'}) and last this is my home.html (dashboard where all my users data will showing up {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.first_name }}</a> </div> <p class="article-content">{{ post.gender}}</p> </div> </article> {% endfor %} {% endblock content %} -
How to stream pdf response as file attachment?
I have a model models.py class Dibbs(models.Model): name = models.CharField(max_length=20) views.py def index(request): dibbs_obj = Dibbs.objects.all() context ={'dibbs_obj':dibbs_obj} return render(request,"index.html",context) template: {% for i in dibbs_obj %} <td data-label="name"><a href="{% url 'display_pdf' %}">{{ i.name }}</a></td> {% endfor %} There is the exact pdf file of name in the media/uploads/ folder. So, I created another view function to stream the pdf file as file response when I click on the name in the template def display_pdf(request,id): buffer = io.BytesIO() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='') How to properly use this FileResponse function so that it opens the link of the same name? (In this case, the data that is in the name have its corresponding pdf file as name.pdf in the media/uploads/ folder) -
How to get Django MultiSelectField values
I have installed Django MultiSelectField through the library django-multiselectfield==0.1.12 and here is my code. models.py: class Job(models.Model): CONTRACT = (("1", _("Indefinido")), ("2", _("Temporal")), ("3", _("Formación o Prácticas")), ("4", _("Autónomo o Freelance"))) contract = MultiSelectField(verbose_name=_("Contract"), max_length=200, choices=CONTRACT, null=True) The Django Admin Form works well, i can select various optionsare saved and show again selected. The database store the list of option ids correctly. But when try to access attribute values on python appears None: print(self.job.contract) None, None Anybody could help me please ? Thanks in advanced. -
How to make a field editable while creating, but read only in existing objects?
I've a django Model, and want to be able to set an id while creating. But once created, the id of existing object shouldn't be editable. class Vehicle: id = models.UUIDField(primary_key=True, default=uuid.uuid4) I see that I need to turn do "editable=True" (which is the default) on the id field, but this would allow editing the id field later on as well. -
Passing POST request by AJAX, Django problem
my view is : def creating_profile(request): if request.is_ajax and request.method == "POST": array = request.POST.get('nums') print(request.POST.get('nums')) else: print('it's not ajax') my js: const RegisterForm = document.forms["RegisterForm"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let nums = [1, 2, 3] RegisterForm.addEventListener('submit', () => { $.ajax({ headers: { 'X-CSRFToken': csrftoken }, url: '/account/creating-profile/', type: 'POST', data: { nums: nums }, success: function (data) { // } }); but it returns None the result of print(request.POST.get('nums')), I would be glad if someone help me about this issue -
django: Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?
Please help with the error I am getting following along a django book.The errors states: "Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?". Attached is the image. Thanks django webpage error {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% if user.is_authenticated %} Hi {{user.username}}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> | <a href="{% url 'signup' %}">Sign Up</a> {% endif %} {% endblock content %} -
KeyError : But the key exists and getting the good result
I have an API that analyse items contained in an image url and return me a dictionnary, everything is OK until I try to count how many occurences of a key, value pair ! The problem is that Python tell me that there is a KeyError on a key that exists and moreover I'm getting the result I want ... To explain, the first for loop is here to access the first dict and then I'm using Counter to group values contained in the 'labelName' key by their key. I'm learning Python just to say. @api_view(['GET']) def send_image_to_url(request, encoded_url): analyzed_image = analyze_url(encoded_url) items_list = [] for response in analyzed_image.values(): aggregated_items = Counter(item["labelName"] for item in response) return Response(aggregated_items) Here is analyzed_image : { "response": [ { "labelId": 8722, "labelName": "Sofa", "score": 0.99225813 }, { "labelId": 8732, "labelName": "Low Table", "score": 0.9896868 }, { "labelId": 8729, "labelName": "Carpet", "score": 0.98912084 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.9777501 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.97317785 }, { "labelId": 8714, "labelName": "Chair-Armchair", "score": 0.9629707 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.91856897 }, { "labelId": 8722, "labelName": "Sofa", "score": 0.88815445 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.6156193 }, { "labelId": … -
How to change `related_name` field of model after migration in Django?
Initially I created a model as shown in image here: MyModel is dummy name Notice, user as a field with ForeignKey relation with related_name as creater which is actually a spelling mistake which I made. Then I ran python manage.py makemigrations and python manage.py migrate commands. After that I realised that I need to correct the spelling and I changed it accordingly as shown in image here: Notice change Now again to incorporate these changes I ran the above two command but when I ran python manage.py makemigrations command I got following error: Error by Django -
Problems with dynamic like and dislike buttons via django templates and JS
I'm trying to dynamically create and use like and unlike buttons for my cs50w project, which should of course allow the user to like or unlike a post and switch a like button to an unlike button and so on. Now, the infuriating thing is, the like and unlike mechanics themselves work, but the buttons are screwing with me. Either I can't get the opposite button to be created after I deleted the original one via Javascript (I tried to use appendChild and CreateElement, to no avail). Or if a post has more than 1 like then more buttons show up with 2/3 of them being duds, etc. I check in a Django view if the current user has liked any posts (the likes are in their own model with 2 Foreign Keys), then if there are any posts then I send them as context to the necessary templates. Inside the templates themselves, I check if a post corresponds to the context if it does I generate an Unlike button, if not I generate a Like button. I've tinkered and googled but the situation is not improving at all... Code: index.html: {% extends "network/layout.html" %} {{ user.username|json_script:"username" }} {% block …