Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest is not applying Django's migrations
I'm setting up for an existing Django + postgresql project that uses pytest to run the tests (alongisde the pytest-django library). The exact error I'm getting is psycopg2.errors.UndefinedTable: relation "django_site" does not exist, and this happens any time I run the test suite. The reason this fails is because the test framework is creating a test database and applying migrations (seemingly) in the wrong order (or just not all of them): There's a custom model that requires the django_site table, but the migration that creates that table is not recognized/applied in order. Perhaps it's import to note that the django_site model has its migrations overridden. I don't know exactly what to make of this, as I have a local postgres database for development purposes that had no problem applying all migrations. Any idea as to why this might happen? -
How to pass user submitted form data into the success_url in django
I am trying to pass the user submitted form data into the url kwargs. As of now I am directely returning the redirect response within the form_valid methoad of django's class based views. class BillsSelectMonthView(GetFormKwargsMixin, FormView): form_class = SelectMonthAndCustomerForm template_name = 'customers/bills_select_month.html' success_url = reverse_lazy('customers:bills_select_month') current_page_name = PAGE_NAME_BILLS def form_valid(self, form): month_year = form.cleaned_data['month'] self.customer = form.cleaned_data['customer'] return redirect( 'customers:bills_preview', month= int(month_year.month), year = int(month_year.year), customer_id = int(self.customer.pk)) But, with this approach some of the django's other internal methoad will be skipped. I am just wondering is there any other or better way to do the same. Thanks. -
how to create a reward redeem system in python django?
Reward page having current points and a redeem buttom based on specific points . the current point of the logged in user have to see in the rewards page while added from the admin panel. Ifthe user redeemed the reward the point should be automatically changed. I tried many and can't reach any. I am expecting a good answer. -
How to split all posts by their day?
I'm noob in django, so I am facing with problem which all posts should divided by day For example: db.sqlite3 > posts_post id name pub_date 1 My awesome name 2023-04-23 09:21:24.3921 2 This is a great title 2023-04-23 09:22:56.7981 3 Another great title 2023-04-24 18:23:34.3123 4 Different name here 2023-04-25 17:45:21.9643 5 Just a few words 2023-04-25 18:04:32.1236 Then, I should get result like that: >>> [ [Post(1), Post(2)], [Post(3)], [Post(4), Post(5)] ] As you can see on result I should get a list that contains lists. In that lists there are only posts whose days are the same. In post 1 and 2, day - 23, so they are together, post 3 is the only post whose day is 24. Same goes for post 4 and 5. Please help me to tackle this problem -
sorl thumbnail not created cache folder
I tried to use sorl thumbnail in django, i think i did everything good with configuration, but thumbnail is not created as well... My configuration urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('pages.urls')), path('galeria/', include('galleries.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sorl.thumbnail', ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' models.py from django.db import models from sorl.thumbnail import ImageField class Gallery(models.Model): title = models.CharField(max_length=50) class Meta: verbose_name = 'Galeria' verbose_name_plural = 'Galerie' def __str__(self): return f"{self.title}" class Photo(models.Model): title = models.CharField(max_length=50) gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='photos',default='') image = ImageField(upload_to='') template {% for gallery in object_list %} <div class="gallery-photo-content"> <h1 class='header'>#{{ gallery }} {% thumbnail gallery.photos.all 'x300' crop="center" as im %} <img src="{{ im.url }}" class="card-img-top" alt=""> {% endthumbnail %} </h1> </div> {% endfor %} and response 404 error "GET /media/cache/b0/cb/b0cb61cf1f55b3a343fd939b5df40efb.jpg HTTP/1.1" 404 6194 I have no idea how to fix that problem.. Someone know how i did wrong? -
Django uses default db as sqlite. My question is in docker-compose.yml how to define default database command which in my case is sqlite,
I have developed an django base rest api with celery and redis, Now i want to dockerise the whole app. So, my question is in docker-compose.yml how to define default database command which in my case is sqlite -
How to display a list of filtered Django model objects with a related field in a template, sorted by date?
I have a Django app with a model called 'Book' which has a foreign key relationship with a 'Author' model. The 'Author' model has a 'name' field. I want to display a list of all 'Book' objects along with their corresponding 'Author' names in a template. However, I want to limit the query to only return books that were published after a certain date, and I also want to order the list by the book's publication date in descending order. Here is the code I have so far: Models.py class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) publication_date = models.DateField() class Author(models.Model): name = models.CharField(max_length=255) views.py from django.shortcuts import render from django.db.models import Q from .models import Book def book_list(request): books = Book.objects.filter(publication_date__gte='2022-01-01').order_by('-publication_date') return render(request, 'book_list.html', {'books': books}) How can I modify this code to also include the 'Author' name for each 'Book' object in the template? -
wagtail-factories Pagechooser block not working
I am trying to create a factory for my Navigation model but, here top_bar field is not creating. The issue is related to the URLChoiceStreamFactory but unable to solve it. models.py from wagtail.models import Page from wagtail import blocks from django.db import models from modelcluster.models import ClusterableModel from wagtail.admin.panels import FieldPanel from wagtail.models import PreviewableMixin from wagtail.snippets.models import register_snippet from django.utils.translation import gettext_lazy as _ from wagtail.fields import StreamField from django import forms class URLBlock(blocks.FieldBlock): def __init__( self, required=True, help_text=( "Either a relative URL that begins with a forward slash or an absolute URL that begins with http, https, " "tel, or mailto." ), max_length=None, min_length=None, **kwargs, ): self.field = forms.CharField( required=required, help_text=help_text, max_length=max_length, min_length=min_length, ) super().__init__(**kwargs) class Meta: icon = "site" class HomePage(Page): pass class URLChoiceStream(blocks.StreamBlock): internal = blocks.PageChooserBlock(icon="doc-empty-inverse") class Meta: max_num = 1 class LinkBlock(blocks.StructBlock): name = blocks.CharBlock(max_length=128) url = URLChoiceStream() class Meta: icon = "link" label = _("Link") class TopBar(blocks.StructBlock): title = blocks.CharBlock(label=_("Title")) top_bar_links = blocks.ListBlock(LinkBlock(), max_num=5) panels = [ FieldPanel("title"), FieldPanel("top_bar_links"), ] class Meta: icon = "resubmit" @register_snippet class Navigation(ClusterableModel, PreviewableMixin): name = models.CharField( unique=True, max_length=256, help_text=_("This is used for internal reference only."), ) top_bar = StreamField( [("top_bar", TopBar())], max_num=1, verbose_name=_("Top Bar"), null=True, blank=True, use_json_field=True, ) … -
How to create something similear to groups or user permission selection options in django admin
I am new in modifying the Django admin panel. I am trying to create something sililear to the default user permission selection option in the Django admin panel. I want to list all the recoards from a model and need to assign the foreign key of selected options to another model. Is there any way to create something similear to this. Thanks. Try to find a tutorial which is trying to creating similear functionality, but till now not able to find anything on google and not in the django's documentations. -
A form with an arbitrary number of fields in Django
I am a beginner web developer and just learning Django. Question: I have a ListView that displays pictures (16-100 or more) on a website page. Each picture has a checkbox. The user can select multiple images and assign them a tag (from input field). How can I make a Django form for this? And how to process it correctly in my ListView? -
How to migrate a Django project's PostgreSQL database to Railway when railway-cli is not found and installation fails with package errors?
i need to host my postgresql database linked with django project to railway, the host of the django project is very easy but I don't know how to do the migration, I have tried to use the railway CLI but i get the eroor: railway: command not found, and when I try to install railway from npm or other place I get errors that one or more packages aren't updated to latest version despite being on the latest version; if anyone have a solution also, is there a free hosting to deploy django + postgreSQL database without day limit and the auto delete of images after inactive -
import model in Django to services django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
I am facing the following problem. On my Django project, I created a services.py file in the "resume" app directory, in which I want to place some project business logic. Below is the project structure: In this file (services.py) I import the models: # services.py from models import PersonalData def get_personal_data(): list_data = PersonalData.objects.all() return list_data Then I get the following exception: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Below is the entire Traceback: Traceback (most recent call last): File "D:\python_projects\my_site\mysite\resume\services.py", line 9, in <module> from mysite.resume.models import PersonalData File "D:\python_projects\my_site\mysite\resume\models.py", line 4, in <module> class PersonalData(models.Model): File "D:\virtualenv\mysite\Lib\site-packages\django\db\models\base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\virtualenv\mysite\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "D:\virtualenv\mysite\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "D:\virtualenv\mysite\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "D:\virtualenv\mysite\Lib\site-packages\django\conf\__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with exit code 1 My INSTALLED_APPS in settings.py has this app: INSTALLED_APPS = [ 'resume.apps.ResumeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] One … -
i was geeting websocket failed error in python
in:119 WebSocket connection to 'ws://127.0.0.1:8000/join' failed: ( loc = window.location; wsStart = 'ws://'; if (loc.protocol == 'https:') { wsStart = 'wss://'; } var endpoint = wsStart + loc.host + loc.pathname; console.log(endpoint); ws = new WebSocket(endpoint); ws.addEventListener('open', (e) => { console.log('connection Opened!!!') sendSignal('new-peer', {}) }); ws.addEventListener('message', webSocketOnMessage); ws.addEventListener('close', (e) => { console.log(e); }); ws.addEventListener('error', (e) => { console.log(e); }); i was geeting error please want to help -
What is the simplest way to implement CDC in a monolithic Django project with MySQL DB?
I want to implement the logic below in my monolithic (not microservice) Django project and its MySQL DB: The Django server changes data of table A in the MySQL db. The CDC tool (?) captures the change and callbacks (?) the Django server. The Django server updates table B (which is for save statistic data) using the changed data of table A. There are many tables like "table A" currently and I will create other tables like "table B" (for statistics) in the MySQL DB, so CDC is needed to keep consistency among such tables. Note that I will not write triggers or stored procedures in the MySQL db because my team want to avoid using them. What is the simplest way to implement CDC in my project? -
I want to develop the front end designs for my website in django
can any one tell me how the front end engineers in software company create the frontend website page designs before starting the development? Do they use any tools to create the designs, if so, could you please demonstrate with one example? -
Problem while executing a project created using old versions of Python and Django
I want to run this project that I found on Github: https://github.com/ldurans/MedicalWebApp The author used Python 3.2.2 and Django 1.6.5, the problem with these two old versions is with pip installation, thus I couldn't create a virtual environment. I installed recent versions of Python and Django, I tried to correct some errors related to their version, I had other errors to which I couldn't find solution on the internet, as the code source isn't mine, I can't correct it easily. My question is this: is there a way I can upgrade the version of Python and Django of the code project so that it can easily be ran using recent versions ? Or is there another way of running it without gettings errors ? PS. I was using python manage.py makemigrations. It is asked to run python quickstart.py I tried so, but I couldn't get a result. Thank you for your help. I tried using recent versions of Python and Django to run this project that was created with old versions. -
wagtail, Failed to import images uploaded from the wagtail administrator console to the page
Failed to import images uploaded from the wagtail administrator console to the page. Image title is being loaded properly, but image url is not being loaded. Please, Help. in browser #home/models.py from django.db import models from wagtail.models import Page from wagtail.fields import RichTextField from wagtail.admin.panels import FieldPanel class HomePage(Page): header_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = RichTextField(blank=True) body_detail = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('header_image'), FieldPanel('body'), FieldPanel('body_detail'), ] #home_page.html {% extends "base.html" %} {% load static %} {% load wagtailcore_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'css/welcome_page.css' %}"> <div class="container"> {% if page.header_image %} <img src="{{ page.header_image.url }}" alt="{{ page.header_image.title }}"> {% endif %} <h1>{{ page.title }}</h1> {{ page.body|richtext }} <div class="homebtn_intro"> <a href="{% slugurl 'about' %}"> <img src="{{ page.image.url }}" alt="hello"> </a> <a href="{% slugurl 'about' %}"> <img src="" alt="registration"> </a> <a href="{% slugurl 'about' %}"> <img src="" alt="donation"> </a> </div> </div> {% endblock %} Checked the path where the image is stored and verify that template language is created correctly. -
How to solve the error when import css in Django
I'm trying to import css from a static directory, but I'm getting the following error: Please help me as soon as possible.enter image description here enter image description here I'm trying to import css from a static directory, but I'm getting the following error: Please help me as soon as possible -
get_object_or_404(), handler404, Http404 response. How do these things works?
Could you help me with something in Django, please? I would like to understand the sequence of execution of 404 page not found error Let me put the code here... url.py -----------file from django project from django.contrib import admin from django.urls import path, include from django.conf.urls import handler404, handler500 from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ] handler404 = views.error404 handler500 = views.error500 url.py -----------file from django app from django.urls import path from .views import index from .views import contact from .views import product urlpatterns = [ path('', index, name='index'), path('contact', contato, name='contact'), path('product/<int:pk>', produto, name='product'), ] view.py def produto(request, pk): print(f'PK: {pk}') prod = get_object_or_404(Product, id=pk) context = { 'product': prod } return render(request, 'product.html', context) def error404(request, exception): template = loader.get_template('404.html') return HttpResponse(content=template.render(), content_type='text/html; charset=utf8', status=404) def error500(request): template = loader.get_template('500.html') return HttpResponse(content=template.render(), content_type='text/html; charset=utf8', status=500) I would like to understand the following: Let's suppose that in the table 'Product' there are only 5 instances...so for the 5th instance, the URL is http://127.0.0.1:8000/product/5 ok? Let's suppose that I try to get the 10th instance in the table that does not exist, so the line of code prod = get_object_or_404(Product, id=pk) will return the instance … -
How to attach user to request object
I'm using JWT for authentication in a django rest framework. It works like this: Creating a JWT token token = jwt.encode(payload, os.environ.get('SECRET'), algorithm='HS256') Sending the JWT token as a cookie with the httponly flag response.set_cookie(key='jwt', value=token, httponly=True) To verfiy that user is logged in any view I look for the cookie and decode it. The problem is that it wont use permission classes for the request object. I would like to know how I can do that. -
Django, Not SupportedError: Mari aDB 10.4 or later is required
I have a simple django project what i used some libraries like PyMySql, pillow and... But problem is on my host, when i enter this command: python manage.py makemigrations Unfortunately, i've got this error: Not SupportedError: Mari aDB 10.4 or later is required(found 10 .3.38). Please help me to resolve and understand this problem. Thanks for your attention. -
Django. Error writing database from csv via custom commands
I want to write my own command to quickly get data from csv. The script successfully fills the table User, Category, Genre. But when it comes to the Title model, I get the error ValueError: Cannot assign '1': 'Title.category' must be an instance of 'Category'. How to make beautiful without using additional modules? models = { User: 'users.csv', Category: 'category.csv', Genre: 'genre.csv', Title: 'titles.csv', } class Command(BaseCommand): help = 'Command to automatically populate the database' def handle(self, *args, **options): path = str(BASE_DIR / 'static/data/') for model, csv_file in models.items(): with open(path + '/' + csv_file, 'r', encoding='utf-8') as file: rows = csv.DictReader(file) records = [model(**row) for row in rows] model.objects.bulk_create(records) self.stdout.write(self.style.SUCCESS(f'Done {model.__name__})')) Example CSV files: users.csv id,username,email,role,bio,first_name,last_name 100,bingobongo,bingobongo@mail.fake,user category.csv id,name,slug 1,Movie,movie genre.csv id,name,slug 1,Drama,drama titles.csv id,name,year,category 1,The Shawshank Redemption,1994,1 -
Django SearchRank not taking full text search operators into account
I'm trying to add a new endpoint that does full text search with AND, OR, NOT operators and also tolerates typos with TriagramSimilarity. I came across this question: Combine trigram with ranked searching in django 1.10 and was trying to use that approach but SearchRank is not behaving as I'd expect, and I'm confused about how it works. When my code looks like the basic implementation of full text search the negative filter is working fine @action(detail=False, methods=["get"]) def search(self, request, *args, **kwargs): search_query = request.query_params.get("search") vector = SearchVector("name", weight="A") query = SearchQuery(search_query, search_type="websearch") qs = Project.objects.annotate( search=vector, ).filter( search=query, ) return Response({ "results": qs.values() }) But I need to implement this using SearchRank so I can later do some logic with the rank score and the similarity score. This is what my code looks like annotating for rank instead of using the tsvector annotation: @action(detail=False, methods=["get"]) def search(self, request, *args, **kwargs): search_query = request.query_params.get("search") vector = SearchVector("name", weight="A") query = SearchQuery(search_query, search_type="websearch") rank = SearchRank(vector, query, cover_density=True) qs = Project.objects.annotate( rank=rank, ).order_by("-rank") return Response({ "results": qs.values() }) And the response looks like: The rank given to the document named "APT29 Attack Graph" is 1. I'd expect the - operator … -
How to link an automatically updating model object with Django Template Language
I'm making a blog, on the index page I have a list that links every single blog post with some details about it <ul> {% for post in object_list %} <li><a href="{% url 'article_detail' pk=post.pk %}">{{ post.title }}</a> - {{ post.author.first_name }} {{ post.author.last_name }}<br/> {{ post.summary }}</li> {{ post.adventure_date }}<br/> {% endfor %} </ul> </div> Now what I want is on the home page to have a featured article section that will automatically update with the two most recently posted articles without having to manually change the code every time the posts are added. I'm struggling to come up with a solution to this, I'm thinking that I would create another variable in my model that was like featured = BooleanField(default=True) But I'm not sure how the true or false would be automatically updated without me going into django admin and manually checking the boxes each time it needed updated -
How to run tasks in django?
I have a Dynamic programming algorithm that takes 2 arrays as an input and returns an array as an output (The arrays are fetched from my django model). I usually just write the algorithm in the view Example: #Model class input(models.Model): arr1 = ArrayField(models.CharField( null=False, max_length=200), blank=False) arr2 = ArrayField(models.CharField( null=False, max_length=200), blank=False) #View @api_view(['GET','POST']) def process(request): arr1 = ... # fetch arr1 arr2 = ... # fetch arr2 def my_algorithm(arr1 , arr2 ): ... ... return arr3 arr3 = process(arr1,arr2) ... ... return Response("Success") There is a tool called celery that does asynchronous task queue/job but it doesn't support windows anymore. What's the alternative or how can i execute the algorithm as a task and call it in the view?