Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Couldn't find add-on hobby-dev for PostgreSQL database on Heroku
I'm trying to push my application to Heroku using Django, however when I run heroku addons:create heroku-postgresql:hobby-dev -a (appname) it gives me this error: Couldn't find either the add-on service or the add-on plan of "heroku-postgresql:hobby-dev". ! I have also checked that the free version was changed from November 28th, 2022. Is there any other Database add-ons that is reliable so I can use to deploy my app on Heroku. Any suggestions? -
Rollup complains "is not exported" when it is
I'm running into this error while bundling one JS library which includes a package from another of my JS libraries. Both are bundled via Rollup, as UMD modules. I've reacreated this issue in a separate repo in order to show a simple example. It'd be best to pull the repo and npm run build to see what I'm running into. build/index.js → dist/index.umd.js... (!) "this" has been rewritten to "undefined" https://rollupjs.org/guide/en/#error-this-is-undefined node_modules/some-package/index.umd.js 3: typeof define === 'function' && define.amd ? define(['exports'], factory) : 4: (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["clarakm-env-js"] = {})); 5: })(this, (function (exports) { 'use strict'; ^ 6: var MY_CONSTANT = "this is my constant"; [!] RollupError: "MY_CONSTANT" is not exported by "node_modules/some-package/index.umd.js", imported by "build/index.js". https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module build/index.js (1:9) 1: import { MY_CONSTANT } from 'some-package'; ^ 2: console.log(MY_CONSTANT); 3: //# sourceMappingURL=index.js.map at error (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:210:30) at Module.error (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13578:16) at Module.traceVariable (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13961:29) at ModuleScope.findVariable (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:12442:39) at Identifier.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:8371:40) at CallExpression.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6165:28) at CallExpression.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:9888:15) at ExpressionStatement.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6169:23) at Program.bind (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:6165:28) at Module.bindReferences (/home/josh/Desktop/rollup-issue/node_modules/rollup/dist/shared/rollup.js:13574:18) All of this is built via tsc && rollup -c. Since MY_CONSTANT is clearly exported from some-module, why does Rollup complain that it is not exported? src/index.ts import … -
django don't show form in template ---
django don't show form in template I applied everything in the Django tutorial, but foam does not appear, but I did not know the reason despite my research add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="post"> {% csrf_token %} <hr> {{form}} <hr> <a href="" type="submit">submit</a> </form> {% endblock content %} in forms from django import forms from .models import book class book_form(forms.Form): class meta: model = book fields = '__all__' in views from .models import * from .forms import book_form def addbook(request): bookform = book_form() context = {'form' : bookform} return render(request, 'add_book.html', context) in url path('book/add', views.addbook, name="addbook"), -
Using ForeignKey in Django
Need help guys I am stuck. I've created 4 models, MasterLoan - listing of all loans, LoanExpenses - listing of all expenses incurred by loans, BillMaster - listing of all billing, BillDetails - expenses incurred by loans billed to client. models.py class LoanMaster(models.Model): loan_number = models.CharField(max_length=50, null=True) loan_name = models.CharField(max_length=150, null=True) class LoanExpenses(models.Model): loan_number = models.ForeignKey(LoanMaster, null=True, on_delete=models.SET_NULL) date = models.DateField(blank=True, null=True) expense_type = models.CharField(max_length=10, blank=True, null=True, choices=EXPENSES_TYPE) amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) class BillingMaster(models.Model): bill_number = models.CharField(max_length=50, null=True) bill_date = models.DateField(blank=True, null=True) bill_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) bill_status = models.CharField(max_length=50, blank=True, null=True, default='Unpaid', choices=STATUS) class BillingDetail(models.Model): bill_number = models.ForeignKey(BillingMaster, null=True, on_delete=models.SET_NULL) loan_number = models.ForeignKey(LoanMaster, null=True, on_delete=models.SET_NULL, verbose_name="Loan Number") bill_item = models.CharField(max_length=150, blank=True, null=True) bill_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) How can I automatically pull all the expenses incurred by the loan to a dropdown select for my HTML? Should my BillingDetail.bill_item be a FK to LoanExpenses? -
Making a search bar work in AlpineJS where the searched items in x-data come from x-init
Basically trying to modify the dynamic search bar that can be found in Alpine docs, but with "items" ("bands" in my case) coming from x-init that fetches a JSON. Outside of this search bar all the desired data from this JSON is displayed so it's not like the JSON itself is empty, but in this particular situation x-text doesn't even list any of the values, as if the JSON data never gets to the x-data/"bands" array. This is what I currently have, like I said it's a little modification of the search bar from the docs. <div x-data="{ search: '', bands: [], get filteredItems() { return this.bands.filter( i => i.startsWith(this.search) ) } }" x-init="bands = await (await fetch('/bands/')).json()"> <input x-model="search" placeholder="Search..."> <template x-for="band in filteredItems" :key="band"> <p x-text="`${band.name}`"></p> </template> </div> I'd be grateful if anyone told me what exactly this seemingly straightforward chunk of code is missing. -
I tried to create an html page within django but it does not seem to work
enter image description here For some reaons when i create an html page within django. The html page don't seem to work i attached a picture. anyone willing to help and tell me how to fix it. I tried to create an html page within django but it does not seem to work. -
is there any performance benefit to using bulk_update as compared to just update in django for a same value update?
I have the following piece of code Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions]).update(renewal_notification_sent=True) but I'm wondering if something like updatable_subscriptions = [] subs = Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions]) for sub in subs: sub.renewal_notification_sent = True updatable_subscriptions.append( subs ) # then Subscription.objects.bulk_update(updatable_subscriptions, ["renewal_notification_sent"]) would have any performance benefit. Does calling filter followed by update make 2 database queries? -
JWT authentication does not work in Django Rest Framework after deploying it to IIS on live server
I built a Rest API using Django's Rest framework. And I've deployed it on Windows OS's IIS. When I deploy the application to the live IIS server, it throws the following issue even though it functions well on the local IIS server. Note: I have passed the Authorization header correctly. { "errors": { "detail": "Authentication credentials were not provided." } } -
How to fill automatically selectsize JS when edit the HTML form?
I have a form with 3 fields which are 2 input text and 1 select from dropdown menu. When I add the data then I want edit them, I want to the old data appearing on the field. Input text field is already OK but the select field (Country) which I build using select size js is not appearing the old value. <form action="" method="post" id="EditForm"> {% csrf_token %} <div class="col-md-12"> <div class="form-group"> <label for="NameEdit" class="control-label">Name</label> <input name="Name" id="NameEdit" type="text" class="form-control" required oncopy="return true;" onpaste="return true;" oncut="return true;" /> </div> <div class="form-group"> <label for="AddressEdit" class="control-label">Address</label> <input name="Address" id="AddressEdit" type="text" class="form-control" data-toggle="popover" data-trigger="focus" required data-placement="left" oncopy="return true;" onpaste="return true;" oncut="return true;" /> </div> <div class="form-group"> <label for="CountryEdit" class="control-label">Country</label> <select name="CountryEdit" type="text" class="form-control" id="CountryEdit" required data-placement="left" oncopy="return true;" onpaste="return true" oncut="return true;" > <option value="">Select the country</option> {% for x in countries %} <option value="{{x.CountryCode}}">{{x.CountryCode}} ({{x.CountryName}})</option> {% endfor %} </select> </div> </div> </form> $(document).on('click', '.editUserBtn', function () { var user = $(this).data('id'); editUrl = 'edit/'+user; var currentURL = window.location.href; console.log(currentURL + 'edit/' + user); $.ajax({ type: "GET", url: currentURL + 'edit/' + user, success: function (data) { $('#EditForm').attr('action', 'edit/' + user); $('#EditModal').modal('show'); $('#NameEdit').val(data.Name); $('#AddressEdit').val(data.Address); $('#CountryEdit option:checked').val(data.Country); } }) }); -
Return JSON or template based on query parameter with django restframework
''' class ProfileList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'profile_list.html' def get(self, request): queryset = Profile.objects.all() return Response({'profiles': queryset}) ''' As documented, the above View renders and returns a html template. However, how to control the view to return the json or html template in the view? For example, by providing parameter as ?type=html, it returns the html page; and with ?type=json it return the json data. -
Django - Counting ManyToMany Relationships
In my model, I have many Things that can have many Labels, and this relationship is made by user-submitted Descriptions via form. I cannot figure out how to count how much of each Label each Thing has. In models.py, I have: class Label(models.Model): name = models.CharField(max_length=100) class Thing: name = models.CharField(max_length=100) class Description: thingname = models.ForeignKey(Thing, on_delete=models.CASCADE) labels = models.ManyToManyField(Label,blank=True) If we say our current Thing is a cat, and ten people have submitted a Description for the cat, how can we make our template output an aggregate count of each related Label for the Thing? For example: Cat 10 fluffy 6 fuzzy 4 cute 2 dangerous 1 loud I've tried a few things with filters and annotations like counts = Label.objects.filter(description_form = pk).annotate(num_notes=Count('name')) but I think there's something obvious I'm missing either in my views.py or in my template. -
"formfield_overrides" vs "formfield_for_dbfield()" vs "form" vs "get_form()" to change the width of the field in Django Admin
For example, there is Person model below: # "models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() def __str__(self): return self.name Then, when using formfield_overrides, formfield_for_dbfield(), form or get_form() below: # "admin.py" from django.contrib import admin from .models import Person from django.db import models from django import forms @admin.register(Person) class PersonAdmin(admin.ModelAdmin): formfield_overrides = { # Here models.PositiveSmallIntegerField: { 'widget': forms.NumberInput(attrs={'style': 'width:100ch'}) }, } Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def formfield_for_dbfield(self, db_field, request, **kwargs): field = super().formfield_for_dbfield(db_field, request, **kwargs) if db_field.name == 'age': field.widget.attrs['style'] = 'width: 100ch' return field Or: # "admin.py" from django.contrib import admin from .models import Person from django import forms class PersonForm(forms.ModelForm): age = forms.CharField( widget=forms.NumberInput(attrs={'style':'width:100ch'}) ) @admin.register(Person) class PersonAdmin(admin.ModelAdmin): form = PersonForm # Here Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['age'].widget.attrs['style'] = 'width: 100ch;' return form I can change the width of age field on "Add" and "Change" pages as shown below: Now, are there any differences between formfield_overrides, formfield_for_dbfield(), form and get_form() to change the width of the field in … -
ValueError at /book/add Field 'id' expected a number but got 'add' --- django
A working site was bringing the collection of books with its content displayed But when I add a function def addbook(request): it gives me a problem this: ValueError at /book/add Field 'id' expected a number but got 'add'. in -- all_book.html: {% extends 'base.html' %} {% block content %} <h1>kljgf</h1> <a href ="{% url 'addbook' %}">Add Book</a> {% for book in books %} <h3> <a href = "{% url 'detail_book' book.id %}">{{book.namebook}}</a> </h3> <hr> {% endfor %} {% endblock content %} in views: def detail_book(request, id): boo = book.objects.get(id=id) context = {'book' : boo} return render(request, 'detail_book.html', context) def addbook(request): book_form = book_form() context = {'form' : book_form} return render(request, 'add_book.html', context) in url: path('book/<id>', views.detail_book, name="detail_book"), path('book/add', views.addbook, name="addbook"), in add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="POST"> {% csrf_token %} {{form}} </form> {% endblock content %} -
How to create a function for Phone Dialing [for Python Django]?
I am an Python Django newbie , trying to find an function to add to my website im working on. What Im trying to do is simple operation - when you click a "Call us" button in my website, to open the Phone Dial with the specific number inputed in the phone dial input line not call immeadiately, just automatically prewrited the set phone number, as shown in the picture I searched alot in google,git,youtube, but I couldn't find what exacly I am looking for. -
How can i add am option box into my Folium Draw Toolbar?
I'm working on a proyect where i use Folium and plugin.drawn in order to handle markers and polygons, The idea it is simple, save all markers en polygons created on the map. It is a collaborative map On the map I have three layers (layer 1: Ubicacion de mujeres, layer 2: Zona de Violencia and layer 3: Poblaciones diversas). What i need is to add markers for any layer the user choose so i would like to add an option box with those layers as options as you can see in the image my options example here it is my map too current map At the moment i'm making a deep research about it. I tried to add macros like this {% macro script(this, kwargs) %} but i don't get to know how to do it correctly Any idea that you recommend me is going to be so helpful Thank you guys PD: I'm new in this -
Flexible Django Filter (django-filter package)
I'm currently implementing some filters and I'm facing multiple problems. First of all my checkboxes don't work, as in I can't select them: this is my .html code: <form method="get"> <div class="toggle-list product-categories"> <h6 class="title">Sorteer</h6> <div class="shop-submenu"> <ul> {{ filter.form.order_by }} </ul> </div> </div> <div class="toggle-list product-categories"> <h6 class="title">Merk(en)</h6> <div class="shop-submenu"> <ul> {% for f in filter.form.brand %} <li> <input type="checkbox"> <label>{{ f }}</label> </li> {% endfor %} </ul> </div> </div> <input type="submit" value="Filter"> </form> my filter in filters.py: class SortFilter(django_filters.FilterSet): ORDER_BY_CHOICES = ( ('-discount_sort', 'Hoogste korting'), ('-new_price', 'Hoogste prijs'), ('new_price', 'Laagste prijs'), ) order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order', empty_label=None) brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects .order_by('brand') .filter(categorie='eiwitten') .values_list('brand', flat=True).distinct() , widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Product fields = ['brand'] def filter_by_order(self, queryset, name, value): return queryset.order_by(value) view function for this certain page: def eiwit(request): # filter alleen eiwitproducten eiwit_list = ['eiwitten'] eiwit_filter = Q() for item in eiwit_list: eiwit_filter = eiwit_filter | Q(categorie=item) products = models.Product.objects.filter(eiwit_filter) product_amount = len(products) # sorteer filter filtered = SortFilter( request.GET, queryset=products ) # paginator paginator = Paginator(filtered.qs, 12) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) product_front_end = { 'final_products': response, 'filter': filtered, 'count': product_amount, … -
Return all values to Map To Model Serializer
I have the following JSON jsonData = {'CompanyId': '320193', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2020-09-26'}, 'value': '39789000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2019-09-28'}, 'value': '50224000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2018-09-29'}, 'value': '25913000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2021-09-25'}, 'value': '35929000000'}], 'NetIncomeLoss': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'value': '55256000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '55256000000'}]} Model: class CashFlow(models.Model): Id = models.AutoField(primary_key=True) Decimal = models.TextField(null=True) UnitRef = models.TextField(null=True) Period = models.TextField(null=True) Value = models.TextField(null=True) CompanyId = models.TextField(null=True) CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = models.TextField( null=True) NetIncomeLoss = models.TextField(null=True) Serializer: class CashFlowSerializer(serializers.ModelSerializer): CompanyId = serializers.CharField() PeriodInstant = serializers.CharField() PeriodStartDate = serializers.CharField() PeriodEndDate = serializers.CharField() Decimal = serializers.CharField() UnitRef = serializers.CharField() Value = serializers.CharField() CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = serializers.CharField() NetIncomeLoss = serializers.CharField() class Meta: model = CashFlowTable fields = "__all__" def create(self, validated_data): print(**validated_data) CashFlowTable.objects.create(**validated_data) View: … -
Uploading images with TinyMCE
I'm trying to install TinyMCE to my django project for blog posts, I have the initial content block working but It isn't allowing me to upload images with the following errors: Forbidden (CSRF token missing.): /admin/mhpapp/testmodel/add/static/images/images I have the app added in my settings.py Settings.py: urlpatterns = [ path('tinymce/', include('tinymce.urls')), TINYMCE_DEFAULT_CONFIG = { "height": "320px", "width": "960px", "menubar": "file edit view insert format tools table help", "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code " "fullscreen insertdatetime media table paste code help wordcount spellchecker", "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft " "aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor " "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | " "fullscreen preview save print | insertfile image media pageembed template link anchor codesample | " "a11ycheck ltr rtl | showcomments addcomment code", "custom_undo_redo_levels": 10, "images_upload_url": 'static/images/images', "images_upload_handler": "tinymce_image_upload_handler" } TINYMCE_EXTRA_MEDIA = { 'css': { 'all': [ ], }, 'js': [ "https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js", "admin/js/tinymce-upload.js", ], } Any help would be greatly appreciated. -
Django, sqlite to mysql migration, json decoder issue with migrated pages
I have an early and simple django project, to get things started we were using a sqlite database during setup. Someone else created some django pages with various plugins, but since these are actual pages and not templates, they are stored in the database. We realized that we should've migrated to mysql before making these pages and now we have 2 options. 1, we migrate and he builds the pages again which is time consuming, or 2, we find a way to migrate the sqlite database contents to mysql. I've been trying to figure out the second option, migrating our sqlite db to mysql. I've scoured google and nothing has been as simple as I would like, but I've been able to create as sql dump file, follow some steps to alter the format of said file, and dump said file into the new mysql database. However, while the data is there and I can access the admin and new pages, the migrated pages all run into an error when I try to view the pages or copy & paste them in the django admin. And for clarity, I created an almost blank page before the migration (tried this a … -
how to make auto logout using ajax and django
I would like to write js function for auto logout using ajax and django. Actually i did and succeded. it works fine. but i do not know is it a proper way to do it. i post my code and i need your reviews and revised or improved code or proper way to implement the auto logout funtion. Here my code. views.py def user_logout(request): logout(request) is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest" if is_ajax: print("auto logout works") return JsonResponse({"redirect_link":"/login"},status=200) else: print("manuel logout works") return redirect("/login") ajax <script language="javascript"> jQuery(document).ready(function(){ function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + "=")) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } setInterval(function(){ jQuery.ajax({ url: "{% url 'user-logout' %}", headers: {"X-Requested-With": "XMLHttpRequest","X-CSRFToken": getCookie("csrftoken"),}, type: 'GET', dataType: 'json', success:function(response){ window.location.href="{% url 'user-login' %}" alert("You are logged out"); } }); }, 5000); }); </script> -
How to access child model from a parent model using Django ORM?
Here are my models: class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') class Product(models.Model): description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() collection = models.ForeignKey(Collection, on_delete=models.PROTECT) I have two models here, one of which is the parent (Collection), and the other is the child (Product). So if I need to filter the queryset based on the title attribute of the Collection class, I can type a queryset like this. query_set = Product.objects.filter(collection__title = 'beauty') Notice: Here I am accessing the parent using the child; the question is, how can I do the opposite? I tried this line of code but i got an error saying:Cannot resolve keyword 'product_set' into field. query_set = Collection.objects.filter(product_set__inventory__lt=10) -
Django Model Choice Field select not working
I have the following form: forms.py class TipoDePagoForm(forms.Form): tipo_de_pago = forms.ChoiceField(widget=forms.RadioSelect, choices=FORMAS_PAGO, required=True) folio = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Folio', 'aria-describedby': 'basic-addon2' }), required= False) medio_venta = forms.ModelChoiceField(queryset= MediosVenta.objects.all()) the ModelChoiceField in HTML is represented like this: <div class="d-block my-3"> <select name="{{ tipodepagoform.medio_venta.nombre }}" id="{{ tipodepagoform.medio_venta.id_for_label }}"> {% for value, name in tipodepagoform.fields.medio_venta.choices %} <option value="{{ value }}" {% if value == tipodepagoform.medio_venta.value %} selected {% endif %}>{{ name }}</option> {% endfor %} </select> </div> when doing the POST in the view (part of the view): def post(self, *args, **kwargs): today = date.today() tipodepagoform = TipoDePagoForm(self.request.POST or None) if tipodepagoform.is_valid(): tipo_de_pago = tipodepagoform.cleaned_data.get('tipo_de_pago') folio = tipodepagoform.cleaned_data.get('folio') medio_venta = tipodepagoform.cleaned_data.get('medio_venta') print(medio_venta) the form_is is not valid and is giving me the following error: <ul class="errorlist"><li>medio_venta<ul class="errorlist"><li>This field is required.</li></ul></li></ul> printing the form I see that is selecting the None value: <tr><th><label for="id_medio_venta">Medio venta:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select name="medio_venta" required id="id_medio_venta"> <option value="" selected>---------</option> <option value="1">Gimnasio</option> <option value="2">Marketplace</option> <option value="3">Membresías</option> </select></td></tr> I don´t know why even if I select any option with a value it does not actually select. -
Webhooks from Azure to Django. Validation problems
I am super stuck trying to validate (I think) the Azure end of my webhook. I have an Event Grid System Topic that is successfully updating (POST) to a dummy webhook site. The problem is when I try to use this webhook in a view I receive this error in Azure. If anyone has any ideas of what I am doing wrong it would be great because I have gone through 50+ stack overflow questions trying to figure it out. -
So I'm learning to create a confirmation email address while registering an account using Django
This is urls.py `from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name="home"), path('signup', views.signup, name="signup"), path('activate/<uidb64>/<token>', views.activate, name="activate"), path('signin', views.signin, name="signin"), path('signout', views.signout, name="signout"), ]` This is views.py myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.is_active = False myuser.save() messages.success(request, "Hey, Your Account has been successfully created. We have sent you a confirmation email. Please confirm your email in order to activate your account.") #welcome email subject = "Welcome to Django Login Project!!" message = "Hello" + myuser.first_name + " !! \n" + "Welcome to Django Login Project!! \n Thank You for visiting our website \n We have sent you a confirmation email, Please confirm your email address in order to activate your account. \n\n Thanking You\n Shalini Singh" from_email = settings.EMAIL_HOST_USER to_list = [myuser.email] send_mail(subject, message, from_email, to_list, fail_silently= True ) #email address confirmation current_site = get_current_site(request) email_subject = "Confirm your email @ Login Django Project!!" message2 = render_to_string('email_confirmation.html',{ 'name' : myuser.first_name, 'domain' : current_site.domain, 'uid' : urlsafe_base64_encode(force_bytes(myuser.pk)), 'token' : generate_token.make_token(myuser) }) email = EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently = True email.send() return redirect('signin') return render(request, "authentication/signup.html") def activate(request, uidb64, token): try: uid … -
How to execute a value from coroutine object in sync celery task?
I have 2 functions - async, which returns the coroutine object with int value, and the sync function, whic is the @shared_task, where the variable must stores the value from the async function (int) My async function, that returns the coroutine with int in it: async def club_count(club_id): return get_number_of_club(club_id).get_clients_in_club_count(club_id) There is my sync function that shared_task with making a record into the Django admin Problem with the variable "club_load" that must stores the value from my async function But when I try to run the celery, I get the error of operation between coroutine and int in "procent_club_load" @shared_task def get_club_load(): all_clubs = Club.objects.all() for club in all_clubs: if club.monitoring_club_load == True: club_load = club_load_json(club.id) club_capacity = club.club_load procent_club_load = None if club_capacity: procent_club_load = int((club_load / club_capacity)*100) club_load_record = ClubLoadModel( club_id = club.id, created_at = timezone.now(), weekday = timezone.localtime().weekday() + 1, club_load = club_load, procent_club_load = procent_club_load ) club_load_record.save() else: pass What the solution that I can execute the value from coroutine object into the variable of sync function that a shared task? I'm trying to store a value from my async function in the variable of sync celery task Problem is that celery couldn't make operations with …