Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check isSubsest in django orm
I'm using django rest framework. and from these models, I want to get a possible cooking queryset using ingredients in fridge. I want to get cookings that all ingredients in fridge. How can I filter? please help.. class Ingredient(models.Model): name = models.CharField() class Cooking(models.Model): name = models.CharField() class Fridge(models.Model): ingredient = models.ForeignKey(Ingredient) class CookingIngredient(models.Model): cooking = models.ForeignKey(Cooking) ingredient = models.ForeignKey(Ingredient) -
How to manually audit log in django-auditlog
How do you manually audit log in django-auditlog? There is no example in the documentation and there is still very limited sources about this. Should the model be registered? What i am really trying to achieve is to manually log data so that i can add additional data like remarks. But i am having problems in using the LogEntry.objects.log_create(). Thanks in advance. -
Passing Two Parameters Through URL in Django
I'm having difficulty passing parameters to a URL in Django. I am attempting to pass two parameters from calander.html -> succ.html. The URL looks like this: Click for Image of URL In that image I want to pass 11:00am as the Start Time and 12:00pm as the end Time. My urls.py file contains: path('calender', views.calender, name='calender'), .... .... path('succ', views.succ, name='succ'), My views.py file contatins: def calender(request): return render(request, 'calender.html') def succ(request): return render(request, 'succ.html') I attempted to add parameters to the views.py file and then add a new path in urls.py after watching several videos and I was never able to find a solution since I am passing two parameters (StartTime and EndTime). -
how to set a default value for a field model to another model field
here are models.py file class album(TimeStampedModel): #album_artist = models.ForeignKey(artist, on_delete=models.CASCADE) album_name = models.CharField(max_length=100, default="New Album") #released_at = models.DateTimeField(blank=False, null=False) #price = models.DecimalField( # max_digits=6, decimal_places=2, blank=False, null=False) #is_approved = models.BooleanField( # default=False, blank=False) #def __str__(self): # return self.album_name class song(models.Model): name = models.CharField(max_length=100,blank=True,null=False) album = models.ForeignKey(album, on_delete=models.CASCADE,default=None) # image = models.ImageField(upload_to='images/', blank = False) # thumb = ProcessedImageField(upload_to = 'thumbs/', format='JPEG') # audio = models.FileField( # upload_to='audios/', validators=[FileExtensionValidator(['mp3', 'wav'])]) # def __str__(self): # return self.name I want to make the default value of the song name equal to the album name which i choose by the album Foreignkey. (in the admin panel page) any help ? -
url is showing in page not found error in django?
I created an endpoint and registered it in urls.py. When I try to hit the endpoint I get a 404 error but on the 404 page the url is shown as one of the patterns django tried to match. Stumped. api.py class UpdateLast(viewsets.GenericViewSet, UpdateModelMixin): def get(self): return XYZModel.objects.all() def partial_update(self, request, *args, **kwargs): if request.user.is_superuser: with transaction.atomic(): for key, value in request.data: if key == 'tic': XYZModel.objects.filter(ticker=request.data['tic']).filter(trail=True).update( last_high=Case( When( LessThan(F('last_high'), request.data['high']), then=Value(request.data['high'])), default=F('last_high') ) ) urls.py (this is inside the app) router = routers.DefaultRouter() router.register('api/dsetting', DViewSet, 'dsetting') router.register('api/update-last-high', UpdateLast, 'update-last-high') urls.py (main) urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), When I hit the end-point api/update-last-high I get a 404 page. On that page the exact end-point is shown as a pattern that django tried to match. ^api/update-last-high/(?P[^/.]+)/$ [name='update-last-high-detail'] ^api/update-last-high/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='update-last-high-detail'] -
Java input ending in a Django regex pattern gets NoReverseMatch error [duplicate]
I just got this NoReverseMatch error: 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)\\Z']. That "\\Z" on the end is NOT part of my code. I plugged it into regex101 with my string and got no match. Then I took the "\\Z" off the end and instantly my string matched. According to regex101, "\\Z" is an escaped literal forward slash and a literal capital Z. These characters are nowhere in my code. They're not in views, urls, get_absolute_url, or the template. Googling for 'django url slug regular expression pattern "\\Z"' got nothing helpful. All I did for this in my url pattern was "<slug:slug>", so I assume Django actually wrote the pattern? But I've never seen this on Django patterns before, either. How do I get rid of this and keep it from making my regex not match? Thanks. -
Django Shell Command Does Not Execute For Loop
I have a Django project going on, containing some functions and creating/updating a database. From time to time, I need to update the staticfiles in the project therefore I created a .py file in the same folder as the project named updatefiles.py I am running the script as python manage.py shell <updatefiles.py. Inside this file there is a for loop but for some reason it does not execute the for loop. I have tried even with a simple for loop such as below but it doesn't execute that one as well. Anyone has any ideas? fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) The output is: (InteractiveConsole) >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> ... ... ... ... ... ... ... ... ... ... ... now exiting InteractiveConsole... Anyone has any ideas? -
How can I implement authentication in Django
I am new to Django. I am going to build simple register and login fullstack application by using React and Django. My problem is when I received register request with form data. Is it ok to create custom table for users? I am going to create another table related to user table. So in that case, there must be id in the users. That's why I am going to create custom table. Please help me it is good practice. -
Django job board, upload form data to database if payment is successful using stripe?
I am creating a django jobboard, where you can fill details(title, description, company logo etc). When submit, check for payment competition(stripe) , if successful, upload the job data to database and redirect to this newly created job data. My question is how to check for payment completion and how to pass form data(image, title, description etc) to database only if payment is complete. How to handle if payment is successful but data failed to upload (for example validation of image extension). Any open source project of django jobbord with payment system(stripe checkout or stripe payment intent method). Thanks. -
How can I calculate discount fields from another table's fielsd
I have a model like this: class InvoiceItem(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='items') title = models.CharField(max_length=100, null=True, blank=True) price = models.IntegerField(null=True, blank=True) discount = models.IntegerField(blank=True, default=0) totalprice = models.IntegerField(null=True, blank=True) count = models.IntegerField(null=True, blank=True) and I want to calculate discount from book's discount table How can I do it? should I calculate it in models? -
'QuerySet' object has no attribute 'defer_streamfields' when accessing root in Wagtail page
I just encountered the problem: 'QuerySet' object has no attribute 'defer_streamfields' when trying to access the Wagtail page in Wagtail admin. image for wagtail page failure Accessing a single page (eg. page/527) is working fine. Some people suggested that the problem can be caused by content type mix up in the database, but I haven't done any database dump before. Can someone offer me some advice on this issue? Thanks! stack trace: File "C:\Users\env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\env\lib\site-packages\django\template\defaulttags.py", line 311, in render if match: File "C:\Users\env\lib\site-packages\django\core\paginator.py", line 177, in __len__ return len(self.object_list) File "C:\Users\env\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\env\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\env\lib\site-packages\wagtail\query.py", line 528, in __iter__ pages = pages.defer_streamfields() AttributeError: 'QuerySet' object has no attribute 'defer_streamfields' I am using Django==3.2, wagtail==4.0.1. The problem occured after upgrading wagtail from 2.6.2 to 4.0.1 -
Python django, trying to make a sidebar, but it doesnt appear/show
so as the title says I'm trying to learn Django and create a sidebar, but it just doesn't appear. This is my home.html {% extends 'main.html' %} {% block content %} <style> .home-container{ display: grid; grid-template-columns: 1fr 3fr; } </style> <div class="home_container"> <div> <h3>Browse Topics</h3> <hr> </div> <div> <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> <a href="{% url 'update-room' room.id %}">Edit</a> <a href="{% url 'delete-room' room.id%}">Delete</a> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> </div> </div> {% endblock content %} This is my main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Site</title> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock %} </body> </html> The problem I am having is with the style part it seems correct and is supposed to make a sidebar with the Browse Topics. This is probably a very dumb question, but I've been struggling for hours and reached a point where I had to make an account to find a solution. Any help would be greatly appreciated. -
Using When and Less then in Django DRF?
I am trying to check where a number is GreaterThan another number in the request.data and set the value if condition is true. ExampleModel.objects.filter( tic=request.data['tic']).update(last_high=When(GreaterThan(F('last_high'), request.data['high']), then=0)) Error: django.db.utils.OperationalError: near "WHEN": syntax error I am not sure how to proceed from here, trying to understand the documentation but I can't seem to find why it won't work. Documentation -
Django annotate multiple "Sum(Case(When()))" returns incorrect result
There is no problem with stock balls, but when you add currency, the stock totals are incorrect. My Models class Product(models.Model): stock_code = models.CharField(max_length=200, unique=True) product_name = models.CharField(max_length=255) class Price(models.Model): product = models.ForeignKey( 'product.Product', models.CASCADE, related_name='product_price_product' ) price = models.FloatField() class Transaction(models.Model): product = models.ForeignKey( 'product.Product', models.CASCADE, related_name='product_transaction' ) warehouse = models.ForeignKey( 'product.Warehouse', models.CASCADE, related_name='product_warehouse' ) type = models.BooleanField(_('Hareket Tipi'), choices=sorted([ (True, _('Stock In')), (False, _('Stock Out')) ])) quantity = models.FloatField() ModelViewSet class ProductView(ModelViewSet): queryset = Product.objects.prefetch_related( 'product_image_product', 'product_price_product', ).all() serializer_class = ProductSeriliazer def get_custom_queryset(self): warehouse = self.request.query_params.get('warehouse', 0) sale_price = self.request.query_params.get('sale_price', 0) purchase_price = self.request.query_params.get('purchase_price', 0) is_tax = self.request.query_params.get('is_tax', None) currency = self.request.query_params.get('currency', None) # Rate Calc if currency: currencies = Currency.objects.all().values('currency_code', 'currency_value') sale_price_when = [] purchase_price_when = [] for i in currencies: to_currency_val = list(filter(lambda x: x['currency_code'] == i['currency_code'], currencies))[0].get('currency_value') money_val = list(filter(lambda x: x['currency_code'] == currency, currencies))[0].get('currency_value') if is_tax == 'true': sale_price_when.append( When( product_price_product__definition_id=int(sale_price), product_price_product__definition__type=True, product_price_product__is_tax=True, product_price_product__currency=i['currency_code'], then=exchange_rate_calculator('product_price_product__price', money_val, to_currency_val) ) ) sale_price_when.append( When( product_price_product__definition_id=int(sale_price), product_price_product__definition__type=True, product_price_product__is_tax=False, product_price_product__currency=i['currency_code'], then=((exchange_rate_calculator('product_price_product__price', money_val, to_currency_val) * F('product_price_product__tax')) / 100) + exchange_rate_calculator('product_price_product__price', money_val, to_currency_val) ) ) purchase_price_when.append( When( product_price_product__definition_id=int(purchase_price), product_price_product__definition__type=False, product_price_product__is_tax=True, product_price_product__currency=i['currency_code'], then=exchange_rate_calculator('product_price_product__price', money_val, to_currency_val) ) ) purchase_price_when.append( When( product_price_product__definition_id=int(purchase_price), product_price_product__definition__type=False, product_price_product__is_tax=False, product_price_product__currency=i['currency_code'], then=((exchange_rate_calculator('product_price_product__price', money_val, to_currency_val) * F('product_price_product__tax')) / 100) + exchange_rate_calculator('product_price_product__price', … -
hello, I can’t solve this problem, I want to run this command, there is such an error?
python manage.py loaddata --settings definme.settings.dev django-dump.json wagtail.models.i18n.Locale.DoesNotExist: Problem installing fixture Locale matching query does not exist. -
Django - How to make multiple choice field in Admin Field?
I have the following Django model: class Level(models.Model): topics = # need to put option choice field here shortDescription = models.CharField(max_length = 50) I want my admins to be able to go into my application and for the topics, I want them to be select multiple values from a list in a user friendly way (dropdown) How can I make is so that admins using my app can go in and choose from a list of topics? They need to be able to choose multiple but they can select 1 if they choose to. -
Python Django update variable in template while function runs in background
I have this simple template which has a button: <a class="button" href="{% url 'function' %}"> <button> Settings </button> </a> And views.py in which I have function definition. def function(request): context = {} object = Runner() object.prepate_sth() context['tasks'] = runner.tasks.remaining try: thread = threading.Thread(target=runner.run_sth, args=()) thread.start() except Exception: raise Exception return render(request, 'home.html', context) I am creating separate thread in order to not to block the function execution and run some other function in the background. That task in the background changes the quantity of elements in runner.tasks.remaining list variable. I would want to have that variable shown in the template and being updated constantly when its value changes. How can I achieve that? -
How to use django-filters to filter a field by a list of inputs
I have a list of objects that have a country code associated with them, I would like to write a FilterSet class that can receive a list of codes ie. ['US', 'CA'] and will return a list of the objects that have the country code column set to either of those values. It doesn't seem like filtersets may be able to do this for me, but its seems like a relatively common requirement? I was thinking maybe it's something like __in for the filterset field. Any help is much appreciated -
Is there a way to sync a user from the code than running the ldap_sync_users <username> in django-python3-ldap?
To sync a user, I need to run ./manage.py ldap_sync_users . I wondered if the same can be achieved in Django without running manage.py. I was hoping to achieve this from the webpage, search for a user and do the sync. -
(staticfiles.W004) The directory in the STATICFILES_DIRS setting does not exist error in django
so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading my error is: (staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist. my code snippets are given below: my setting is: settings.py Django settings for epayment project. Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+)&^ze^f+g#k28j#(1&r8y@u)g4=9!g7c4ef-i07!5@yhq2dd3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'epayapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'epayment.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', … -
Nextjs Error occurred prerendering page Error: connect ECONNREFUSED 127.0.0.1:8000 (Believe me this one is complicated)
Maybe this question was asked a hundred times, but I have an awkward one. All my pages load successfully with npm run dev. Whenever executing "npm run build" there are some errors. Do you guys have any idea? Console output info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules info - Linting and checking validity of types info - Creating an optimized production build info - Compiled successfully info - Collecting page data [ ] info - Generating static pages (0/333) Error occurred prerendering page "/r/sustainable-responsible-tourism". Read more: https://nextjs.org/docs/messages/prerender-error Error: connect ECONNREFUSED 127.0.0.1:8000 at Function.AxiosError.from (file:///C:/Users/aybas/Desktop/tto-frontend/node_modules/axios/lib/core/AxiosError.js:89:14) at RedirectableRequest.handleRequestError (file:///C:/Users/aybas/Desktop/tto-frontend/node_modules/axios/lib/adapters/http.js:516:25) at RedirectableRequest.emit (node:events:513:28) at ClientRequest.eventHandlers.<computed> (C:\Users\aybas\Desktop\tto-frontend\node_modules\follow-redirects\index.js:14:24) at ClientRequest.emit (node:events:513:28) at Socket.socketErrorListener (node:_http_client:481:9) at Socket.emit (node:events:513:28) at emitErrorNT (node:internal/streams/destroy:157:8) at emitErrorCloseNT (node:internal/streams/destroy:122:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) [ ===] info - Generating static pages (2/333) Error occurred prerendering page "/how-to-roam/family-vacations". Read more: https://nextjs.org/docs/messages/prerender-error Error: connect ECONNREFUSED 127.0.0.1:8000 at Function.AxiosError.from (file:///C:/Users/aybas/Desktop/tto-frontend/node_modules/axios/lib/core/AxiosError.js:89:14) at RedirectableRequest.handleRequestError (file:///C:/Users/aybas/Desktop/tto-frontend/node_modules/axios/lib/adapters/http.js:516:25) at RedirectableRequest.emit (node:events:513:28) at ClientRequest.eventHandlers.<computed> (C:\Users\aybas\Desktop\tto-frontend\node_modules\follow-redirects\index.js:14:24) at ClientRequest.emit (node:events:513:28) at Socket.socketErrorListener (node:_http_client:481:9) at Socket.emit (node:events:513:28) at emitErrorNT (node:internal/streams/destroy:157:8) at emitErrorCloseNT (node:internal/streams/destroy:122:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) info - Generating static pages (333/333) > Build error occurred Error: Export encountered errors on following paths: /how-to-roam/[category]: /how-to-roam/family-vacations /r/[slug]: /r/sustainable-responsible-tourism at C:\Users\aybas\Desktop\tto-frontend\node_modules\next\dist\export\index.js:404:19 at … -
How to automatically update a field when creating another record in different models?
I have two models that look like this: class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), verbose_name='Member Name', related_name="team_members") team = models.ManyToManyField('Team', verbose_name='Team Name', related_name="team_members", blank=False, default=team_id) shift = models.ForeignKey(Shift, on_delete=models.PROTECT) ... class Team(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(TeamMember, blank=True, related_name="members") ` The users use the admin panel to add new members. When adding a new member, I want to automatically add the member to the associated team. For example, when adding John, it is required to assign a team to him(blank=False), and the team is from what we have in the Team model. Then how do I update the members in the Team model to add John to one of the teams accordingly? Please help, thanks! -
slug related Feilds are not parsed in json parsing
I am trying to import with codenames it takes as a string while doing json parsing with slug feilds class ImportFinanceSaleSerializerField(serializers.JSONField): def to_representation(self, obj): user_serializer = ImportFinanceSaleSerializer(obj, many=False, ) return user_serializer.data def to_internal_value(self, data): return data' class ImportFinanceSaleSerializer(serializers.ModelSerializer): interestpercentage = serializers.SlugRelatedField( required=False, allow_null = True, slug_field="code", queryset=PercentageInterest.objects.filter(status=1,)) guarantor = serializers.SlugRelatedField( required=False, allow_null = True, slug_field='code', queryset=Person.objects.filter(status=1,)) emi_date = serializers.IntegerField(required=False, min_value=1, max_value=30) -
Doing polymorphic model, what's the best approach?
I'm trying to upscale a project that originally was used by an area to assign reports to their respective departments. Those reports I want them to be tasks, to broaden the spectrum of use to all of the organization. Originally, I was using separate models for reports, updates, report files, update files. (Those tables, had almost the same fields) Now, I'm trying to have a polymorphic model, as shown below: #### TASK TYPE (TASK, UPDATE) class TipoTarea(models.Model): nombre = models.CharField(max_length=50, unique=True) def __str__(self): return self.nombre ###### TASK CATEGORY (TOPIC AND THE AREA WHO IS BEING DIRECTED TO) class CategoriaTarea(models.Model): nombre = models.CharField(max_length=50, unique=True) area = models.ForeignKey(Area, on_delete=models.CASCADE) tiempo_atencion = models.IntegerField(default=2) def __str__(self): return self.nombre ##### TASK STATE (CREATED, IN PROCESS, COMPLETED, REASIGNED) ##### REASIGNED STATE, CREATES A NEW TASK WITH A DIFFERENT CATEGORY class EstadoTarea(models.Model): nombre = models.CharField(max_length=50) def __str__(self): return self.nombre ###### TASK ###### TASK PARENT WOULD BE USED FOR UPDATES, BUT HOW CAN REASIGNMENTS BE CLASSIFIED class Tarea(models.Model): tipo = models.ForeignKey(TipoTarea, on_delete=models.CASCADE, related_name = 'tarea') categoria = models.ForeignKey(CategoriaTarea, on_delete=models.CASCADE, related_name = 'tarea') descripcion = models.CharField(max_length=500) fecha = models.DateField(default=datetime.date.today) estado = models.ForeignKey(EstadoTarea, default= 1, on_delete=models.CASCADE) creado_por = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creador') creado = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name="actualizaciones", null=True, … -
how to run tasks in parallel with django async
i'm using daphne as a asgi server, with django. turning my view from sync to async was relatively simple, since i could use @sync_to_async at the ORM part. the problem is, some service of mine is like this: async def service_of_mine(p1, p2, p3): r1 = await foo1(p1) r2 = await foo2(p2) r3 = await foo3(p3) return r1, r2, r3 i wanted to run all three calls in parallel, using return await asyncio.gather(foo1(p1), foo2(p2), foo3(p3)) but my api hangs with Application instance <Task pending name='Task-1' coro=<ASGIStaticFilesHandler.__call__() running at /mypath/python3.10/site-packages/django/contrib/staticfiles/handlers.py:101> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /home/rado/.pyenv/versions/3.10.6/lib/python3.10/asyncio/futures.py:385, Task.task_wakeup()]>> for connection <WebRequest at 0x7f8274b98340 method=GET uri=/myApiPath clientproto=HTTP/1.1> took too long to shut down and was killed. how can i achieve this?