Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating chart.js with ajax ,conditionnal error
i'm trying to auto-update my chart js graph trough ajax , but my if statement always return the wrong awnser on the first iter , any idea why ? thank again. , tell me if you need anything more. var datanp = JSON.parse("{{data|escapejs}}"); var label = JSON.parse("{{label|escapejs}}"); console.log('checkin',datanp) console.log('follow up',label) const data = { labels: label, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(0, 99, 132)', borderColor: 'rgb(0, 99, 132)', data: datanp, }] }; const config = { type: 'line', data: data, options: {} }; const myChart = new Chart( document.getElementById('myChart'), config ); setInterval(addData, 10000); //setting the loop with time interval function addData() { $.ajax({ method: 'get', url: "/hello-world/", success: function(response) { let labels = String(response.labels); let datas = response.datas; console.log('check', String(label.slice(-1))); console.log('in', labels); myChart.data.labels.slice(-2)[1]); if (labels == String(label.slice(-1))) { console.log('same content'); } else { console.log('updating content', labels, 'to', String(label.slice(-1))); myChart.data.datasets[0].data.push(datas); myChart.data.labels.push(labels); myChart.update(); }; myChart.update(); } } }); } the values returned by all the variable are correct , everything is running except the if who is always wrong on the first iter . It give the correct awnser afterward but the first issue create a duplicate of the last value . def hello_world_view(request): _,data=connect_influx(listed={"mesure": ["U", [0, 10], "mesure"]},database='test') labels=dumps(data.timestamp.astype(str).values.tolist()[-1]) … -
SwiperJs slides not showing on Django template
So,I am trying to show images in slider in my small blog. In my index page I am looping through all my blogs. And If I have images, I am looping through images in Swiper js slider. I think I have done everything appropriately. But no image or slider is showing in the screen. No error in the console. Here is my models class Blog(models.Model): title = models.CharField(max_length=200, null=True, blank=True) body = models.TextField(null=True, blank=True) created = models.DateTimeField() class ImageUrl(models.Model): blog = models.ForeignKey(Blog, related_name="image_urls", on_delete=models.CASCADE) url = models.URLField(max_length=1000) Here is my template {% for blog in page_obj %} <div class="mx-3 block content"> {% if not blog.image_urls.count == 0 %} <div class="swiper mySwiper{{blog.id}}"> <div class="swiper-wrapper"> {% for image in blog.image_urls.all %} <div class="swiper-slide"> <div class="swiper-zoom-container"> <img data-src="{{image.url}}" class="swiper-lazy" /> </div> <div class="swiper-lazy-preloader"></div> </div> {% endfor %} </div> <div class="swiper-pagination"></div> </div> {% endif %} </div> {% endfor %} Css .swiper { width: 100%; height: 100%; } .swiper-slide { text-align: center; font-size: 18px; background: #000; } .swiper-slide img { width: auto; height: auto; max-width: 100%; max-height: 100%; -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); transform: translate(-50%, -50%); position: absolute; left: 50%; top: 50%; } <script> {% for blog in page_obj %} {% … -
Django Choice Queries with annotate
I am stucked in django annotate query. here is certain Model I have been working. class Claim(model.Model) CLAIMS_STATUS_CHOICES = ( (2, PROCESSING), (1, ACCEPTED), (0, REJECTED) ) status = models.CharField(max_length=10,choice=CLAIMS_STATUS_CHOICES) problem is I don't want to annotate processing choice but I just want to get individual status count of accepted and rejected. Here is what I tried. claim = Claim.objects.filter(Q(status=1) | Q(status=0)) total_status_count = claim.count() status_counts = Claim.objects.filter(Q(status=1) |Q(status=0)).annotate(count=Count('status')).values('count', 'status') but I am getting multiple rejected and accepted queries this is what I got as op [ { "total_claims": 3, "status_count": [ { "status": "1", "count": 1 }, { "status": "0", "count": 1 }, { "status": "1", "count": 1 } ] } ] what I wanted [ { "total_claims": 3, "status_count": [ { "status": "1", "count": 2 }, { "status": "0", "count": 1 } ] } ] Any help regarding this? -
Session data is not getting updated - decoding the session key
Need help with a Django related doubt. I've been trying to develop an ecommerce webapp using Django. When I try to get the session data after clicking on 'Add to Basket' it shows the response from the 'init' method and not the 'add' method. This is the button: <button type="button" id="add-button" value="{{product.id}}" class="btn btn-secondary btn-sm">Add to Basket</button> Ajax Script: <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> View.py file: from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import JsonResponse from store.models import Product from .basket import Basket def basket_summary(request): return render(request, 'store/basket/summary.html') def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product = get_object_or_404(Product, id=product_id) basket.add(product=product) response = JsonResponse({'test':'data'}) return response urls.py file: from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary'), path('add/', views.basket_add, name='basket_add'), ] Basket Class: class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self, product): product_id = … -
Django - No video supported format and MIME type found
When I run python manage.py runserver the videos on a webpage work. I deployed the web with apache2 and instead of the videos I see No video with supported format and MIME type found. Did I omit something when deploying the web? When I deployed it the first time it worked, but now it is not working. Here is my /etc/apache2/sites-available/001-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerName video.xyz.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files … -
Getting ValueError: Field 'id' expected a number but got 'favicon.ico'
I am follwing this YT tutorial https://www.youtube.com/watch?v=A_j5TAhY3sw, on 4:23:18,when he enters all the details he is able to submit ,but I get the following error: ValueError: Field 'id' expected a number but got 'favicon.ico'. (On my VScode console) Request Method: POST (On my Browser) Request URL: Django Version: 4.0.4 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: postions_postion.invoice_id Exception Location: D:\Python\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Its working fine using the Django admin. This is the views.py file class AddPostionsFormView(FormView): form_class = PositionForm template_name = 'invoices/detail.html' def get_success_url(self): return self.request.path This is the model.py for positions: from django.db import models from invoices.models import Invoice # Create your models here. class Postion(models.Model):#models.Models to inherit from django.db.models.Model invoice = models.ForeignKey(Invoice,on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True,help_text="optional info") amount=models.FloatField(help_text="in US $") created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Invoice : {self.invoice.number},postion title={self.title}" This is the sqlite ddb: id title description amount created invoice_id 1 cleaning the kitchen 30 2022-05-25 07:56:38.750572 1 2 Tarnslating test clip 100 2022-05-28 05:26:46.370414 1 3 Test Test des 300 2022-06-01 06:53:08.567545 10 4 Good test des 222 2022-06-01 07:08:36.972521 10 This is the mega link for uptill where I have completed the course: https://mega.nz/folder/EUoVhQbT#iN16PXAOcMv9Qr55MlUSIA -
Django Table.render_foo methods with Boundcolumn
I'm confused, please tell me how to put the value of another Term_Implementation field in Table.render_foo methods? It follows from the documentation that I have to use Boundcolumn for this, but I couldn't find a concrete example to implement this. Table.render_foo methods BoundColumns class EvensList(IncidentsTable, tables.Table): class Meta: model = AkpEvents sequence = ('Term_Implementation', 'Status') Term_Implementation = tables.DateColumn(empty_values=(),) Status = tables.Column(empty_values=(),) def render_Status(self, value, column, columns): if value == 'Выполнено': column.attrs = {'td': {'class': 'table-success'}} elif value == 'В работе': column.attrs = {'td': {'class': 'table-warning'}} elif columns['Term_Implementation'] <= date.today(): column.attrs = {'td': {'class': 'table-danger'}} else: column.attrs = {'td': {'class': ''}} return value -
Annotating in django using a field from another model
I'm trying to calculate a field that it's a sum agregation when two of other fields are the same. The problem is that one of this fields is from the same model as the sum field, but the other one is from another model. models.py: class Node(model.Model): text = models.CharField(max_length=100, verbose_name=_('Text')) perimeter_ID = models.CharField(max_length=100, verbose_name=_('Perimeter_ID')) pos_x = models.FloatField(verbose_name=_('Position X')) pos_y = models.FloatField(verbose_name=_('Position Y')) class Meta: ordering = ['pk'] class Routes(models.Model): from_id = models.ForeignKey(Node, on_delete=models.PROTECT, verbose_name=_('From'), related_name='transport_from') to_id = models.ForeignKey(Node, on_delete=models.PROTECT, verbose_name=_('To'), related_name='transport_to') n_box = models.FloatField(verbose_name=_('Number of boxes')) day = models.CharField(max_length=10, verbose_name=_('day')) class Meta: ordering = ['from_id__id', 'to_id__id'] And in my views, I'm first filtering by day as the request will be something like filter/?day=20220103 and then I want to know the sum of boxes when from_id and perimeter_id are the same (the perimeter_id of the node corresponding to to_id). So, I need somehow to make the relation between, the to_id node and its perimeter_id. views.py: class sumByPerimeterListAPIView(ListAPIView): queryset = Routes.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = { 'day': ["in", "exact"], } def get(self, request, **kwargs): queryset = self.get_queryset() filter_queryset = self.filter_queryset(queryset) values = filter_queryset.values('from_id')\ # TODO: INCLUDE perimeter_id OF to_id .annotate(n_box=Sum('n_box')) return Response(values) I've been reading about subquery and OuterRef in … -
DRF easy method for reverse lookup to get a single item, not a list for 1:1 relations?
In my Django App I am using a model serializer for the API to get read access tot he objects in the DB. For one API call I have to provide data from different, but related objects in one result. class Car(models.Model): name = models.Charfield() class Driver(models.Model): name = models.Charfield() car = ForeignKey(Car, on_delete=models.CASCADE, null=Fals, blank=False) The problem I have is that I always get back a list instead of a single object if I use nested serializers. For example class CarSerializer(serializers.ModelSerializer): driver = DriverSerilizer(source='driver_set', many=True, read_only=True) gives back a list with one item if there is a driver. If I set "many=False" I get a list with one driver object where all values are null. So I use a MethodSerializer now to get the first Item in the list, but that seems to be like a lame solution to me. driver = serializers.SerializerMethodField() def get_driver(self, obj): driver_list = DriverSerilizer(obj.driver_set.all(), many=True).data driver = None if len(driver_list) ==1: driver = driver_list[1] return driver So it works, but isn't there a better way? -
empty image field in formset not valid and shows no errors
Why form not valid an empty image field... fall into a database empty records if I do a print (formset.is_valid) it returns me true and creates 3 fields with empty image when the image field is empty and should instead give me an error. views def product_gallery_create_view(request, id): ProductGalleryFormset = formset_factory(FormCreateProductGallery, extra = 3) product = Product.objects.get(id = id) if request.method == "POST": formset = ProductGalleryFormset(request.POST, request.FILES) if formset.is_valid(): for form in formset: if form.has_changed(): instance = form.save(commit = False) instance.product = product instance.save() return redirect('home') else: formset = ProductGalleryFormset() context = {'formset':formset} return render(request, 'crud/product_gallery_create.html', context) model class ProductGallery(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_gallery') image = models.FileField(upload_to ='galleria/') form class FormCreateProductGallery(forms.ModelForm): class Meta: model = ProductGallery exclude = ['product'] html {% if formset.errors %} <div class="alert alert-danger"> {{ formset.errors }} </div> {% endif %} <form method="post" enctype='multipart/form-data' class="notifica" autocomplete="off" novalidate> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="d-flex align-item-center justify-content-between"> <div><small>img</small> {{ form.image }}</div> </div> <hr class="mt-4 mb-4"> {% endfor %} <input type="submit" value="crea galleria" class="btn btn-info w-100"> </form> -
Django - OneToOneField does not work - RelatedObjectDoesNotExist: User has no userdetail
I am trying to extend the User model with this: class UserDetail(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE, verbose_name="Používateľ") def __str__(self): return f"{self.user.first_name} {self.user.last_name} ({self.user.username}) / Celková hodnota všetkých objednávok používateľa: {self.total_value_of_users_orders} €" @property def total_value_of_users_orders(self): all_orders = Order.objects.all().filter(user=self.user, status__in=["NW", "WP", "PD", "IP", "ST", "DN"]) total_value = 0 for order in all_orders: total_value += order.total_value return total_value However, when I try to access the total_value_of_users_orders property, it does not work: from django.contrib.auth import get_user_model User = get_user_model() all_users = User.objects.all() for u in all_users: u.userdetail.total_value_of_users_orders it shows this exception: RelatedObjectDoesNotExist: User has no userdetail. What am I doing wrong? I expect all users to have the total_value_of_users_orders property which either returns 0 (if there are no Orders belonging to the given user) or the exact value (if there are Orders belonging to the given user). Thank you -
How can I create Automatic user profile in django
how can i create automatic user profile ? is there any way i can create automatic user profile when a user submitted the registration form In django, Like Stack Overflow. In Stack Overflow when a new user created an account with either Gmail, Facebook Or Github The Stack Overflow will create automatic user profile for He/she so He/She can edit it of His/Her choices. I know how to implement an edit functionality using UpdateView. I just want to create automatic user profile when the form is submitted. can i create an automatic user profile in django if yes then How ? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='avatar', blank=True, null=True) stories = RichTextField(blank=True, null=True) twitter = models.URLField(max_length=300, blank=True, null=True) website = models.URLField(max_length=300,blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=80, blank=True, null=True) slug = models.SlugField(unique=True, max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) def __str__(self): return str(self.user) my user registration views: def register(request): if request.method == 'POST': username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email or user name Already taking') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'username … -
Ordering django model queryset based on child model which has OneToOne Relation with parent
Here are my Django Models Product Model class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='productCategory') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='productBrand') name = models.CharField(max_length=255) hsnCode = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) . . . Product Inventory Model class ProductInventory(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, related_name="productInventory") inventoryInWarehouse = models.IntegerField(default=0) . . . I want to order the query set based on high to low inventory what will be the queryset for this I want to Product order like this | product | price | ..... | inventory | | ------ | ----- | ----- | --------- | | T-shirt | 647 | ... | 100 | | xxxxxxx | 876 | ... | 78 | | xxxxxxx | 356 | ... | 64 | | xxxxxxx | 878 | ... | 43 | | xxxxxxx | 999 | ... | 23 | -
How can I prevent an endpoint from directly accessing only redirection can access not the user?
I am making a website where after signing up, it redirects to OTP endpoint. I don't want that URL to be accessible directly by user. I only want to be accessible when a function like signup redirects towards that endpoint. How can I do that? Here is my code Forms.py class OTP_Form(forms.ModelForm): class Meta: model = OTP fields = ("otp", ) otp = forms.CharField(label="Enter your OTP", required=True, widget=forms.PasswordInput(attrs={'placeholder': 'e.g. 123456'})) Here is the view for OTP def phone_verification(request): try: if request.method == "POST": otp = request.session.get('otp') username = request.session.get('username') first_name = request.session.get('first_name') last_name = request.session.get('last_name') email = request.session.get('email') password = request.session.get('password') phone = request.session.get('phone') age = request.session.get('age') otp_form = OTP_Form(request.POST) if otp_form.is_valid(): get_otp = otp_form.cleaned_data['otp'] if get_otp == otp: user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name, last_name=last_name, last_login=str(datetime.now(pytz.timezone('Asia/Karachi')))) customer = Customer.objects.create( user=user, phone=phone, age=age) user.save() customer.save() otp_entry = OTP.objects.create(phone=phone, otp=otp) otp_entry.save() messages.success(request, 'Your account has been creaated') return redirect('login') else: messages.error(request, 'Incorrect OTP') return redirect('otp') else: messages.error(request, 'Please enter the OTP again') return redirect('otp') else: otp_form = OTP_Form() return render(request, 'otp.html', {'otp_form': otp_form}) except: return ValidationError("An error occured while verifyig otp") -
"Response_status": "Invalid data provided", "Error": null}
I am in a project of migrating an old project which is in python 2.6 to the newest current version. python 2 except Exception,e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':e.message})) I have changed to this python 3 except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':print(e)})) *Note: Tried 'Error':e, 'Error':str(e) and 'Error':e.str() But got a 500 response error like this {"Response": "Failure", "Response_status": "Invalid data provided", "Error": null} Need help to solve this issue guys! Update...This is my views.py def registerUser(request): # permission_classes = (permissions.IsAuthenticated,) if request.method == 'POST': try: received_json_data=json.loads(request.body) referralid=received_json_data.get('referralid') received_json_data["name"]=str(received_json_data.get("firstname"))+' '+str(received_json_data.get("lastname")) latestid=1 if tbl_user_profile.objects.all().count()>0: latestid=tbl_user_profile.objects.latest('userid').userid + 1 serializer = tbl_user_profileSerializer(data=received_json_data) if serializer.is_valid(): try: if str(received_json_data.get('role')) == '3': yearsago = datetime.now() - relativedelta(years=25) serializer.save(dob=yearsago.date(),gender=1,userid=latestid) emailid = serializer.data.get('emailid') username = serializer.data.get('name') password = received_json_data.get('password') userid=serializer.data.get('userid') role=tbl_role.objects.get(roleid=received_json_data.get('role')) user=tbl_user_profile.objects.get(userid=userid) myuservalues=MyUsers.objects.create_user(username,emailid,password) myuservalues.userid=user myuservalues.roleid=role myuservalues.userPassword=password myuservalues.save() usersettings=tbl_user_settings.objects.create(user_id_id=user.userid,isprivacy=1) usersettings.save() if referralid is not None and len(str(referralid))>0: relation=tbl_coach_user_mapping.objects.create(coachid_id=referralid,userid_id=userid,status=2) response=sendMail(str(emailid), str(password), '/templates/CyberHealth/registrationTemplate.html', 'CyberHealths Registration',None) verifyMyEmail(userid) user={'Response':'Success','Response_status':'', 'User_Profile':serializer.data} if response=='Success': return JsonResponse(user) else: #Error occured while email send return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':response})) else: return HttpResponse(status=403,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'User not allowed'})) except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':print(e)})) else: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':serializer.errors})) except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':print(e)})) else: return HttpResponse(status=405,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Method not allowed'})) -
Django API Authentication using azure AD
I am very new to Django and need a bit of help around authentication. The requirement is that our Django API uses azure AD for authentication. I not only need to authenticate but also need check the user role for authorization. Can anyone please provide me some details/docs that I can refer to. Thank you -
Sending user agent in flask API URL
I am trying to maintain logs for all the users who are logged into the Django platform and write all the information into a CSV file. I have made a flask API which will extract information like current user logged into the Django platform and user agent. But i am not able to pass user agent into the URL and getting error message HTTPStatus.BAD_REQUEST Attaching my API code below. @app.route('/usernameLogs/<username>/<userAgent>') def usernameLogs(username,userAgent): List=[username,userAgent] with open(username_logs, 'a', newline='') as f_object: writer_object = writer(f_object) writer_object.writerow(List) f_object.close() return "Success" This is my code in Django views.py def username_log(username, userAgent): try: request_url = "https://127.0.0.1:5000/usernameLogs/{}/{}".format(username, userAgent) res = requests.request('GET', request_url) except: res = 'fail' return res This is how I am calling API. def index(request): if request.user.is_anonymous: return redirect("/") #---------logs----------- try: userAgent = request.headers.get('User-Agent') username_log(request.user, userAgent) except: pass #---------logs----------- return render(request, 'index.html') I verified that I am getting user agent by printing it. I think the issue is that i am not able to pass user agent into the URL as it has some special characters. If anyone can suggest what alternative can be done to fulfill the requirement, it will be helpful. Thanks in advance! -
How to select start date to end date filter using django and third party api
I am using another API in my new Django project for plotting the data from the start date to the end date, but I have no idea how I could define the Django function without a model for the rest API; here, I am attaching my Django view.py file and HTML file view.py file def index(request): site_url = 'http://172.24.105.27:8092/' headers = {'Accept': 'application/vnd.github.v3+json','Authorization':'Basic Q'} response = requests.get(site_url, headers=headers) print(response) response_json = response.json() repositories = response_json['R']['L'] first_repo = repositories[0] repo_names, repo_stars = [], [] for repo_info in repositories: repo_names.append(repo_info['M']) repo_stars.append(repo_info['A']) data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}] layout = {'title': 'MD Data','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import'}} fig = {'data': data_plots, 'layout': layout} plot_div = offline.plot(fig, output_type='div') return plot_div def index_view(request): my_graph = index(request) context={'graph':my_graph} if request.method == "POST": queryset = index.object.all() fromdate = request.query_params.get('start_date', None) todate = request.query_params.get('end_date', None) if fromdate and todate: queryset = queryset.filter(timstamp__range=[fromdate, todate]) return render(request,"index.html",queryset) return render(request, "index.html", context) html file From:<input type = "date" name = "fromdate"/> To:<input type = "date" name = "todate"/> <input type = "submit" value = "Search"/> {% if graph %} {{ graph|safe }} {% else %} <p>No graph was provided.</p> {% endif %} Could anyone help … -
Count number of users which having total amount less than X:number
I have an amount let's say 10000. I want to find how many users are present in the table they have bought something of a total amount less than or equal to 10000. class SaleTransaction(models.Model): trans_id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sales') amount = models.FloatField() created_at = models.DateTimeField(auto_now_add=True) Example: trans_id user amount created_at 1 12 1200.0 2022-03-12 2 34 5000.0 2022-03-12 3 17 1000.0 2022-03-12 4 29 5000.0 2022-03-12 here 4 users have bought things for a total amount of 12200. Now I want to find the count of top users who have a Sum(of the bought amount) less than or equal to 10000. output: 3 users i.e, (5000.0 + 5000.0) <= 10000 SaleTransaction.objects.all().order_by('-amount').annotate(Count("pk"), cumulative_sum=Sum('amount')).count() Please suggest !! -
Why am I getting Value Error here? (Django)
I am trying to make a CRUD application in Django. My emp view is returning none where it should return HttpResponse. Here's my code. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) and here's my error. The view employee.views.emp didn't return an HttpResponse object. It returned None instead. -
How to fetch Nested Json data in django template along with If else condition?
json { "customer_id": 113, "customer_name": "Kiya Stacy", "coach_name": "Dr. Shraddha", "coach_profile_image": "2022420768.jpg", "diet_plan_id": 154 }, { "diet_plan_list": [ { "variant_number": 1, "meal_time_list": [ { "meal_type_flag": 1, "meal_time": "Early Morning", "food_item_list": [ { "id": 13084, "name": "Detox Water - Pineapple And Orange", "cooking_instructions": "1. Chop the orange into slices. Add all the ingredients to a large jar or bottle. You can muddle them a little to extract more flavour.\n2. Cover with a lid and keep aside to infuse for a minimum of 2 hours. You can even place it in the refrigerator and let the flavours infuse overnight. \n3. Sip on it throughout the day.", "calories": 117.62325, "is_custom_food_item": false, "image_name_list": [ "IMG_13084_2021_04_10_15_28_34_956147.png" ], "ingredient_information": [ { "id": 2619, "name": "Orange - Raw (With Peel)", "food_category": 4, "volumetric_weight": null, "standard_weight": 100, "quantitative_weight": null, "volumetric_density": 1, "quantitative_density": 200, "video_name": null, "video_thumbnail_image_name": null, "is_custom_food_item": false, "image_name_list": [ "IMG_2619_2021_03_16_05_31_56_233738.png" ], "calories": 63, "calories_per_100_gm": 63, "fibers_per_100_gm": 4.5, "carbohydrate_percentage": 16, "protein_percentage": 1, "fat_percentage": 0, "food_recipe_id": 75060, "ingredient_unit": { "id": 1, "name": "gm", "category": 3, "value": 1, "is_active": true }, "ingredient_quantity": 150 }, { "id": 2732, "name": "Pineapple - Pieces (Without Skin)", "food_category": 4, "volumetric_weight": 172, "standard_weight": 100, "quantitative_weight": null, "volumetric_density": 0.86, "quantitative_density": 1, "video_name": null, "video_thumbnail_image_name": null, … -
Django Login with Email or Phone Number
I have been trying to find a solution of a problem in Django for a very long time. The problem is I am trying to develop a login system than can use either email or phone number to authenticate user. Any help would be appreciated. Thank you -
Colvis is not working using serverside processing in datatables
i implemented datatable with serverside enabled. Now the colvis button stopped working as far as i learned it should wait for the data to load and hence: i wrote following code and many other similar to it: $(document).ready(function() { var table = $('#user_processes_{{pk}}').DataTable({ dom: 'Bfrtip', buttons: [ 'copyHtml5', 'excelHtml5', 'pdf', 'colvis' ], "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); }, // rowReorder: { // selector: 'td:nth-child(2)' // }, pagingType: "full_numbers", responsive: true, orderCellsTop:true, fixedHeader: true }); table.buttons().container() .appendTo( $('.col-sm-6:eq(0)', table.table().container() ) ); }); Still the problem remains. Any help is appreciated. Many thanks. -
How do I set up the structure of my wsgi file to deploy Heroku?
I'm working on a Django website that I'd like to deploy with Heroku. When I try to deploy to Heroku, it keeps crashing. I've been having an issue with my Procfile. My Procfile: web: gunicorn theGame.wsgi I have a wsgi file in the same folder as my settings folder. My Django Project is named theGame. The main application that holds all the html files is called 'interface'. When I restart my dynos, I keep getting the same error: [TIMESTAMP] app[web.1]: ModuleNotFoundError: No module named 'theGame.wsgi' -
How to generate a password which complies with auth validators in Django?
I used User.objects.make_random_password() to generate passwords for new users, however I found out that this method was creating passwords which didn't comply with the validators (AUTH_PASSWORD_VALIDATORS) that are configured in Django. I also tried with from django.contrib.auth.hashers import make_password, but the hashed password does not match all the password validation criteria because is too long. I want to know if there is a function which creates passwords based on AUTH_PASSWORD_VALIDATORS?.