Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get product count from parent in django rest framework
a'm new in django, I have one model like this class Category(models.Model): title = models.CharField(max_length=200) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') Parent - foods subparent - Italian food, French food and other pizaa, Polenta, Lasagna Parent - drinks subparent - juice, alkohol water, tea, leamon tea Can i count in serializer foods count - 3 drinks count - 4 -
How to compare and validate form values before sending in Django Admin?
In my admin panel, users can edit a dropdown to set values for one or more lines before saving the changes. When 2 or more lines are edited at once, I would like to check if the values set by the user are coherent. Here is an example. These two rows should not have 2 different values. I have tried overriding the clean() methods in the model but I need to validate the data before this is triggered, preferably right after the form is sent. Is this possible? Official Django Documentation mostly describes data validation form in the model, but this would not allow me to compare rows between them. -
How can I deal with the Problem while the Tutorial of Django
I'm trying to make a code for administraion with Django. But unfortunatley it doesn't work well like what the tutorial said. Here is the code that I used from django.contrib import admin from .models import Question admin.site.register(Question) and the errormesseage shows and also here is the datalist in my labtop can someone please give me any advice, how can I fix this problem? thank you -
add user to auth0 automatically
My question is similar to this stack overflow question. So any time a create u user in django admin I want that user with the same data to appear in auth0. Thanks for help. -
Javascript request with cookies with django csrf token
I have a checkbox in django template that has function binded to it. <input type="checkbox" id="confirm-switch" onchange="Change({{AvgUser.id}})" > the function supposed to send requests on endpoint. The problem is csrf token in cookies.How can i send request with cookies attached? -
Working with Mysql stored procedures in pythonanywhere
I have imported mysql workbench data along with stored procedures from local to pythonAnywhere. However the query in stored procedures are not being executed properly. I am trying to order them in desc order, but it is not working. Can anyone guide? -
django summernote Limit the number of images
I know how to limit the size of the image file in django summernote. However, I can't find the way to limit the total number of images I upload. Is there anyone who knows? -
Django add to wishlist
i have to do wishlist, i have done wishlist page,model and html.But when i click on the button bellow my post, im redirected to wishlist page and post didnt saved in my wishlist.So thats my code: models.py class Wishlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) wished_item = models.ForeignKey(Posts, on_delete=models.CASCADE) def __str__(self): return self.wished_item.title class Posts(models.Model): TYPE = Choices( ('private', _('private')), ('business', _('business')), ) STATUS = Choices( ('active', _('active')), ('deactivated', _('deactivated')) ) owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='posts', on_delete=models.CASCADE, verbose_name='owner') phone_number = PhoneNumberField(verbose_name=_('Phone_number'), null=False, blank=False, unique=True) title = models.CharField(verbose_name=_('Title'), max_length=100) text = RichTextField(verbose_name=_('Text')) image = models.ImageField(upload_to='images/%Y/%m/%d/', null=True, blank=True, validators=[file_size]) price = models.DecimalField(verbose_name=_('Price'), decimal_places=2, max_digits=9) status = models.CharField(choices=STATUS, max_length=50) created = models.DateTimeField(auto_now=True) type = models.CharField(choices=TYPE, max_length=50) def __str__(self): return self.title views.py class WishListView(generic.View): def get(self, *args, **kwargs): wish_items = Wishlist.objects.filter(user=self.request.user) context = { 'wish_items': wish_items } return render(self.request, 'wishlist/wishlist.html', context=context) def addToWishList(request): if request.method == 'POST': post_var_id = request.POST.get('object-id') post_var = Posts.objects.get(id=post_var_id) print(post_var) try: wish_item = Wishlist.objects.get(user=request.user, post=post_var) if wish_item: wish_item.save() except: Wishlist.objects.create(user=request.user, post=post_var) finally: return HttpResponseRedirect(reverse('wishlist')) wishlist.html {% extends 'posts/base.html' %} {% load thumbnail %} {% block content %} <div> {% for item in wish_items %} {% if item.wished_item.image1 %} <img src="{{item.wished_item.image.url}}" alt=""> {% endif %} </div> <div> <li>{{item.wished_item.title}}</li> <li>{{item.wished_item.text}}</li> <li>{{item.wished_item.price}}</li> <li>{{item.wished_item.phone_number}}</li> {% … -
zero-size array to reduction operation fmin which has no identity
I'm trying read xlsx file but gets me ValueError zero-size array to reduction operation fmin which has no identity views.py def t(request): context = {} if request.method == "POST": uploaded_file = request.FILES['document'] print(uploaded_file) if uploaded_file.name.endswith('.xlsx'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) d = os.getcwd() file_directory = d + '\media\\' + name readfile(file_directory) return redirect(r) else: messages.warning(request, 'File was not uploaded. Please use xlsx file extension!') return render(request, 't.html', {}) def read_file(filename): my_file = pd.read_excel(filename) data = pd.DataFrame(data=my_file) Note: It reads some files correctly -
Building a ChatOps solution using MS Teams as its collaborative platform
So I am trying to create a chatOps environment for our operations team using MS Teams as the communication platform. Since I already have the OpsBot running on Django Python, and the limitations I faced corporate policy wise made us decide to use Teams incoming & outgoing webhooks to send commands to the bot and receive feedback to the chat. Is there any other possible way to build this without having to pay Microsoft for their features that we are using. Our subscription is Enterprise. -
How to fix this error: Template Does Not Exist ? Django
urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home') ] another urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('subokLang.urls')), path('admin/', admin.site.urls), ] settings.py under templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'tryingDjango/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] here, the views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return render(request, 'templates/home.html') I am stuck here, tried changing many already, still won't work, the 500(Template does not exist), what is the right code? Thanks in advance! -
Django automatiser l'exécution d'une fonction tous les jours
Bonjour, Comment puis-je faire pour exécuter automatiquement une fonction tous les jours sous django, par exemple chaque jours à 10h30 la fonction se lance. Quelqu'un peut m'aider svp ? merci d'avance -
Reverse a mp3 file in python
I would need some api or some way to have a input mp3 file and make a new one that is the same file but in reverse and/or faster pace/slowed down Is there a simple Api for that or do I have to make it on my own -
orderitem_set.all() returning empty query
def cart(request, *args, **kwargs): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer,complete=False) items = order.orderitem_set.all() print(items) else: items = [] return render(request, 'product_pages/cart.html', {'items': items}) everythings fine till that items value, because items returning empty query. And this is returned message to terminal. System check identified no issues (0 silenced). October 04, 2022 - 10:17:16 Django version 4.1, using settings 'lira_gold_site.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 2 <QuerySet []> [04/Oct/2022 10:17:18] "GET /cart/ HTTP/1.1" 200 4646 [04/Oct/2022 10:17:18] "GET /static/css/navbar.css HTTP/1.1" 200 1872 [04/Oct/2022 10:17:18] "GET /static/css/cart.css HTTP/1.1" 200 1108 [04/Oct/2022 10:17:18] "GET /static/fontawesomefree/css/all.min.css HTTP/1.1" 200 101784 [04/Oct/2022 10:17:18] "GET /static/fontawesomefree/js/all.min.js HTTP/1.1" 200 1528342 [04/Oct/2022 10:17:19] "GET /static/images/lira_gold_logo.png HTTP/1.1" 200 4517 [04/Oct/2022 10:17:19] "GET /static/fontawesomefree/webfonts/fa-solid-900.woff2 HTTP/1.1" 200 150472 Not Found: /favicon.ico [04/Oct/2022 10:17:19] "GET /favicon.ico HTTP/1.1" 404 3822 -
TypeError when using Django update_or_create
I try to use update_or_create method but got a TypeError Django 2.2.5 Python 3.7 TypeError: update_or_create() got multiple values for keyword argument 'dcf_ide' I probably misunderstand how to use update_or_create method I've read this post datas in DataCorrectionForm model before update dcf_ide pat status crated_date 0 43_inc_poi_1 01-001 1 2022-10-04 08:36:21.991740+00:00 1 43_inc_poi_3 01-003 1 2022-10-04 08:36:22.031926+00:00 2 43_inc_poi_7 02-001 1 2022-10-04 08:36:22.054673+00:00 3 43_inc_poi_9 01-050 1 2022-10-04 08:36:22.075715+00:00 4 43_inc_poi_11 01-002 1 2022-10-04 08:36:22.096237+00:00 5 46_inc_tai_2 02-002 1 2022-10-04 08:36:22.147911+00:00 6 46_inc_tai_4 01-004 1 2022-10-04 08:36:22.175169+00:00 7 46_inc_tai_7 02-001 1 2022-10-04 08:36:22.193514+00:00 8 46_inc_tai_9 01-050 1 2022-10-04 08:36:22.210608+00:00 records = DCF_AFTER_UPDATE.to_dict(orient='records') for record in records: DataCorrectionForm.objects.update_or_create( dcf_ide=record['dcf_ide'], **record ) Update/Create dcf_ide pat status crated_date 0 43_inc_poi_1 01-001 0 2022-10-04 08:36:21.991740+00:00 #<= update status column 1 43_inc_poi_3 01-003 2 2022-10-04 08:36:22.031926+00:00 #<= update status column 2 43_inc_poi_7 02-001 2 2022-10-04 08:36:22.054673+00:00 #<= update status column 3 43_inc_poi_9 01-050 2 2022-10-04 08:36:22.075715+00:00 #<= update status column 4 43_inc_poi_11 01-002 2 2022-10-04 08:36:22.096237+00:00 #<= update status column 5 46_inc_tai_2 02-002 2 2022-10-04 08:36:22.147911+00:00 #<= update status column 6 46_inc_tai_4 01-004 2 2022-10-04 08:36:22.175169+00:00 #<= update status column 7 46_inc_tai_7 02-001 0 2022-10-04 08:36:22.193514+00:00 #<= update status column 8 46_inc_tai_9 01-050 2 2022-10-04 … -
Best way to fetch rating data using django ORM
I have a serialzer which have get_rates method. I want a way to get the rates for the driver in a better way and fast as well. def get_rates(self, obj): reviews = Review.objects.filter(driver=obj) rate_5 = reviews.filter(customer_rate__gt=4, customer_rate__lte=5).count() rate_4 = reviews.filter(customer_rate__gt=3, customer_rate__lte=4).count() rate_3 = reviews.filter(customer_rate__gt=2, customer_rate__lte=3).count() rate_2 = reviews.filter(customer_rate__gt=1, customer_rate__lte=2).count() rate_1 = reviews.filter(customer_rate__gt=0, customer_rate__lte=1).count() return { 'rate_5': rate_5, 'rate_4': rate_4, 'rate_3': rate_3, 'rate_2': rate_2, 'rate_1': rate_1, } -
Django - Create model with fields derivable from other model
I have 2 Django models representing the coin domain. The Coin has some properties and the trading Pair is based on those properties. class Coin(models.Model): code = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=32) class Pair(models.Model): code = models.CharField(max_length=16, primary_key=True) name = models.CharField(max_length=64) base_currency = models.ForeignKey(Coin, on_delete=models.CASCADE, null=False, related_name='base_currency') quote_currency = models.ForeignKey(Coin, on_delete=models.CASCADE, null=False, related_name='quote_currency') Let's add a couple of Coin instances: first = Coin.objects.create(code="BTC", name="Bitcoin") second = Coin.objects.create(code="USD", name="United States Dollar") and one Pair: Pair.objects.create(code="BTCUSD", name="Bitcoin / United States Dollar", base_currency=first, quote_currency=second) As you can see, code and name in the Pair model can be derived from code and name in the Coin model. To put it simple: Pair Code = First Coin Code + Second Coin Code Pair Name = First Coin Name + "/" + Second Coin Name But, in this example I simply hardcoded those values and for sure this is not the best way to handle this situation. For example: what if in the Coin model I need to change the name of an instance? Then, I will have to manually update code and name in the Pair model, because this values are not properly binded from the Coin Model. I believe Pair code/name must be binded/derived … -
How do i make a bootstrap form in django scrollable?
enter image description here I have tried different CSS properties to make the form scrollable but none is working. -
Django/PostgreSQL parallel concurrent incrementing field value with transaction causes OperationalError
I have model related to some bunch. Each record in one bunch should have it's own unique version (in order of creation records in DB). As for me, the best way to do this is using transactions, but I faced a problem in parallel execution of transaction blocks. When I remove transaction.atomic() block, everything works, but versions are not updated after execution. I wrote some banch of code to test concurrent incremention version of record in database: def _save_instance(instance): time = random.randint(1, 50) sleep(time/1000) instance.text = str(time) instance.save() def _parallel(): instances = MyModel.objects.all() # clear version print('-- clear old numbers -- ') instances.update(version=None) processes = [] for instance in instances: p = Process(target=_save_instance, args=(instance,)) processes.append(p) print('-- launching -- ') for p in processes: p.start() for p in processes: p.join() sleep(1) ... # assertions to check if versions are correct in one bunch print('parallel Ok!') save() method in MyModel is defined like this: ... def save(self, *args, **kwargs) -> None: with transaction.atomic(): if not self.number and self.banch_id: max_number = MyModel.objects.filter( banch_id=self.banch_id ).aggregate(max_number=models.Max('version'))['max_number'] self.version = max_number + 1 if max_number else 1 super().save(*args, **kwargs) When I run my test code on random amount of records (30-300), I get an error: django.db.utils.OperationalError: server … -
Djangosaml2 the use of metadata
I'm manage to integrate SAML authentication in my Django application using the package Djangosaml2 and Pysaml2 with Azure as IdP provider. everything is working properly I can login with SAML and log out. What I don't understand is what is the use of having a metadata at the url https://panda.company.com/saml/metadata and what is the use of having a url https://panda.company.com/saml2/ls/ ? Because with just the remote_metadata.xml provided by Azure is enough to login and logout. SAML_CONFIG = { 'xmlsec_binary': '/usr/bin/xmlsec1', 'name': 'CloudBolt SP', 'entityid': 'https://panda.company.com/', 'service': { 'sp': { 'want_assertions_signed': False, 'want_response_signed': False, 'allow_unsolicited': True, 'endpoints': { 'assertion_consumer_service': [ ('https://panda.company.com/saml2/acs/', saml2.BINDING_HTTP_POST), ], 'single_logout_service': [ ('https://panda.company.com/saml2/ls/', saml2.BINDING_HTTP_REDIRECT), ], }, 'required_attributes': ['email'], }, }, 'debug': 1, 'key_file': os.path.join(SAML2_DIR, 'saml.key'), # private part 'cert_file': os.path.join(SAML2_DIR, 'saml.crt'), # public part 'allow_unknown_attributes': True, 'attribute_map_dir': os.path.join(/usr/local/lib/python3.6/site-packages/saml2/attributemaps'), 'metadata': { 'local': [os.path.join(SAML2_DIR, 'remote_metadata.xml')], }, 'contact_person': [{ 'given_name': 'First', 'sur_name': 'Last', 'company': 'Company', 'email_address': 'me@company.com', 'contact_type': 'technical' }], 'organization': { 'name': 'Company', 'display_name': 'Company', 'url': 'http://www.company.com', }, 'valid_for': 24, # how long is our metadata valid 'accepted_time_diff': 120, #seconds } SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'username' SAML_CREATE_UNKNOWN_USER = True SAML_ATTRIBUTE_MAPPING = { 'email': ('email', ), 'givenName': ('first_name', ), 'sn': ('last_name', ), 'uid': ('username', ), } -
In model my image field is showing blank even though I have inserted the image from html
In model my image field is showing blank even though I have inserted the image from html -
admin dashboard for ecommerce - react & django
I'm building an ecommerce app in react and django and I also have to build a a dashboard. What would be a good approach to build the dashboard? This dashboard will be used to upload products, see users and their enquiries and also if the order was successful and stuff like that. I've never done anything like this before so would love your suggestions. Edit: I'm asking if usually we build the dashboard from scratch or is there something else we use? -
Django serializer validate related serializer
I have two Django Model, one depend on another. I made serializers for them, but I don't understand how i'm supposed to link the serializer so one call the validation of the child. class Tree(Model): id = AutoField(primary_key=True, auto_created=True) class Leaf(Model): id = AutoField(primary_key=True, auto_created=True) tree= ForeignKey(Tree, on_delete=SET_NULL, db_column="etude") My serializers look like this class TreeSerializer(ModelSerializer): leafList = LeafSerializer(source="leaf_set", many=True) class Meta: model = Tree fields = [ "id", "leafList", ] def create(self, validated_data): leafs = validated_data.pop("leaf_set", []) instance = Tree.objects.create(**validated_data) for leaf in leafs : leaf.update({"tree": instance}) Leaf.objects.create(**leaf) class LeafSerializer(ModelSerializer): class Meta: model = Leaf fields = [ "id", "tree" ] def validate(self, attrs): return False But my LeafSerializer seems to never be called. All objects are properly created, but LeafSerializer's validate method is never run, thus don't prevent creation when a Leaf is invalid. I can't find in the django rest documentation instructions on how to do validation on related object. I've looked at django rest relations documentation but i'm not sure it is what i'm looking for. I'm thinking about explicitly creating a LeafSerializer inside the create function of TreeSerializer. I would be able to check the data, but i'm not sure if that's the right way … -
Automatic Time and Date Insertion
I want to automatically add the date and time information of that time to a certain field in the project I am doing. I am using Django, HTML, JavaScript in my project, how can I do it with any of them? -
How to send back the data to react frontend after callback from google OAuth in django?
I am working on an application with two parts as frontend and backend in react and django , I am using server side flow and using token authentication for login and authentication system with OAuth . When user clicks on the frontend on LOGIN WITH GOOGLE it is allowed to choose the email and login with the react server with port 3000 and the redirect url or callback url is my django backend with port 8080 and when it will be in production there will be an ip or domain for that . But now when i login with frontend , it goes to callback and sends all the data there . Now the thing is that after receiving the authorization_code , getting access_token and then data , the request resides in the backend code and the connection with the react frontend is completely broken . Now I don't understand how to send data back to the frontend with auth token and all other data. my views.py "http://localhost:8080/api/callback/" @api_view(["GET"]) def getCallBack(request , *args , **kwargs): if request.method == "GET" : data = { "scope" : request.GET.get("scope").strip().lstrip().rstrip() , "authuser" : request.GET.get("authuser").strip().lstrip().rstrip() , "prompt": request.GET.get("prompt").strip().lstrip().rstrip() , "code" : request.GET.get("code").strip().lstrip().rstrip() , "client_id" :"", …