Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django as Backend and Weblfow as frontend?
I can code and I want to build a SaaS with Python Django but I want to use Django as the backend and for the front end, I want to use Webflow. Is it a good idea? If not what would you suggest? -
Django Channels is not taking over deployment server
I am attempting Django Channels for the first time. I am following this tutorial - https://www.youtube.com/watch?v=cw8-KFVXpTE&t=21s - which basically explains Channels basics. I installed Channels in my virual environment using pip install channels and it installed the latest version, which is 4.0.0. I have laid out the basic setup. But when I run python manage.py runserver, I get - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 02:37:40 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. when I shoul be getting this - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 02:37:40 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. I cannot figure out what I might be doing wrong here and I cannot find any relevant solution anywhere. I would really appreciate any suggestions anyone might have. settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Orders', ] ASGI_APPLICATION = "BrokerBackEnd.asgi.application" asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, … -
"django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" when run Celery
I'm trying to install celery in my docker-compose project. When I execute docker-compose up I obtain this log: project_meals_celeryworker | ERROR 2023-01-09 20:29:06,089 signal 11 274910545088 Signal handler <bound method DjangoFixup.on_import_modules of <celery.fixups.django.DjangoFixup object at 0x4004f385e0>> raised: ModuleNotFoundError("No module named 'food'") project_meals_celeryworker | Traceback (most recent call last): project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/utils/dispatch/signal.py", line 276, in send project_meals_celeryworker | response = receiver(signal=self, sender=sender, **named) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 82, in on_import_modules project_meals_celeryworker | self.worker_fixup.validate_models() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 120, in validate_models project_meals_celeryworker | self.django_setup() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/celery/fixups/django.py", line 116, in django_setup project_meals_celeryworker | django.setup() project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/init.py", line 24, in setup project_meals_celeryworker | apps.populate(settings.INSTALLED_APPS) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate project_meals_celeryworker | app_config = AppConfig.create(entry) project_meals_celeryworker | File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 193, in create project_meals_celeryworker | import_module(entry) project_meals_celeryworker | File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module project_meals_celeryworker | return _bootstrap._gcd_import(name[level:], package, level) project_meals_celeryworker | File "", line 1030, in _gcd_import project_meals_celeryworker | File "", line 1007, in _find_and_load project_meals_celeryworker | File "", line 984, in _find_and_load_unlocked project_meals_celeryworker | ModuleNotFoundError: No module named 'food' project_meals_celeryworker | ERROR 2023-01-09 20:29:06,096 signal 11 274910545088 Signal handler <promise@0x4004ebaee0 --> <bound method Celery._autodiscover_tasks of <Celery main at 0x4004ed1130>>> raised: AppRegistryNotReady("Apps aren't loaded … -
Django , map sql output with different values using dictionary and send them to template
I have a function that I use to show number of citizens and countries in charts.js def Inbound_top_20(request): cursor1=connections['default'].cursor() // calling default database connection cursor1.execute("select citizens, countries from world ") r1=dictfetchall(cursor1) // calling dictfetchall function , because I use raw sql D1={"1-1":"France" , "2-2":"Spain" , "3-3":"Germany",.....} //dictionary return render(request,'app_sins/countries .html',{"show1" : r1,"D1": D1,}) output of query are values of citizens, and name of countries, but countries are represented as string "1-1" , "2-2" , "3-3". I wish to map SQL output for countries using dictionary D1, to give them real names , not strings "1-1" or "2-2" ... After that I need to vizualize them through the charts.js. Below is extract from charts.js using column countries which works fine for strings ("1-1" or "2-2" ...) ...... const ctx11 = document.getElementById('myChart11').getContext('2d'); const myChart11 = new Chart(ctx11, { type: 'line', data: { labels: [{% for show1 in show1%} '{{show1.countries}}', {% endfor %}], ......... Please advise how I can easily map sql output strings ("1-1" or "2-2" ...) to real names and put them in template tags -
Javascript toggle display in for loop
I am currently trying to toggle a div to show and hide when a user clicks on a button and it currently works. However, as i am using a for loop to display some list of data, the toggle button only shows and hides the div of the first set of data from the list and not the rest. There are multiple of the same buttons as it is being looped in a for loop and each one should toggle display the div of their current data from the list and not the first. Is this because the id is the same for all the divs if so how would i go around fixing this? Code: <div class = "profile"> {% for i in profile %} <button onclick="toggle()">Show Form</button> ... <div class ="form" id = "toggle_display"> <form method="POST" enctype="multipart/form-data"> <input type="text" name="username"> <button class="uploadPost" type="submit">submit</button> </form> </div> {% endfor %} </div> Javascript: function toggle() { var x = document.getElementById("toggle_display"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } -
Why does running `./manage.py dumpdata core.Setting > setting.json` work from the terminal but not when using `docker-compose run --rm...`?
I have a Docker container (django) and want to dump some data from Django into a fixture file (JSON), so I try this: docker-compose run --rm django ./manage.py dumpdata core.Setting > setting.json It fails spectacularly: Traceback (most recent call last): File "./manage.py", line 20, in <module> main() File "./manage.py", line 16, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked … -
Is it possible to change the status of filefield in admin - DJANGO
I'm new with django and I was wondering if it is possible to change the status Currently(see the pic) of a filefield to other things like maybe: all, list... Because currently only return the last uploaded item. I have uploaded 5 file(File1, FIle2, .., File5) on a specific field, base on user ID, but it only return file5. I want to display all uploaded files and be able to get it via template. enter image description here I am able to see the complete list after the insertion in the db, via command prompt but only the last uploaded file is display in django admin. -
How to write a single file django app (version 4)
I'm trying to write a single file django app but the code that used to work in earlier versions is no longer working in version 4. I keep getting an error: "Segmentation Fault" Here's the code that I used: # app.py from django.conf import settings from django.core.wsgi import get_wsgi_application from django.http import HttpResponse from django.urls import path import os settings.configure() settings.DEBUG = True # settings.configure(DEBUG=True, ROOT_URLCONF=__name__, ALLOWED_HOSTS=['*'], ) def hello(request): return HttpResponse("Hello, World!") urlpatterns = [ path('', hello), ] application = get_wsgi_application() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(['manage.py', 'runserver']) $ python app.py runserver 8080 Segmentation fault -
View returning None and not returning a response object django
What I am working on is saving a new listing that is created by a given user on my commerce site, and displaying/redirecting the user to my index page. For some reason, the view keeps returning None and I'm not exactly sure why. Here is the code snippets below: views.py def createListing(request): if request.method == "POST": listing = NewListingForm(request.POST) if listing.is_valid(): creator = request.user title = listing.cleaned_data['title'] price = listing.cleaned_data['price'] description = listing.cleaned_data['description'] image = listing.cleaned_data['image'] category = listing.cleaned_data['category'] # Using .objects.create much simpler solution auction = Listing.objects.create( creator=creator, title=title, description=description, price=price, category=category, image=image, ) starting_bid = auction.price bid = Bid.objects.create( bid=starting_bid, user=creator, auction=auction ) return render(request, "auctions/index.html", { "message": "Listing Created Successfully." }) if request.method == "GET": return render(request, "auctions/create.html", { "create_form": NewListingForm() }) models.py class User(AbstractUser): pass class Comment(models.Model): comment = models.CharField(max_length=64) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comment") class Listing(models.Model): CATEGORIES = [ ('Toys', 'Toys'), ('Electronics', 'Electronics'), ('Lifestyle', 'Lifestyle'), ('Home', 'Home'), ('Fashion', 'Fashion'), ('Other', 'Other') ] creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator") title = models.CharField(max_length=64, blank=False, null=False) price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=True) description = models.CharField(blank=True, max_length=1064, null=True) category = models.CharField(max_length=64, blank=True, choices=CATEGORIES) image = models.URLField(default='https://user-images.githubusercontent.com/52632898/161646398-6d49eca9-267f-4eab-a5a7-6ba6069d21df.png') starting_bid = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) bid_counter = models.IntegerField(default=0) active = models.BooleanField(default=True) winner = … -
How to add a dependant drop-down in html form .using python
I want to create a dependant drop-down for my already existing drop-down in html form . Any one please recommend me a solution?? -
How to add two models in one page Django
When i try to add two models in one page it doesn't work and return the html code: How can i add to the one page two models? views.py def home(request): home_results = MainPageInfo.objects.all(); context_home = {'home_results': home_results} navigation_results_hone = Navigation.objects.all(); context_navigation_home = {'navigation_results_hone': navigation_results_hone} return render(request, 'index.html', context_home, context_navigation_home) models.py class Navigation(models.Model): title = models.FileField(upload_to='photos/%Y/%m/%d', blank = False, verbose_name=' SVG') class MainPageInfo(models.Model): title = models.CharField(max_length=255, verbose_name='Info') admin.py admin.site.register(Navigation) -
Getting data from MySQL table with 25+ columns using django model
I have a MySQL db (companies_data) with 4 tables (all_users, freq_user, special_users, products). all_users table has 27 columns and thousands of rows, I use that data to feed my machine learning algorithms. I'm using python, django rest_framework for backend. Now I wanted to get those data using django model and convert it into pandas dataframe so that I can predict and add the predictions to the other tables. Is there a easy way to get all the data using django model? Now I'm using raw SQL query with all the coloum names to get the data. -
Django permissions - how to prevent permissions_list from being sent to client
In my application, I found that all of the permissions list of all clients shown in page can be shown to the client. In the attached image, a user with role "assistant" can see the physician permissions. How can I prevent the permissions_list from being sent to client? -
Can Django's Replace be used to replace multiple substrings at once?
In Django, I can have queries that look like this: from django.db.models import Value from django.db.models.functions import Replace MyModel.objects.update(description=Replace("description", Value("old_1"), Value("new_1"))) MyModel.objects.update(description=Replace("description", Value("old_2"), Value("new_2"))) The first .update will go through the database, look for the "old_1" substring in the description field, and replace it with the "new_1" substring. The second .update call will do the same thing for the old_2 substring, replacing it with the new_2 substring. Can this be done in a single query? -
ManyToMany querying django
I have: Foo <=> FooGroup <=> Bar relation, where <=> stands for ManyToMany field. How do I retrieve all the Foos for a specific Bar instance? -
Django - How to set a value for Forms.HiddenInput() in Template
I currently have a form that has a field "id" that uses HiddenInput() as i do not want the user to fill in this input. I am trying to set this value "{{profile.id}}" for the "id" field inside the Django template but i cannot find anyway to do so. I have tried doing the following <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.value = {{profile.id}} }} ... <button type="submit">Submit</button> </form> and <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.initial = {{profile.id}} }} ... <button type="submit">Submit</button> </form> However, trying both of these does not work. If the "id" field is not a HiddenInput(), and just a regular TextInput(), i am able to set the value and the form is valid. Is there anyway to set a value for a HiddenInput() field? Here is my code: forms.py class CreateCommentForm(ModelForm): post = forms.CharField( widget=forms.HiddenInput() ) profile.html <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.initial = {{profile.id}} }} ... <button type="submit">Submit</button> </form> -
How to select multiple items in dropdown menu django?
I have django model: class at(models.Model): ... apostols = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='apostols', on_delete=models.CASCADE, null=True) ... Above and below apostols field are more fields which aren't important now. My form: class AtCreateForm(forms.ModelForm): ... class Meta: model = at fields = ['apostols'] widgets = { 'apostols': forms.widgets.TextInput(attrs={'class': 'form-control', 'list': 'user-list', 'autocomplete': 'off', 'multiple': True}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['apostols'].queryset = User.objects.all() In this form, we have apostols field which we display in template: <form method="post"> {% csrf_token %} <input type="text" list="user-list" multiple> <datalist id="user-list"> {% for user in form.apostols.field.queryset %} <option value="{{ user.username }}">{{ user.username }}</option> {% endfor %} </datalist> <input type="submit" value="Submit"> </form> This is how it works now. This form actually works as intented, but I want to be able to select multiple users. At best, it would work like on stackoverflow.com the tag-select section when you select more tags. -
Access list of field values for a list of related objects Django
I have a Django project where each Bid model object has a foreign key on an Event and a User along with some other information. The Event has a foreign key on a Post. I want to be able to test whether the current user is in the list of bids associated with an event using Django's frontend logic. I can use: {% for event in post.events.all %} {% for bid in event.bids.all %} {% if bid.bidder.pk == user.pk %} You have bidded on this event {% else %} You have not bidded on this event {% endif %} {% empty %} no bids on this event {% endfor %} {% endfor %} to test for this generally, but I only want one message to be printed for the user to see. I was hoping to do something more like: {% if user.pk in event.bids.all.bidder %} or (extending from the use of the for loop): ... {% if bid.bidder.pk == user.pk %} {% var bidded = True %} {% else %} {% var bidded = False %} ... I've heard of adding properties to my model for this sort of thing but I wanted to see if there was some … -
How to do a django multi-multi-selection form field
I have a django form where in a choice field the users can not only select more values but also select more combinations of values , for example: option1 option 2 and option 3 option 2 and option 4 here we have three combinations, the first one of one value (option1), the others of two values. How can I do that? Maybe I can use a M2M field with a through table where to associate at each option the combinations in which appear like this: option1: combination 1 option2: combination 2 and combination 3 option3: combination 2 option4: combination 3 I'm not sure the through table can have an undetermined number of combinations. Maybe there's a better way. Also any help on how to actually realize it will be appreciated because the widget allows only one combination. -
Parsing Complex JSON To Class (AttributeError: 'list' object has no attribute 'get')
(Sorry about the long but this is minimal to reproduce the error) I have been searching for the same error for a while but have not been able to find a solution. My aim is to parse the JSON data to classes so that it is easier for me to map it to a db schema and store the data in the database. I am using django and I am pretty new to learning it. Any guidance is very helpful My Attempt here. This link includes the JSON as well. ERR -> _CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = [CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalent.from_dict( y) for y in obj.get("CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents")] Entire code @dataclass class Period: instant: str startDate: str endDate: str @staticmethod def from_dict(obj: Any) -> 'Period': _instant = str(obj.get("instant")) _startDate = str(obj.get("startDate")) _endDate = str(obj.get("endDate")) return Period(_instant, _startDate, _endDate) @dataclass class Segment: dimension: str value: str @staticmethod def from_dict(obj: Any) -> 'Segment': _dimension = str(obj.get("dimension")) _value = str(obj.get("value")) return Segment(_dimension, _value) @dataclass class ShareBasedCompensation: decimals: str unitRef: str period: Period value: str @staticmethod def from_dict(obj: Any) -> 'ShareBasedCompensation': _decimals = str(obj.get("decimals")) _unitRef = str(obj.get("unitRef")) _period = Period.from_dict(obj.get("period")) _value = str(obj.get("value")) return ShareBasedCompensation(_decimals, _unitRef, _period, _value) @dataclass class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalent: decimals: str unitRef: str period: Period value: str @staticmethod def from_dict(obj: … -
Is there a way to check (from code) if django migrations haven't been executed yet?
with: ./manage.py showmigrations one sees the list of executed and pending migrations. I'd like to get this list (or number of migrations) at runtime so that I can expose it via a monitoring tool to see if any migrations failed. I checked the internals, but can't find any way to expose this for now. -
REST Framework applicability
There is Django, which allows you to create an application in the app of html pages. And there is an addition to Django - Django REST Framework, which allows you to implement the interface in the form of a REST API and receive JSON on GET, POST ... requests. So the question is, do I understand correctly that these two technologies are usually combined with each other in one application and the application is initially written in simple Django so that everything works, and then they supplement the Django REST Framework to add an additional interaction interface? I don't know anything about this topic, please help me. -
Problem with connecting Django, Celery, Redis to Azure Cache for Redis
I have an application where I am using django-celery-beats and django-celery-results libraries. I've configured everything and it works on my local machine but when I want to connect to Azure Cache for Redis then I get Error 11001 connecting to <app-name>.redis.cache.windows.net.redis.redis.cache.windows.net:6380. getaddrinfo failed.. I guess that it has something to do with CELERY_BROKER_URL and CELERY_RESULT_BACKEND in my settings.py file, however I can't find my mistake: This is what I have in my settings: CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://redis:6379") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_RESULT_EXTENDED = True os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" my keys in my env file look like this: CELERY_BROKER=redis://<PRIMARY_KEY>@<HOST_NAME>:6379 CELERY_BACKEND=django-db What am I doing wrong in my settings? I want to use Redis for celery tasks like this one: @app.task(bind=True) def hello_world(self): print(f'Hello world!') -
Datepicker in Django and update tables with jquery or without
Good good evening! I've been thinking for a few days now and using different options to solve the problem - updating the table when a date interval is selected. I have a table and a form to display data and a calendar. I'm taking two different values from a calendar and trying to update the data in a table. But nothing happens to me. I would be very grateful if you manage to at least suggest something to find an error. Save me please. Maybe you will offer a more simplified version without using jquery - I will be very grateful. models from django.db import models class EmployeeModel(models.Model): empid = models.IntegerField(primary_key=True) empname = models.CharField(max_length=50) salary = models.IntegerField() joindate = models.DateField() class Meta: db_table = "employee" forms from datetime import date from django import forms from .models import * today = date.today() class StockHistorySearchForm(forms.ModelForm): start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) class Meta: model = EmployeeModel fields = ['start_date', 'end_date'] views from django.shortcuts import render from django_filters.views import FilterView from django_tables2 import SingleTableMixin # Create your views here. from django.http import HttpResponse from . import models from .models import EmployeeModel from .forms import StockHistorySearchForm def showresults(request): header = "HYSTORY DATA" queryset = … -
How to delete duplicate rows from a table using Django ORM?
I have a database table bad_reviews and a corresponding Django model BadReviews. I want to delete duplicate records based on the fields client_id, survey_id, text, rating, privacy_agreement. I've come up with this query which works: SELECT br.* FROM bad_reviews br JOIN ( SELECT client_id, survey_id, text, rating, privacy_agreement, COUNT(*) FROM bad_reviews GROUP BY client_id, survey_id, text, rating, privacy_agreement HAVING count(*) > 1 ) dupes ON br.client_id = dupes.client_id AND br.survey_id = dupes.survey_id AND br.text = dupes.text AND br.rating = dupes.rating AND br.privacy_agreement = dupes.privacy_agreement ORDER BY br.client_id, br.survey_id, br.text, br.rating, br.privacy_agreement, br.id How to rewrite it using Django ORM?