Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "Authentication credentials were not provided." when I want to signup user
when I want to post data and create a new teacher it gives me this error and I don't know what to do please help me this is my models.py this is my views.py this is my serializer.py -
Django all auth create userprofile with signup form
I am trying to create a user profile. The database row gets created, also the ID is correct (one-to-one relation). All other data is not being stored. For example: The counter_announcements_approved cell is always filled with NULL, instead of 222. Why is that? class CustomSignupImmobilienbetreiber(SignupForm): first_name = d_forms.CharField(max_length=128, required=True, label="Vornamen") last_name = d_forms.CharField(max_length=128, required=True, label="Nachnamen") company_name = d_forms.CharField(max_length=128, required=True, label="Firma/Unternehmen") telephone_number = d_forms.CharField(max_length=128, required=True, label="Telefonnr.") street = d_forms.CharField(max_length=128, required=True, label="Straße") city = d_forms.CharField(max_length=128, required=True, label="Stadt") state = d_forms.ChoiceField(choices=STATE_CHOICES, label="Bundesstaat", required=True) gewerbeanmeldung = d_forms.FileField() def custom_signup(self, request, user): #profile, created = Immobilienbetreiber.objects.get_or_create(user=user) user.user_type = 1 user.is_active = 0 user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.company_name = self.cleaned_data['company_name'] user.telephone_number = self.cleaned_data['telephone_number'] user.street = self.cleaned_data['street'] user.city = self.cleaned_data['city'] user.state = self.cleaned_data['state'] profile = user.immobilienbetreiber_profile profile.gewerbeanmeldung = self.cleaned_data['gewerbeanmeldung'] profile.counter_announcements_approved = 222 user.save() profile.save() return user -
Django - Using a complex query
I've read almost all of the related questions and still can't figure out how to execute the following query in Django. Using the Django standard tables for Auth I've added a group called 'approvers'. I need to query to return all approvers. In SQLite designer I developed the following sql: select auth_user.email, auth_user.first_name, auth_user.last_name from auth_user, auth_user_groups where auth_user.id = auth_user_groups.user_id and auth_user_groups.group_id in ( select auth_group.id from auth_group where auth_group.name = "approvers") It seems that I should be able to do this by using the raw method on the models, but would like to understand how to use the Django ORM to access this if it's a better more acceptable approach. -
Django signals @receiver POST_SAVE not working on PROD (ok on DEV)
Getting nuts ... On dev, my signals (for sending an alert by mail) works for all save (create + update) and delete. But on prod, only delete action sends an email. I didn't notice at once delete signals were working so I spent much time looking for an issue caused by firewall (blocked email outgoing). Post Save @receiver(post_save, sender=Navette) def alerte(sender, instance, created, **kwargs): ref = instance.ref user = instance.user.username if created: alert(pour=['tintin@gmail.com'], sujet=f'Nouvelle navette pour la référence {ref} créé par {user}') else: alert(pour=['tintin@gmail.com'], sujet=f'Mise à jour de la navette pour la référence {ref} par {user}') Post Delete @receiver(post_delete, sender=Navette) def alerte(sender, instance, **kwargs): ref = instance.ref user = instance.user alert(pour=['tintin@gmail.com'], sujet=f'La navette pour la référence {ref} a été supprimée par {user}') just for info : alert.py def alert(**kwargs): #ref = kwargs.get('ref', 'noref') de = kwargs.get('de', 'toto@gmail.com') pour = kwargs.get('pour', 'tintin@gmail.com') sujet = kwargs.get('sujet', 'Sujet Général') contenu = kwargs.get('contenu', 'cf. objet du mail') fichier = kwargs.get('fichier', '') host = 'smtp.gmail.com' port = 465 user = settings.EMAIL_HOST_USER passw = settings.EMAIL_HOST_PASSWORD msg = EmailMessage() msg['Subject'] = sujet msg['From'] = de msg['To'] = pour msg.set_content('HTML uniquement') msg.add_alternative(contenu, subtype='html') with smtplib.SMTP_SSL(host, port) as smtp: smtp.login(user, passw) smtp.send_message(msg) As said almost everywhere, I declared my … -
PyCharm: Django templates don't seem to be working?
I am trying to use Django in PyCharm, but the Django templates are not working. For example {% block %} elements and {{variable}} references are not treated specially and when I view the page preview, it just displays it as text? -
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', ), }