Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch container keeps exiting with these logs
I have a docker container with elasticsearch in it. I think when too much requests is sent to my server this container crashes (exits). Could you approve that this is because of the pressure on server? As we see in logs: Logs Thanks in advance! -
How to show the list_display feature in Inline admin in django?
class CartItemInline(admin.StackedInline): model = CartItem class CartInlineAdmin(admin.ModelAdmin): inlines = [ CartItemInline, ] admin.site.register(Cart, CartInlineAdmin) Trying to display some extra fields in Cart Admin Model. How to do that? -
rabbitmq.conf consumer_timeout not working in docker
I'm trying to execute a longer task with celery, so to test I made a sample task sleep for 5 minutes and set the rabbitmq.conf file with a single line containing consumer_timeout = 10000 expecting the task to fail with precondition error after 10seconds(or at least after 60 seconds as per this answer), but it never did. The task completes after 5mins. I can see the rabbitmq.conf file shows up on top of logs(which I think it means it loaded the file successfully??) main_rabbitmq | Config file(s): /etc/rabbitmq/rabbitmq.conf main_rabbitmq | /etc/rabbitmq/conf.d/10-default-guest-user.conf My Dockerfile: FROM rabbitmq:3.9.13-management # Define environment variables. ENV RABBITMQ_USER user ENV RABBITMQ_PASSWORD password ENV RABBITMQ_PID_FILE /var/lib/rabbitmq/mnesia/rabbitmq COPY ./myrabbit.conf /etc/rabbitmq/rabbitmq.conf ADD init.sh /init.sh RUN chmod +x /init.sh # Define default command CMD ["/init.sh"] The init.sh file is similar to this. -
Django set initial pre-filled field value
I have two models: class Budget(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField(default=now) datecompleted = models.DateTimeField(blank=True, null=True) class Meta: ordering = ['-date'] def __str__(self): return self.name class Expenses(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) budget = models.ForeignKey(Budget, on_delete=models.CASCADE, related_name='budget_expense') category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateField(default=now) def __str__(self): return self.name class Meta: ordering = ['-date'] and my Form as follow class ExpenseForm(forms.ModelForm): date = forms.DateTimeField( widget=forms.widgets.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}), label='Data', input_formats=['%d/%m/%Y %H:%M']) class Meta: model = Expenses fields = ('name', 'quantity', 'budget', 'category', 'date') and now I trying to create an instance of Expense with pre-filled (existing) Budget instance with below code: def expense_add(request, pk): if request.method == 'GET': budget = get_object_or_404(Budget, pk=pk) form = ExpenseForm(initial={'budget': budget.name}) return render(request, 'budget/expense-create.html', {'form': form}) else: form = ExpenseForm(request.POST or None) if form.is_valid(): form.save() return redirect('list') return render(request, 'budget/expense-create.html', {'form': form}) but, as you may guess there is nothing in budget field inside my formfield. Please help. Thank you all! -
How to can change the format of date from year-month-date to date-month-year?
Am new in Django so any help will be appreciated, I have a model that contain 3 fields , one of them is date , i want to change the display of date in Django Admin(now it's 2022-05-20 but i want it to be 20-05-2022). How i can do that please ! this is my models.py: class reports(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project_name = models.CharField(verbose_name="Project name", max_length=60) date = models.DateField(verbose_name="Date", default=date.today) def __str__(self): return str(self.user) and this is my admin.py: class reportsAdmin(admin.ModelAdmin): @admin.display(description='date') def admin_date(self, obj): return obj.date.strftime('%d-%m-%Y') list_display = ('user', 'project_name', 'admin_date') admin.site.register(reports, reportsAdmin) and in my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False USE_TZ = True but nothing work , still display to me in format 2022-05-20(year-month-date). I need to change to date format because i need to render a html to a pdf(xhtml2pdf) and display all fields including the date that should be with the format date-month-year.( that i will get it from the models Table) so How i can correctly change the format date to be date-month-year in Django admin??? -
Can you make a many-to-many field that only selects specific objects from the model
So I'm currently developing an e-commerce store, where I have a model called OrderItem and a model called Order, the OrderItem contains a BooleanField that tells you whether that item has been ordered or not. The Order contains a many-to-many field to OrderItem to show you what items you have ordered, but the problem is that it also selects the items where ordered=True. Is there any way I can have my many-to-many field only select the items where Ordered=False -
Form not submitting CSRF token missing although it is in rendered html
I'm getting a "CSRF token missing" error, when submitting a form in Django. I'm using django-crispy-forms in combination with htmx. The form is rendered via render_crispy_form: def SwapFormView(request, partialform): ctx = {} ctx.update(csrf(request)) mitglied = model_to_dict(request.user.mitglied) if request.method == 'POST': # do form things return HttpResponse("""POST""") else: form = ChangeDataForm( initial=mitglied, partialform=partialform, ) html = render_crispy_form(form, helper=form.helper, context=ctx) return HttpResponse(html) My helper is contructed like this: def __init__(self, *args, **kwargs): super(ChangeDataForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'change-form' self.helper.attrs = { 'hx-post': reverse('back-to-same-url'), 'hx-target': '#change-form', 'hx-swap': 'outerHTML', } self.helper.add_input(Submit('submit', 'absenden')) The thing is, that as soon as I change the helper to a 'normal' POST-Request it works - but I need this to be done via HTMX to only change out the specific parts in the DOM. Weirdest thing for me is, that the token is rendered into the final html of the form: <form hx-post="/profil/nameform/" hx-swap="outerHTML" hx-target="#change-form" id="change-form" method="post" enctype="multipart/form-data" class=""> <input type="hidden" name="csrfmiddlewaretoken" value="token-value"> <label for="id_title" class="">Titel</label> <input type="text" name="title" value="Hau" maxlength="50" class="textinput textInput form-control" id="id_title"> <label for="id_first_name" class=" requiredField">Vorname<span class="asteriskField">*</span> </label> <input type="text" name="first_name" value="Test" maxlength="50" class="textinput textInput form-control" required="" id="id_first_name"> <label for="id_last_name" class=" requiredField">Nachname<span class="asteriskField">*</span></label> <input type="text" name="last_name" value="aBVIpzRJoBKP" maxlength="50" class="textinput textInput form-control" required="" id="id_last_name"> … -
Calling a model method from url parameter
model method: def category_name_en(): return "categoryname" urls: path('<str:region>/<slug:category>/', views.category, name="category_view") template: {% for iteration, article in results_main %} . <a href="{% url 'category_view' region=article.region category=article.category_name_en %}"> . {% endfor %} stack trace: NoReverseMatch at /search/ Reverse for 'category_view' with keyword arguments '{'region': 'en', 'category': ''} The method does not return anything ,so I'm guessing it's either a syntax problem or django does not allow calling methods like that. I am hoping I can resolve this without adding a new field to the model. -
How to calculate numbers of days between two dates and subtract weekends DJANGO MODELS
hope you're all fine! I have a model called Vacation and I'm struggling with one field: days_requested, this field is the number days from vacation_start and vacation_end, it works and gives me an integer as result. The problem I'm facing now is that I need to subtract the weekends (or not count them). What I have: vacation_start = '2022-05-20' vacation_end = '2022-05-24' days_requested = 5 What I'm trying to have: vacation_start = '2022-05-20' vacation_end = '2022-05-24' days_requested = 3 #21/05 and 22/05 are weekends Vacation Models: class Vacation(models.Model): department = models.ForeignKey( 'departments.Department', on_delete=models.SET_NULL, null=True) responsible = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='responsible_vacation') status = models.CharField( max_length=20, choices=STATUS_CHOICES_VACATIONS, default='open') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='created_by_vacation') vacation_start = models.DateField(blank=False) vacation_end = models.DateField(blank=False) days_requested = property( lambda self: (self.vacation_end - self.vacation_start).days + 1 ) def __str__(self): return str(self.created_by.first_name + ' ' + self.created_by.last_name) I have tried: days_requested = property( lambda self: [(self.vacation_start + datetime.timedelta(days=i)).date() for i in range(0, (self.vacation_end - self.vacation_start)) if (self.vacation_start + datetime.timedelta(days=i)).weekday() not in [5, 6].days()]) But I get the following error: 'datetime.timedelta' object cannot be interpreted as an integer And as I perform operations with the amount of days asked I need to … -
AutocompleteSelect broken after moving from django 2.2 to django 3.2
Hello :) After upgrading Django version to 3.2, widget AutocompleteSelect that I use in django admin panel (to have a drop-down from which I can choose an object) is broken. The error I see is AttributeError at /admin/demand/ 'QuerySet' object has no attribute 'name' Request Method: GET Request URL: http://localhost:8000/admin/demand/ Django Version: 3.2.13 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'name' Exception Location: /home/django-app/env/lib/python3.8/site-packages/django/contrib/admin/widgets.py, line 412, in build_attrs Python Executable: /home/django-app/env/bin/python3 Python Version: 3.8.10 Python Path: ['/home/django-app/testsite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/mb/proj/usun/django-app/env/lib/python3.8/site-packages'] Server time: Fri, 20 May 2022 10:13:27 +0000 Error during template rendering In template /home/django-app/testsite/polls/templates/admin/question_export.html, error at line 18 'QuerySet' object has no attribute 'name' 11 12 {% block content %} 13 <div id="content-main"> 14 <p>Select question to export:</p> 15 <form method="post" enctype="multipart/form-data"> 16 {% csrf_token %} 17 <table> 18 {{form.as_table}} 19 </table> 20 <div class="submit-row"> 21 <input type="submit" value="Export Question" /> 22 </div> 23 </form> 24 </div> 25 {{form.media}} 26 {% endblock %} 27 AutocompleteSelect inherits from AutocompleteMixin When I compare AutocompleteMixin for django 3.2 and django 2.2 https://github.com/django/django/blob/3.2.13/django/contrib/admin/widgets.py#L410-L412 https://github.com/django/django/blob/2.2.7/django/contrib/admin/widgets.py#L411 I see that they added new attributes 'data-app-label': self.field.model._meta.app_label, 'data-model-name': self.field.model._meta.model_name, 'data-field-name': self.field.name, in django 3.2 but there is no name on self.field and probably … -
Django Graphene, order data returned nested response
I have two table that contains data regarding orders and data regarding products in those orders. I would like to return the data from the products table but alphabetical order. schema # region Purchase Orders class PurchasesProducts(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders_products class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {} connection_class = ArtsyConnection class PurchasesQuery(ObjectType): purchases = ArtsyConnectionField(Purchases) @staticmethod def resolve_purchases(self, info, **kwargs): return purchase_orders.objects.filter(user_id=info.context.user.id).all().order_by("-date") purchasesSchema = graphene.Schema(query=PurchasesQuery) # endregion The purchase order data that is return is ordered correctly but date descending. However the data that is returned for the products in a order is not order by anything. I would like to order the products but name alphabetically. response ... "edges": [ { "node": { "id": "", "cmOrderId": "", "username": "", "date": "2022-04-28T20:16:05", "articles": 10, "merchandiseValue": "", "shippingValue": "", "trusteeValue": "", "totalValue": "", "cardMarketPurchaseOrdersProductsOrderId": [ { "id": "", "productId": "", "productName": "Yasharn, Implacable Earth", "productNumber": "148", "quantity": 1, "foil": false, "condition": "NM", "language": "ENG", "cost": "", "status": "INCOMING" }, { "id": "", "productId": "", "productName": "Magmatic Channeler", "productNumber": "240", "quantity": 3, "foil": false, "condition": "NM", "language": "ENG", "cost": "", "status": "INCOMING" }, ... -
EDITING ONE FOR ALL
how to make it so that if you change the value from true to false or vice versa in one place, all others change. class Ralevant default is True class Rooms default is True class Registration value changes and if in the registration class you change from true to false, then the Room class and Ralevant should also change from django.contrib.auth.models import User import datetime class Ralevant(models.Model): bool_roo = models.BooleanField(default=True) def __str__(self): return f'{self.bool_roo}' year=datetime.datetime.now().year month=datetime.datetime.now().month day = datetime.datetime.now().day class Rooms(models.Model): room_num = models.IntegerField() room_bool = models.ForeignKey(Ralevant, on_delete=models.CASCADE, related_name='name1') category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField(default=datetime.datetime(year=year,month=month,day=day+1,hour=12,minute=00,second=00)) guest_count = models.IntegerField() room_bool = models.ForeignKey(Ralevant, on_delete=models.CASCADE, related_name='name2') def __str__(self): return self.rooms,self.last_name,self.first_name -
How to block external requests to a NextJS Api route
I am using NextJS API routes to basically just proxy a custom API built with Python and Django that has not yet been made completely public, I used the tutorial on Vercel to add cors as a middleware to the route however it hasn't provided the exact functionality I wanted. I do not want to allow any person to make a request to the route, this sort of defeats the purpose for but it still at least hides my API key. Question Is there a better way of properly stopping requests made to the route from external sources? Any answer is appreciated! // Api Route import axios from "axios"; import Cors from 'cors' // Initializing the cors middleware const cors = Cors({ methods: ['GET', 'HEAD'], allowedHeaders: ['Content-Type', 'Authorization','Origin'], origin: ["https://squadkitresearch.net", 'http://localhost:3000'], optionsSuccessStatus: 200, }) function runMiddleware(req, res, fn) { return new Promise((resolve, reject) => { fn(req, res, (res) => { if (res instanceof Error) { return reject(res) } return resolve(res) }) }) } async function getApi(req, res) { try { await runMiddleware(req, res, cors) const { query: { url }, } = req; const URL = `https://xxx/api/${url}`; const response = await axios.get(URL, { headers: { Authorization: `Api-Key xxxx`, Accept: "application/json", … -
getting multi values from CSV to DB
I have a CSV file that goes like this 1,CA5D23 ,1410,111, Detail,"/assets/images/thumb/1537.png, /assets/images/thumb/1536.png" 2,C7F91E ,1525,109, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1452.png" 3,C4263D,1375,40, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1201.png" 4,C1595W,600,39, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1136.png" 5,C3145M,585,39, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/0216.png" the URLs for images are in the same cell. This is my model.py class Account(models.Model): code = models.IntegerField(__("code")) orbs = models.IntegerField(__("orbs")) price = models.IntegerField(__("price")) detail = models.CharField(__("detail"), max_length=255) image = models.ImageField(__("image")) I then import the CSV file to the DB using sqlite3.exe db.sqlite3 command. After that, I go to my index.html and write this code. <tr > {% for account in account %} <td style="text-align:center;vertical-align:middle;">{{account.code}}</td> <td style="text-align:center;vertical-align:middle;"><img src=" {% static 'assets/images/assets/orb.png' %} " width="22" height="22" style="padding-bottom:3px;" />{{account.orbs}}</td> <td style="text-align:center;vertical-align:middle;">{{account.price}}</td> <td style="text-align:center;vertical-align:middle;"><a target="_blank" href=" {% static 'account61f3.html?id_xml=001660' %} " ><input type="button" class="btn btn-success btn-sm" value={{account.detail}} ></a></td> </tr> <tr> <td colspan="5"> <div class="parent"><img class="img" title="" src=" {% static account.image.url %} "width="64" height="64"></div> </td> </tr> {% endfor %}<tr > Focus on the account.image.URL which shows only one image on the site or none if there's more than one URL. How can I include more than one URL to the DB and iterate over it without messing with the next cell? PS: I did try to change from ImageField to CharField and paste the whole image reference on … -
Djangochannelsrestframework websocket firstly connects and disconnect after a second [closed]
I'm trying to create websocket connection with djangochannelsrestframework. I tried all like in documentation and I got this error (venv) user@user-pc:~/Projects/igroteka$ daphne igroteka.asgi:application 2022-05-20 15:20:24,560 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2022-05-20 15:20:24,560 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2022-05-20 15:20:24,561 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2022-05-20 15:20:24,561 INFO Listening on TCP address 127.0.0.1:8000 127.0.0.1:40216 - - [20/May/2022:15:20:30] "WSCONNECTING /ws/" - - 127.0.0.1:40216 - - [20/May/2022:15:20:30] "WSCONNECT /ws/" - - 2022-05-20 15:20:30,569 ERROR Exception inside application: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Traceback (most recent call last): File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/utils.py", line 58, in await_many_dispatch await task File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/utils.py", line 50, in … -
Display join date and last_login in Django
I have User default Django User model to register user. I want to print user last_login and join_date on the template. And also I want to check if user is active or not. I want to check user active status like this, If user is currently using my website the status should be "Active" If User logged out Then status should be "Loged out" if it is possible please provide me solution for this as well I am filtering user data like this data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Model.py class Profile(models.Model): user = models.OneToOneField(User,default="1", on_delete=models.CASCADE) image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' -
Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct?
I installed django with django and got this eror in runtime: Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct? alongside manage.py: vue create frontend Default ([Vue 3] babel, eslint) cd frontend npm run serve list of files in frontend directory is: babel.config.js jsconfig.json node_modules package.json package-lock.json public README.md src vue.config.js npm --version 6.14.15 nodejs --version v10.19.0 node --version v14.17.6 npm list webpack-bundle-tracker └── webpack-bundle-tracker@1.5.0 pip install django-webpack-loader pip freeze django-webpack-loader==1.5.0 INSTALLED_APPS = ( ... 'webpack_loader', ... ) # vue.config.js const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true }) index.html {% load render_bundle from webpack_loader %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title></title> {% render_bundle 'app' 'css' %} </head> <body> <div class="main"> <main> <div id="app"> </div> {% endblock %} </main> </div> {% render_bundle 'app' 'css' %} </body> </html> -
KeyError 'some_field_for_form_a' is not found in FormB during concurrent requests
I am posting this because I am out of ideas. I have tried to find the cause of this issue for the last 2 years. Say I have 4 model admins: TabbedAdminMixin, ModelAdmin a: BasketAdmin b: ConsumerAdmin Normal Django ModelAdmin c: RoleAdmin d: BranchAdmin It took me veeeery long to be able to find a way to re-create this error but as of yesterday, I can easily re-create it by using locust to simulate concurrent requests. When I run locust with 5 concurrent users, each doing requests to /basket//change/ and /consumer//change/ I get a keyerror where render_tab_fieldsets_inlines want to create a, for example, BasketAdmin with fields from ConsumerAdmin's form and vice versa. When I run the same locust file on /role//change/ and /branch//change/ (vanilla django modeladmins) I don't get keyerrors. This happend locally with runserver and in production with uwsgi. Any help will be very much appreciated! -
How to get rid of pytz UnknownTimeZoneError in my Django logs?
I've deployed a Django Application on Windows Server 2022 and error logs are flooded with the following message: pytz.exceptions.UnknownTimeZoneError: 'Europe/Paris'\r, referer: https://my_server_url During handling of the above exception, another exception occurred I've checked my pytz installation and it seems to work just fine : # run Windows cmd as Apache service account python manage.py shell from django.conf import settings import pytz pytz.timezone(settings.TIME_ZONE) <DstTzInfo 'Europe/Paris' LMT+0:09:00 STD> settings.TIME_ZONE in pytz.all_timezones True I've tried to uninstall and reinstall my virtual environnement and upgrade/downgrade pytz, without success. I've no idea on how to investigate this problem furthermore and how to solve it. Here is the application setup : Apache 2.4.52 (built from sources) Python 3.10.4 Mod_wsgi 4.9.0 Django 3.2.9 pytz 2021.3 -
authenticate individual users using api keys or public/private key pairs for api calls in django rest framework
i need to provide authentication method for my users so they can interact with my api endpoints out of the client side (frontend) . something like developer authentication . i've made research and realized that api keys are not recommended for authenticating individual users . on the other hand using ssh key pairs are good approach but saving private keys in order to decrypt the public key message is a security breach . all i need is just to understand the concept of implementing such authentication methods and the flow of how to do it.do you have any suggestion , advice or resource so i can figure out how to implement it ? Thanks -
django-admin: why there is table list inside the table
In the django-admin page, When i click into File table, there are table list above my File data list. How can i unshow the list of table? -
How can I click on any of the categories in the list and be redirected to all active listings in that category? Django
Im working on a django project (im newb) and I`ve made a html page displaying a list of available categories. I want to make each a link and when the user clicks it he/she should be redirected to a list of active listings based on that category. I simply cannot understand how. Here is my code: models.py class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class Listings(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=128) description = models.CharField(max_length=822) price = models.FloatField() sold = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True, null=True, related_name="listings_category") categories = models.ManyToManyField(Category, blank=True, related_name="select_category") image_url = models.CharField(max_length=128,blank=True, null=True) def __str__(self): return f"{self.title}" urls.py path('category/', views.category, name="category"), path("listing/<str:listing_id>", views.listing, name="listing") views.py def category(request): cat = Category.objects.filter().values('category') category_id = Category.objects.filter().values('id') z = [] for c in category_id: z.append(c['id']) listing = Listings.objects.filter(category__in= z) categories = Category.objects.all() category = Category.objects.filter(id__in=z) print(category) return render(request, "auctions/category.html",{ "categories":categories, "category":category, "listing":listing }) def listing(request, listing_id): listing = Listings.objects.get(id=listing_id) user = request.user owner = True if listing.user == user else False category = Category.objects.get(category=listing.category) comments = Comments.objects.filter(listing=listing.id) watching = WatchList.objects.filter(user = user, listing = listing) if request.method == "POST": comment = request.POST["comment"] if comment != '': Comments.objects.create(user=user, listing=listing, comment=comment) return HttpResponseRedirect(listing_id) return render(request, "auctions/listing.html", { "listing": … -
How to fix Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed?
I created an application with a Django backend and an Angular frontend, I am trying to display the list of my fleet table with its information However I get this error my data is saved in the database but I have this error when I want to display them Html <div class="flotte-list"> <ul class="flottes"> <li *ngFor="let flotte of flottes"> <span class="badge">{{flotte.id}}</span> {{flotte.name}} {{ flotte.nb_engins}} <button class="delete" title="delete flotte" (click)="delete(flotte)">x</button> </li> </ul> </div> <div class="flotte-box"> <div class="flotte-form"> <div class="textbox"> <input #flotteName placeholder="Name"> </div> <div class="textbox"> <input #flotteNbengins placeholder="nb_engins" type="number"> </div> <div class="textbox"> <input #flottetest placeholder="nb_b" > </div> <div class="textbox"> <input #flottefichier placeholder="Type fichier" > </div> <input type="button" class="btn" value="Add flotte" (click)="add( flotteName.value, flotteNbengins.valueAsNumber, flottetest.value, flottefichier.value ); flotteName.value=''; flotteNbengins.value=''; flottetest.value=''; flottefichier.value=''; "> </div> </div> Component.ts getAllFlottes() { this.api.getAllFlottes() .subscribe(data => this.flottes = data) } add(name: string, nb_engins: number, calculateur: string, type_fichier: string){ name = name.trim(); if (!name) { return; } if (!nb_engins) { return; } calculateur = calculateur.trim(); if (!calculateur) { return; } type_fichier = type_fichier.trim(); if (!type_fichier) { return; } this.api.registerFlotte({name, nb_engins, calculateur, type_fichier} as Flotte) .subscribe(data => { this.flottes.push(data); }); } service.ts // GET Flottes getAllFlottes(): Observable<Flotte[]> { return this.http.get<Flotte[]>(this.base_url); } registerFlotte(flotte: Flotte): Observable<Flotte> { return this.http.post<Flotte>(this.base_url, flotte, { headers: … -
Differnece between Q, SearchVector and TrigramSimilarity
I am learning django at the moment and i cant understand the difference between Q, SearchVector and TrigramSimilarity. Which one should I use? -
django cannot annotate queryset in custom model manager
I seem to have some code that works when run manually in the shell, but not when run as part of a custom model manager method. Any hints on what I'm doing wrong? models.py: from django.db import models from django.db.models import Q, ExpressionWrapper class MyTag(models.Model): name = models.CharField(max_length=128, unique=True) class MyManager(models.Manager): def get_queryset(self): queryset = MyQuerySet(self.model, using=self._db).all() queryset.annotate( is_nice=ExpressionWrapper( Q(tags__name__in=["nice"]), output_field=models.BooleanField() ) ) return queryset class MyQuerySet(models.QuerySet): def nice(self): return self.filter(_is_nice=True) class MyModel(models.Model): objects = MyManager() #.from_queryset(MyQuerySet)() name = models.CharField(max_length=64) tags = models.ManyToManyField( MyTag, blank=True, related_name="models", ) This works (explicit y calling annotate): >>> from models.py import * >>> queryset = MyModel.objects.all() >>> queryset.annotate(is_nice=ExpressionWrapper(Q(tags__name__in=["nice"]), output_field=models.BooleanField()) >>> queryset.values_list("is_nice", flat=True) [True, False, ...] But this fails: >>> from models.py import * >>> queryset = MyModel.objects.all() >>> queryset.values_list("is_nice", flat=True) *** django.core.exceptions.FieldError: Cannot resolve keyword 'is_nice' into field. Choices are: id, name, tags