Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When create django table dynamically, how can I set Meta class?
I have a Django abstract model class and want to create it dynamically with meta class. class AccountTransaction(models.Model): class Meta: abstract = True account_num = models.ForeignKey('Account', on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() tran_type = models.CharField() tran_detail = models.CharField() tran_time = models.DateTimeField(auto_now_add=True) for i in range(10): model_name = f'account_transaction_{i:02}' globals()[model_name] = type(model_name, (AccountTransaction, ), {'__module__': AccountTransaction.__module__}) I could create 10 tables with this code when execute makemigrations and migrate Is it possible to set different metaclasses for each tables? For example, account_transaction_01 class Meta: db_table: "table1" account_transaction_02 class Meta: db_table: "table2" -
Django, Is there a way to access additional custom fields to the default user model in the serializer?
I am trying to send current user information through an API endpoint. I am using the Django default user model, and adding additional fields through inline. (Please refer to the code below) I am wondering if there is a way that I can access the newly added fields in the User serializer? I tried a lot of ways to include the newly added data but all failed. (for example, I am trying to pass gender_identity to my serializer so that my frontend could access the information) Here is my serializer.py: from django.contrib.auth.models import User from accounts.models import Account class UserSerializer(serializers.ModelSerializer): # author = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='username') class Meta: # gender_identity = User.objects.get(username = 'bucky').account.gender_identity model = User fields = ['username', 'email','first_name','last_name'] read_only_fields = ['username', 'email','first_name','last_name'] depth = 3 Here is my Views.py: from rest_framework import viewsets # from .serializers import UserSerializer from .serializers import UserSerializer from django.contrib.auth.models import User from rest_framework.generics import (ListAPIView, ListCreateAPIView, DestroyAPIView, UpdateAPIView) class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_object(self): # print(self.request.user.account.gender_identity) print(type(self.request.user)) return self.request.user def list(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) My models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = … -
Why does Bootstrap cards have cards all shifted to the left?
I am creating a page in which news articles get fetched using Python, and then formatted into cards. I have used pagination to have 12 cards per page, but for some reason, all my cards and pagination bar are shifted to the left, and everything is off-centered. I would like to have them centered and all have the same width and height. How would I do this? {% if not posts %} <p>No articles were found.</p> {% else %} <div class="card-columns"> <!--class="row" style="display: flex; flex-wrap: wrap; gap: 8px; max-width: 916px; width: calc(100% - 20px);"--> {% for result in posts %} <div class="card"> <!--style="height: 260px; width: 300px; border-radius: 10px;"--> <img class="card-img-top img-fluid" src="{{ result.img }}" alt="Article image cap"> <div class="card-body"> <a href="https://{{ result.link }}" target="_blank"><h5 class="card-title">{{ result.title }}</h5></a> <p class="card-text">{{ result.desc }}</p> </div> </div> {% endfor %} </div> {% endif %} {% if posts.has_other_pages %} <ul class="pagination justify-content-center"> {% if posts.has_previous %} <li class="page-item"> <a class="page-link" href="?page= {{ posts.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#!" tabindex="-1" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for num in posts.paginator.page_range %} {% … -
copyleaks sent pdfReport to endpoint as binary on request.body, not as file
I have django view that gets request and I try to send pdf result of copyleak scan. I get file as request.body and request.FILES is empty. I have checked copyleaks docs to see if I could pass extra argument as we should pass enctype="multipart/form-data" in django form to get files in request.FILES, but I did not see anything related. I can read request body and write it to file, no problem here, but would be great if I directly get pdf file in request FILES. myobj = json.dumps( { "pdfReport": { "verb": "POST", "endpoint": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/download/", }, "completionWebhook": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/complete/", "maxRetries": 3, } ) response = requests.post( "https://api.copyleaks.com/v3/downloads/file4/export/export16", headers=headers, data=myobj, ) I tried to change Content-Type manually and got error django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None Bad request (Unable to parse request body): /en/tool/copyleaks/download/ -
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 …