Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What it can be? ModuleNotFoundError [closed]
Working with Django I faced with very strange problem. I wanted to create a request, but url list can't see my path.. I have tried to change pathes, but it didn't helped -
Disable Django to keep only Django Rest Framework for Vue
for a school project, I have to use Django and Vue. Django to provide an API and Vue for the frontend. They are two separate projects that we have mix. For example, I type my-site/clients, it gives me the list of the clients in json format (API). But if I type my-site/home it gives me a Vue page. I tried to run the two servers on the same port, but that is not compatible (Django want to display a page when it has to Vue to display it). So I was thinking to disable the Django to only keep Django Rest Framework for the API. Is it possible ? Thank you ! -
Django & PostgreSQL - backup and restore part of the database
Current Implementation: I have a Django application on one server that uses a PostgreSQL database instance in the same server. This Django app is served using UWSGI as an app server, then NGINX layer on top of it as a web server. This database instance has a complex schema that handles multiple companies' data. Each single row is related to one company. Based on the user's company, he can work on his company's data only. So, an isolation is implemented for each company users. New Business Requirement: A backup should be taken daily from the database mainly because any company may need to rollback to an old version of their data (for example, 3 days back). So, I have done some research and I came up with multiple options: Option 1: having one Django application but with multiple database instances, and controlling the selected database based on the subdomain where each subdomain represents one company. This makes it possible to backup and restore a single instance of the database if needed at any point of time, but it makes it complex in code to separate the selected database by company. Also, it could be harmful for the single application to … -
Processing a file on client side in Django?
I want to build a web application where a user can upload a file, the file is processed and some result is shown to the user (for example the amount of lines of the file). However, since the files might be confidential, the user does not want that the file is stored on the server side. So the file needs to be processed without storing it on the server. Since I am familiar with Python, I wanted to create the website using Django (I want to learn it anyway). But as I understood, Django is a server framework, so is it even achievable using Django what I want to do? How? Or do I need to use React and Django? Or only React? -
Can’t open database while using Django in VSCode
I’m working on a django project and I’m trying to open database in VSCode but I keep getting “failed to open database” error. The sql explorer doesn’t even show up on the explorer pane. I have SQLite extension installed. I’ve also installed sqlite3 on my computer and it works according the cmd prompt. But I’m still getting this error message. I read the Django documentation and I’m not sure if I need to make any changes in settings.py? This is what it looks like ENGINE: ‘django.db.backends.sqlite3’, NAME: BASE_DIR / ‘db.sqlite3’, I’m using a windows 10. Any help would be appreciated. This is my first django project so I’m still learning. -
Django Q object to query vendors near my location within their delivery radius
I am trying to get from a query all vendors in 10km radius and i got it working with: latitude = 51.507506503730866 longitude = -0.12812200560448234 radius = 10 if latitude and longitude and radius: pnt = GEOSGeometry("POINT(%s %s)" %(longitude, latitude)) vendors = Vendor.objects.filter(Q(is_approved=True, user__is_active=True), user_profile__location__distance_lte=(pnt, D(km=radius))).annotate(distance=Distance("user_profile__location", pnt)).order_by("distance") When i loop through vendor i can get the distance between user_profile and vendors with: for v in vendors: print(v) print(v.user_profile.location) No I would like to filter it so only the vendors within the max_delivery_distance in range be listed. I dont now if i have to add it in the same query or do a separeted query for it. I now this is a bit specific but if some one has this know how i would be thankfull for any directions. thank you very much in advance reynaldo -
'function' object has no attribute 'getlist'
I have an error in my Django project my project cannot understand the getlist function what is the problem and what can I do? my code is this: req = request.post.getlist('name1[]') and the error is this: AttributeError at / 'function' object has no attribute 'getlist' -
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