Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i use django filter with multiple value select
I want to filter my data based on city , how can i filter my data if the user choose more than one city using django filter class games(generics.ListAPIView): queryset = Game.objects.filter(start_date__gte=datetime.today()) serializer_class=GameSerializers filter_backends = [DjangoFilterBackend,filters.OrderingFilter] filterset_fields = ['id','city','level'] game model class Game(models.Model): city = models.CharField(max_length=255) gender = models.ForeignKey(Gender,on_delete=models.CASCADE) level = models.ForeignKey(Level,on_delete=models.CASCADE) host = models.ForeignKey(Host,on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() fees = models.IntegerField() indoor = models.BooleanField() capacity = models.IntegerField() age_from = models.IntegerField() age_to = models.IntegerField() description = models.CharField(max_length=255) earned_points = models.IntegerField() created_at = models.DateTimeField(default=django.utils.timezone.now) image = models.ImageField(upload_to="GameImage",null=True) history = HistoricalRecords() -
Django + Celery task never done
I'm trying to run the example app Django+Celery from official celery repository: https://github.com/celery/celery/tree/master/examples/django I cloned the repo, ran RabbitMQ in my docker container: docker run -d --hostname localhost -p 15672:15672 --name rabbit-test rabbitmq:3 ran celery worker like this: celery -A proj worker -l INFO When I try to execute a task: python ./manage.py shell >>> from demoapp.tasks import add, mul, xsum >>> res = add.delay(2,3) >>> res.ready() False I always get res.ready() is False. The output from worker notify that task is recieved: [2022-12-14 14:43:20,283: INFO/MainProcess] Task demoapp.tasks.add[29743cee-744b-4fa6-ba68-36d17e4ac806] received but it's never done. What might be wrong? How to catch the problem? -
Pythonanywhere - Error code: Unhandled Exception Django
it's my leaveitcafe_pythonanywhere_com_wsgi.py # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/leaveitcafe/Leave-it-Cafe/Leave_it_cafe' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Leave_it_cafe.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() enter image description here how to solve this error -
How to make a copy of Django FileField without reapplying upload_to directory path?
My Django Model contains the following: def photo_directory_path(instance, filename): return 'photos/{0}/foo-{1}'.format(instance.id, filename) photo = models.FileField(null=True, blank=True, editable=True, upload_to=photo_directory_path, max_length=500) Let's say I have an instance of this Model as oldModel, and I would to create a new instance and use the same photo. I don't want to store the photo again but have a reference to the same file: newModel = Model() newModel.photo = oldModel.photo newModel.save() However, this does not work as photo_directory_path will be applied again to the file name. How can I copy the FileField as "raw"? -
I have a datefield field in mysql and how do I know if it is null
using djangoenter image description here I want to create an if else block and make this data in mysql so that if it is empty, the button will not appear, but if it is not empty button will appear, I tried this, but it counts as full. -
How do I filter query objects by time range in Django
I've got a field in one model like: class Sample(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True) this is what it's looks like if saved: 2022-12-13 13:00:29.84166+08 2022-12-13 14:00:29.84166+08 2022-12-13 15:00:29.84166+08 Is it possible to filter that by range of time? maybe similar to this? Sample.objects.filter(created_at __range=["13:00", "15:00"]) -
Django select2 with autocomplete_fields to have a dynamic default value
I have a Product model and a HeadFlowDataset model. These two models are connected with a foreinkey relationship, in which one product can have many headflowdataset pairs. Their model codes are as below: class Product(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) ... # other fields in the model, not exactly related to this problem class HeadFlowDataSet(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) product = models.ForeignKey( Product, on_delete=models.CASCADE, ) head = models.FloatField() flow = models.FloatField() def __str__(self): return self.product.pump_name Every product can have up to 10-15 head-flow sets. And currently I'm using Django admin panel to populate my product database. On the other hand, there may be up to 1000 products in total. So when the admin is trying to add head-flow datasets, the process was a bit challenging to find the product name from the select menu that Django admin provides. So I used Django autocomplete_fields in the ModelAdmin as below so that the admin can at least search for the product name: class HeadFlowDatasetAdmin(admin.ModelAdmin): list_display = ( "product", "head", "flow", ) fields = ( "product", "head", "flow", ) autocomplete_fields = ["product"] def get_ordering(self, request): return [Lower("product__pump_name"), "head"] But this approach too is a bit frustrating to search … -
How to transmit Django variables to a Js file
As you can see in the code below, I have imported a <script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script> to my Index.html. But there are Django variables in that JS file. like: {{ sizes }} and {{ urlsPosts }}, they go from Views.py to the Index.html. Unfortunately Django doesn't see these variables in the JS file if I keep the JS as a separate file. If I copy paste the JS right to the HTML without separating - everything works well. How can I include these Django variables into the separate Js file? Index.html: <html> {% load static %} {% include 'head.html' %} <body> <header> </header> </body> <footer> <script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script> </footer> </html> Views.py: def index(request): posts = Post.objects.all() sizes = '' urlsPosts = '' for i in range(0, len(posts)): if i == len(posts): sizes = sizes + str(posts[i].thumbnail.width) + 'x' sizes = sizes + str(posts[i].thumbnail.height) urlsPosts = urlsPosts + posts[i].thumbnail.url else: sizes = sizes + str(posts[i].thumbnail.width) + 'x' sizes = sizes + str(posts[i].thumbnail.height) + ' ' urlsPosts = urlsPosts + posts[i].thumbnail.url + ' ' return render(request,'index.html',{'posts':posts, 'sizes':sizes, 'urlsPosts':urlsPosts) posts_lazy_loading.js: var images = document.getElementsByClassName('cover_main_page'), posts = document.getElementsByClassName('post'), descriptions = document.getElementsByClassName('description'), description_height = descriptions[0].clientHeight; post_content = document.getElementsByClassName('post_content'), loading = … -
Multi-Step form with every step depends on the data filled in previous step / first step in Django
I am struck on this for hours, I have a multi-step form, the structure of the form is like <form> <fieldset> <input>source airport</input> <input>destination airport</input> </fieldset> <fieldset> <!--Here I want to show airlines according to the data filled in the 1st fieldset, from the DATABASE--> </fieldset> <fieldset> <!--something here, which will depend on 1st fieldset filled data--> </fieldset> <fieldset> <!--something here, which will depend on 1st fieldset filled data--> </fieldset> </form> what I have done, Used JS to get the fields in the first fieldset by id and then send the data in Django view using AJAX and I was able to save data in DB. But, now the problem is that when next button is clicked to move to next fieldset, then page doesn't send the GET request And 2nd fieldset doesnt get populated according to the data filled in the 1st fieldset I am looking to get any help I can get and get this thing done. I am implementing this in Django. I am very much okay to provide more details regarding this to get help. -
Calling MPTTModel model that is child
I have 2 models, Lucrare and Deviz. Deviz is a MPTTModel and has ForeignKey reference to Lucrare. Deviz models will have this form: Chapter 1 -Subchapter 1 --SubSubchapter 1 ---Article 1 ---Article 2 ---Article 3 Chapter 2 -Subsubchapter1 --Article 1 --Article 2 And only the Chapter will have the foreignkey reference to Lucrare. models.py: class Lucrare(models.Model): name = models.CharField(default='',max_length=100,verbose_name="Name") class Deviz(MPTTModel): lucrare = models.ForeignKey(Lucrare, on_delete=models.CASCADE,default='',null=True) parent = TreeForeignKey('self', on_delete=models.CASCADE,null=True,blank=True) Name = models.TextField(default='',verbose_name="Name") Created a class based view for Lucrare views.py: class LucrareDetail(LoginRequiredMixin, DetailView): template_name = "proiecte/lucrare_detail.html" context_object_name = "lucrari" model = Lucrare def get_queryset(self, **kwargs): context = super().get_queryset(**kwargs) return context I do not understand how to use this part in the template so that I create a table with Deviz data referenced to my Lucrare model: {% load mptt_tags %} <ul> {% recursetree genres %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
why is the pip install django Why does it take so long? ''Installing collected packages" step?
I'm trying to pip install django but installation takes a long time "Installing collected packages" step? like 40 min $ python -m pip install django Collecting django Using cached Django-4.1.4-py3-none-any.whl (8.1 MB) Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, django -
How to execute django query from string and get output
I want to run a django query from a string and put the output into a variable i tried using exec('model.objects.all()') but i can't assign the output to a variable, i also tried using subprocess.run([sys.executable, "-c", 'model.objects.all()'], capture_output=True, text=True) but subrocess doesn't find the model -
how to reverse page after deleting any data in django?
i wanted to redirect my page to index after deleting row so i use ` return HttpResponseRedirect(reverse('index')) to reverse . i wanted thishttp://127.0.0.1:8000/indexbut it is showinghttp://127.0.0.1:8000/index/index` what is the proble please help me. this is my view.py ` def index(request): return render(request, "card/index.html") def delete(request, id): dishes = dish.objects.get(id=id) dishes.delete() return HttpResponseRedirect(reverse('index')) this is urls.py path('index', views.index, name="index"), path('check', views.check, name="check"), path('delete/<int:id>', views.delete, name='delete'), ` -
counter with date information from django with javascript
I have a project in django, I have a field called delivery_time in the database, this is a datetimefield. I want to take this value and use it in javascript to make a counter. The date I'm talking about comes as text in html, I can use it too. I don't know how to use a text written in html.  my code ss -
Ajax call for form
What is django-ajax-selects and how to use it? an example. I want to create a filter app that show filtered data as soon as possible when selected option from form selector. -
Django - Failed to load resource: the server responded with a status of 404 (Not Found)
I'm trying to deploy a Django app that works locally, but doesn't on my website. The Django index.html (template) is shown but the errors below are shown and no css / js is loaded. Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/js/main Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/css/style.css Lines I think are relevant in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'src.pages' ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] How I include the files in index.html template {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> </head> <body> <script src="{% static 'js/main.js' %}"></script> </body> </html> App structure is as follows web_app/ ├── src/ │ ├── config/ │ │ └── settings.py │ ├── pages/ │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ └── style.css │ │ │ ├── js/ │ │ │ │ └── main.js │ │ │ └── fonts/ │ │ ├── templates/ │ │ │ └── pages/ │ │ │ └── index.html │ │ ├── urls.py │ … -
Django template == condition on string doesn't work
I want to display in an email template some conditional informations but even if the {{ error }} confirms the value of my error is list index out of range , the condition is not applied and else is taken in account. I send to my (email) template this: views.py try: [...] except Exception as e: error_product_import_alert( {'order_increment_id': order_increment_id, 'product': item['sku'], 'error': e, 'request': request}) error_product_import_alert() def error_product_import_alert(context): product = context['product'] order_id = context['order_increment_id'] error = context['error'] sujet = f' Anomalie : Import SKU {product} ({order_id}) impossible ({error})!' contenu = render_to_string('gsm2/alerts/product_import_ko.html', context) [...] email template <p>--{{ error }}--</p> {% if error == 'list index out of range' %} <p><strong>Le produit est introuvable dans la base.</strong></p> {% else %} <p><strong>Erreur inconnue : veuillez contacter l'administrateur.</strong></p> {% endif %} Maybe my error is so big that I even can't see it. Is there one ? -
How do I visualize NetCDF files in Python using the Django framework?
How to visualize the netCDF files in python using Django Framework? I tried using Folium map, but it doesn't support JavaScript. JavaScript is required to interact with map, like on-click function, pagination, etc. While using JavaScript, I need to go with conversion of netCDF File to GEOJSON file. But, it takes lots of storage space. Is there any alternate method to proceed with my requirement? -
Django ORM LEFT JOIN SQL
Good afternoon) Please tell me, there is a foreign key in django models in the Foreign Key, when creating a connection, it creates a cell in the _id database by which it subsequently performs JOIN queries, tell me how to specify your own cell by which to do JOIN, I can't create tables in an already created database I need a banal simple LEFT JOIN without connection with _id. Or specify another cell in the database for JOIN instead of _id, for example CastleModels.id = ClanModels.hasCastle class ClanInfoModels(models.Model): clan_id = models.IntegerField() name = models.CharField(max_length=80) class Meta: db_table = 'clan_subpledges' managed = False class ClanModels(models.Model): clan_id = models.IntegerField() hasCastle = models.IntegerField(primary_key=True) class Meta: db_table = 'clan_data' managed = False class CastleModels(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=11) class Meta: db_table = 'castle' managed = False ordering = ['id'] need sql query = SELECT castle.name, castle.id, clan_subpledges.name as 'name_clan' FROM castle LEFT JOIN clan_data ON clan_data.hasCastle = castle.id LEFT JOIN clan_subpledges ON clan_subpledges.clan_id = clan_data.clan_id -
Weather Api Right/wrong city filter not working
Openweather api call replay same message with differnt 'cod' 200 (200 for city that exist) or 404(404 for city does not exist). it was easy to set if condittion if cod == 200: form.save() else: print("City does not exist") but api.weatherapi.com gving me two differnt reply for city that exist or city that not exist when i am trying to add Wrong city i am geting this replay from api. {'error': {'code': 1006, 'message': 'No matching location found.'}} when i am writing right city name i am geting this reply from api. {'location': {'name': 'Texas City', 'region': 'Texas', 'country': 'United States of America', 'lat': 29.38, 'lon': -94.9, 'tz_id': 'America/Chicago', 'localtime_epoch': 1670842210, 'localtime': '2022-12-12 4:50'}, 'current': {'last_updated_epoch': 1670841900, 'last_updated': '2022-12-12 04:45', 'temp_c': 18.9, 'temp_f': 66.0, 'is_day': 0, 'condition': {'text': 'Overcast', 'icon': '//cdn.weatherapi.com/weather/64x64/night/122.png', 'code': 1009}, 'wind_mph': 9.4, 'wind_kph': 15.1, 'wind_degree': 60, 'wind_dir': 'ENE', 'pressure_mb': 1016.0, 'pressure_in': 30.01, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 93, 'cloud': 100, 'feelslike_c': 18.9, 'feelslike_f': 66.0, 'vis_km': 11.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 10.1, 'gust_kph': 16.2, 'air_quality': {'co': 260.3999938964844, 'no2': 17.0, 'o3': 1.100000023841858, 'so2': 6.5, 'pm2_5': 4.0, 'pm10': 5.800000190734863, 'us-epa-index': 1, 'gb-defra-index': 1}}} How can i use code 1006 to filter out city that exist or not exist before … -
'Read' status of the message in Django chat built with django-channels
How can I show read or unread status of the message for the user? I thought about store IDs of messages seen by user - too much info to store. Maybe store tuple(first_seen_message, last_seen_message) - much less memory in use, but we have many chatrooms and direct messages - all messages get IDs in common pull. How to do it? I haven't tried anything in particular, bc I have no idea howto :D -
My if statement is not working, I am using django and python and I know the if statement is true
I am working with django and python trying to create an application, for some reason the following if statement is not working, but I know it should work because the if statement is true. `{% if reservation_breakfast %} {% for zone in zones %} <table class="table"> <thead class="thead-dark"> <tr> <td></td> <td></td> <td>{{zone.place_of_table}}</td> <td></td> <td></td> </tr> </thead> <tbody class="table-group-divider"> {% for x in reservation_breakfast %} <p>{{x.table_place_preference}} == {{zone.place_of_table}} ?</p> {% if zone.place_of_table == x.table_place_preference %} <tr> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> {% endif %} {% endfor %} </tbody> </table> {% endfor %} {% endif %}` The output is the following: It should print the table line with the words Mark Otto and @mdo right? So does anyone can tell me what am I doing wrong? I am expecting to know what am I doing wrong... -
Django-App: IIS Permission for Network Harddrive
I have a Django app that displays files in a folder via "os.listdir" in my Django app. However, the files are on a network hard drive with the drive letter "W". When I start Django as a development environment, this also works. I have deployed Django via IIS but due to lack of permissions, presumably these files cannot be displayed. I then added the user "IIS AppPool\DefaultAppPool" in the "Security" tab for the entire hard drive for testing with "Full Access" but still my Django app cannot read this folder on the external hard drive. Which user rights do I have to set so that Django can access a network hard disk via IIS to read data there? -
Django: combine values of two models fields into one new model field (3 different models)
I have three different models. class A(models.Model): department = models.CharField(max_length=50, blank=False, null=False) class B(models.Model): state = models.CharField(max_length=50, blank=False, null=False) class C(models.Model): db_name = models.CharField(max_length=50, blank=False, null=False) @property def db_name(self): return f"{A.department}_{B.state}" I would like to auto populate the db_name column as follow "DEPARTMENT_STATE". I thought that db_name would do this, but for some reason it isn't working at all, and I don't get why? There is relation on ID between model A -> B, A -> C (but for some reason the values are NULL in the table of model B and C). Does someone know how I can auto populate db_name which requires not manual/user input? -
Pytest parametrized django_db mark required
I am writing unit tests for a function. In parameterize, I am generating tests cases by making some DB calls when required. def my_function(tokens): pass def generate_tokens_helper(): tokens = list(MyTable.objects.values()) return tokens @pytest.mark.django_db class TestMyClass: @pytest.mark.parameterize( "tokens, expected_result", [ ( generate_tokens_helper(), True ) ], ) def test_my_function(self, tokens, expected_result): assert expected_result == my_function(tokens) This is generating the following error: test_file.py:47: in <module> class TestMyClass: test_file.py:17: in TestMyClass generate_token_helper(), test_file.py:5: in generate_token_helper items = list(MyTable.objects.values()) spm/accessors/variable_accessor.py:182: in get_all_operators operator_list = list(qs) venv/lib/python3.9/site-packages/django/db/models/query.py:269: in __len__ self._fetch_all() venv/lib/python3.9/site-packages/django/db/models/query.py:1308: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.9/site-packages/django/db/models/query.py:53: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py:1154: in execute_sql cursor = self.connection.cursor() venv/lib/python3.9/site-packages/django/utils/asyncio.py:26: in inner return func(*args, **kwargs) venv/lib/python3.9/site-packages/django/db/backends/base/base.py:259: in cursor return self._cursor() venv/lib/python3.9/site-packages/django/db/backends/base/base.py:235: in _cursor self.ensure_connection() E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I have already marked TestMyClass with django_db but I am still getting this error.