Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cleaned_data is returning wrong/different value
I have been struggling with the Forms in Django. Able to get the value from the cleaned_data but it returns a totally different number. For example, I have 4 values to choose from (2,3,4,5). If I select 2, it will give cleaned_data.get(name_of_form_field) returns 5. And so on. class PopulationForm(forms.Form): districts = forms.ModelChoiceField(queryset=Population.objects.order_by('districtid').values_list('districtid',flat=True).distinct()) There are 4 options for a user to choose from: 2,3,4,5. If the user selects 2, it returns 5 and so on. I am not sure what's happening. Here is my views.py: if request.method == 'POST': form = PopulationForm(request.POST) if form.is_valid(): print(form.cleaned_data.get('districts')) return HttpResponse(form.cleaned_data.get('districts')) Here is my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Forms Tutorial</title> </head> <body> <h2>Django Forms Tutorial</h2> <form action="/display/" method="post"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value="Submit" /> </form> </body> </html> -
Cannot resolve keyword 'pub_date_year'
I followed the documentation django enter link description here this my code model.py from django.db import models # Create your models here. class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): return self.full_name class Article (models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete = models.CASCADE) def __str__(self): return self.headline code urls.py from django.urls import path from . import views urlpatterns = [ path('article/<int:year>/', views.year_archive), ] code views.py from django.shortcuts import HttpResponse, render from .models import Article def year_archive (request,year): a_list = Article.objects.filter(pub_date_year = year) context = { 'year' : year, 'article_list' : a_list } return render(request, 'news/year_archive.html', context) and than year_archive.html {%block title%} Article For {{ year }} {%endblock%} {% block content %} <h1>Article For {{year}} </h1> {% for ar in article_list %} <p>{{ar.headline}} </p> <p>By{{ar.reporter.full_name}} </p> <p>Publsihed {{ar.pub_date}} </p> {% endfor %} {% endblock %} I want to ask when i input urls http: // localhost: 8000 / article / 2020 / error appears Cannot resolve the keyword 'pub_date_year' what should I fix -
django DetailView doesn't catch data from ManyToMany field
I have 3 models: first main "Stones" connect by ForeignKey with "Typs" and Many-to-Many with "Mentions". When I try to write a template for detail view for each "stone" with DetailView class, it shows data only from "Stones" and "Typs", not from 'Mentions" my models.py (necessary part) class StonesManager(models.Manager): def all_with_prefetch_mentions(self): qs = self.get_queryset() return qs.prefetch_related('mentions') class Stones(models.Model): title = models.CharField(max_length=30, verbose_name='Назва') place = models.TextField(verbose_name='Месцазнаходжанне') legend = models.TextField(null=True, blank=True, verbose_name='Легенда') typ = models.ForeignKey('Typ', null=True, on_delete=models.PROTECT, verbose_name='Тып') objects = StonesManager() class Typ(models.Model): name = models.CharField(max_length=20, db_index=True, verbose_name='Назва тыпу') def __str__(self): return self.name class StonesImage(models.Model): image = models.ImageField(upload_to=stones_directory_path_with_uuid) uploaded = models.DateTimeField(auto_now_add=True) stones = models.ForeignKey('Stones', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Mentions(models.Model): work = models.TextField(verbose_name='Праца') year = models.PositiveIntegerField(blank=True, null=True) sacral_objects = models.ManyToManyField(Stones, related_name='mentions', verbose_name='Сакральны аб\'ект') my views.py (necessary part) class StonesDetail(generic.DetailView): queryset = Stones.objects.all_with_prefetch_mentions() template_name = 'volumbf/stone_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_form'] = self.stones_image_form() return context def stones_image_form(self): if self.request.user.is_authenticated: return StonesImageForm() return None my template (necessary part) 1. All are shown in the right way <h2> {{ stones.title}} </h2> <p>{{ stones.legend }} </p> <p>{{ stones.place }}</p> <p>Typ: <a href="/volumbf/{{ stones.typ.pk }}/">{{ stones.typ.name }}</a></p> Isn't shown at all Mentions: {% for work in stones.mentions.work %} <p><a href="{% url 'work_detail' work.pk %}"> … -
Django : Best way to Query a M2M Field , and count occurences
class Edge(BaseInfo): source = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_source") target = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_target") def __str__(self): return '%s' % (self.label) class Meta: unique_together = ('source','target','label','notes') class Node(BaseInfo): item_type_list = [('profile','Profile'), ('page','Page'), ('group','Group'), ('post','Post'), ('phone','Phone'), ('website','Website'), ('email','Email'), ('varia','Varia') ] item_type = models.CharField(max_length=200,choices=item_type_list,blank = True,null=True) firstname = models.CharField(max_length=200,blank = True, null=True) lastname = models.CharField(max_length=200,blank = True,null=True) identified = models.BooleanField(blank=True,null=True,default=False) username = models.CharField(max_length=200, blank=True, null=True) uid = models.CharField(max_length=200,blank=True,null=True) url = models.CharField(max_length=2000,blank=True,null=True) edges = models.ManyToManyField('self', through='Edge',blank = True) I have a Model Node (in this case a soc media profile - item_type) that has relations with other nodes (in this case a post). A profile can be the author of a post. An other profile can like or comment that post. Question : what is the most efficient way to get all the distinct profiles that liked or commented on anothes profile's post + the count of these likes /comments. print(Edge.objects.filter(Q(label="Liked")|Q(label="Commented"),q).values("source").annotate(c=Count('source'))) Gets me somewhere but i have the values then (id) and i want to pass the objects to my template rather then .get() all the profiles again... Result : Thanks in advance -
django rest framework accessing and editing nested model
i'm new to django rest framework, spent last ~2hours looking for the answer and still didn't find one. Let's say i've got 2 models class Person(models.Model): name = models.CharField(max_length=50) class Language(models.Model): person = models.ForeignKey( Person, related_name='prs', on_delete=models.CASCADE) name = models.CharField(max_length=50) i want to be able to access all persons languages like that -> person/{person_id}/language and to access and edit specific language like that -> person/{person_id}/language/{language_id} thanks in advance -
I can not start Django local server
I am learning Django during this lock-down. My app has been running properly , made some changes like adding models ,etc and hit runserver and got errors below: PS C:\Users\RK\RentalMgt\TenancyMgt> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Traceback (most … -
Django session issue while redirecting to other
I am developing the e-commerce website with Django, So after successful payment through Paytm payment gateway(Integration testing) I have a session issue in the local server, after redirecting from Paytm test integration portal to a payment success page (local server ), user session logout automatically while I am on the payment success page. Payment.html file {% extends 'shop/base.html' %} {% load static %} {% block title%} Paytm merchant payment page {% endblock %} {% block content %} {% csrf_token %} <h1>Redirecting you to the merchant....</h1> <h1>Please do not refresh your page....</h1> <form action="https://securegw-stage.paytm.in/order/process" method="post" name="paytm"> {{ form.as_p }} {% for key, value in param_dict.items %} <input type="hidden" name="{{key}}" value="{{value}}"> {% endfor %} </form> <script> document.paytm.submit() </script> {% endblock %} paymentstatus.html file {% extends 'shop/base.html' %} {% load static %} {% block title%}Shoppy hub{% endblock %} {% block content %} {% csrf_token %} <div class="container"> <div class="col my-4"> <h1>Payment status regarding your order Id : {{response.ORDERID}}</h1> {% if response.RESPCODE == '01' %} <h3>Amount paid:{{response.TXNAMOUNT}} </h3> <h3><img style="height:50px;"src="/static/img/success.png" >Your order has been received successfully</h3 > <h3>Thank you for your purchase! </h3> {% else %} <h2> <img style="height:50px;"src="/static/img/fail.jpg" >Your order has been failed</h2 > {% endif%} </div> </div> {% endblock %} {% block … -
Django 3.0.3 IntegrityError FOREIGN KEY constraint failed when making changes to db
I have two models in my database, an 'Account' model (which is a custom user model) and a 'Return' model. My database worked fine up to the point of adding the 'Return' model, which has a ForeignKey relationship with the 'User' model, which I suspect is causing the problem. (Each return belongs to an existing user. In the admin panel, the option box is populated with existing users so I thought this was working correctly?) Appreciate any help with this! Error: IntegrityError at /admin/returns/return/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/returns/return/add/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Here is my Return app's models.py: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Return(models.Model): user = models.ForeignKey(User, related_name="returns", on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=True) last_edited = models.DateTimeField(null=True) TAX_YEAR_CHOICES = [ ('2019', '2019'), ('2020', '2020'), ('2021', '2021'), ] tax_year_ending = models.CharField( choices=TAX_YEAR_CHOICES, max_length=4, blank=False, null=False, ) RETURN_STATUS_CHOICES = [ ('1', 'In progress'), ('2', 'Completed, awaiting review'), ('3', 'Completed, under review'), ('4', 'Completed, awaiting client action'), ('5', 'Submitted to HMRC'), ] return_status = models.CharField( choices=RETURN_STATUS_CHOICES, max_length=1, default=1, blank=False, null=False, ) Here is the post request information from the … -
Django @register.simple_tag of custom tags and filter is not working in template
app/templatetags/custom.py from django import template register = template.Library() @register.simple_tag def add(value, args): return value + args template/index.html {% load custom %} {% with number=0 n=0 %} {% for n in range(50) %} {% if n|divisibleby:6 %} {{ number|add:"1" }} {{ number }} {% endif %} {% endfor %} {% endwith %} I read the official Django Template Tag I want an increment in number like number ++ or number +=1 but it's not working and the server is also working. Somehow I found that {% load custom %} is not working because add function defined is not working. How to solve this error please help !! -
Django: changing representation of a field in serializer
I have a field what displays an average score and depends on another model's field. I use SerializerMethodField in order to get needed value. It looks like this: class TitleSerializer(serializers.ModelSerializer): rating = serializers.SerializerMethodField() class Meta: fields = '__all__' model = Titles def get_rating(self, obj): rating = obj.reviews.all().aggregate(Avg('score')) return rating It works but doesn't return it in a way I need. Now I get data what looks like: "rating" : { "score__avg" : some_value } How can I change it to: "rating" : some_value Thanks in advance. -
How do I serve static files using uvicorn?
I followed a tutorial regarding websockets for django and it works, however, if I try to serve a javascript file, I get a 404. asgi.py looks like: import os from django.core.asgi import get_asgi_application from chat.chat import websocket_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auralias.settings') django_application = get_asgi_application() async def application(scope, receive, send): if scope['type'] == 'http': # Let Django handle HTTP requests await django_application(scope, receive, send) elif scope['type'] == 'websocket': # We'll handle Websocket connections here await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type {scope['type']}") The settings file has STATIC_URL = '/static/' STATIC_ROOT = 'auralias/static' And there are files in the auralias/static directory. The index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Group Chat</title> </head> <body> <h1>Group Chat</h1> <script src="{% static "chat/js/chat.js" %}"></script> </body> </html> But I'm getting INFO: 127.0.0.1:42822 - "GET /static/chat/js/chat.js HTTP/1.1" 404 Not Found In the output of uvicorn. If I run python manage.py 0.0.0.0:8000 then the file is found. How am I meant to serve static files via uvicorn? -
Pass Primary Key To Bootstrap Modal in Django
Hi I am trying to pass the primary key of an object to a bootstrap modal form. What I am finding is that one particular line of code is preventing the modal from even launching but I do not know why. I will highlight that below. So what am I missing? If I change the url in convert.html the modal launches, but I need to use the url I show below. base.html .... <div id="modal-div"></div> proforma_list.html {%for item in proformas %} <tr class="table-item"> ... <td> <a id="convert-modal" class="open-modal" data-url="{% url 'ConvertProformaView' item.pk %}">Convert</a> </td> <tr> {% endfor %} <script> ////////////////// CONVERT PROFORMA FORM /////////////////////// var modalDiv = $("#modal-div"); console.log(modalDiv) $("#convert-modal").click(function() { $.ajax({ url: $(this).attr("data-url"), success: function(data) { modalDiv.html(data); $("#myEdit").modal(); } }); }); </script> convert.html {% load crispy_forms_tags %} <div class="modal fade" id="myEdit" role="dialog"> <div class="modal-dialog"> <form class="well contact-form" method="POST" action="{% url 'ConvertShipmetView' %}"> <!---THIS URL CREATES THE PROBLEM, BUT I DONT KNOW WHY! IF I PUT A DIFFERENT URL HERE IT WORKS FINE---> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Shipment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{shipmentForm|crispy}} </div> <div class="modal-footer"> <button type="submit" class="btn btn-default">Submit</button> <button value="" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> … -
make Django `JSONField` stoke dictionary keys as integer
Is it any way to make Django JSONField store dictionary keys as integers? for example i have following dictionary in JSON {4: timezone.now().timestamp()} Key is 4 and it is integer. After this dictionary is saved in DB , key 4 turns to "4" : {"4": timezone.now().timestamp()} Is it any chance to prevent this behaviour somehow? Thank you. -
TypeError in as_view() in Django Restful Application
I have a basic Django app that I am copying in part from the Django Rest Framework docs. The issue I am having is that having implemented generic class based views I am getting a strange error. TypeError: as_view() takes 1 positional argument but 2 were given The stack trace points to my api/urls.py file and this line where I define url patterns: path('', include(router.urls)), The project is based out of api with a second app users. The only place as_view() is implemented is in users/urls.py as so: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from users import views urlpatterns = [ path('users/', views.UserList.as_view()), path('users/<int:pk>', views.UserDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) What arguments should be there or what have I configured wrong that is causing this issue? views.py from users.models import User from users.serializers import UserSerializer from rest_framework import generics class UserList(generics.ListCreateAPIView): """ List all users or create a new user """ queryset = User.objects.all() serializer_class = UserSerializer @classmethod def get_extra_actions(cls): return [] class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer api/urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from users import views router = routers.DefaultRouter() router.register(r'users', views.UserList) router.register(r'users', views.UserDetail) urlpatterns = [ path('', … -
which docker image should i use as base for a production django project?
with Ubuntu 20.04 LTS recently published, which docker image should I use as a base image for my dockerfile? the image is intended to be used in production but I also want to use it for development. in the tutorials I watched they use python:3.*-alpine but they say it is not for production. -
Django creates an extra object on submit
I am trying to create an Answer object once the page is rendered, when the user provide his input, the Answer object should be updated with the new input and saved. I am able to do that but for some reason an extra object is created when the user clicks the submit button and that object is always None. I use AJAX to send data from the template. views.py def attention_view(request): participant = get_object_or_404(Participant, user=request.user) if request.method == 'POST': question_id = request.POST.get('assigned_question') question = get_object_or_404(Question, pk=question_id) answer = Answer.objects.get(participant=participant, question=question) if answer.answer is not None: #preventing participants from changing their answer HttpResponse('') else: answer.answer = selected_choice answer.save() attention_question = Question.objects.get(id=13) answer = Answer.objects.create(participant=participant, question=attention_question) seconds_left = int(answer.seconds_left) context = {'attention_question': attention_question, 'answer': answer} return render(request, 'study/AttentionCheck.html', context) what could be the cause of creating an extra object ? -
Which AWS service to use when i have different backend and frontend?
I have my backend written in django. I researched and understand that AWS EC2 or AWS lightsail are cost effective solutions for me. What I am confused is about frontend. Should I use the same instance or create a container and use Amazon Container services ? The concerns I have is flexible load of containers during multiple users coming to website, CORS/Same origin issues when deployed in same instance, security issues when deployed in same instance, cost effectiveness Please help how do you decide in this situation -
Resizing django text forms and allowing users to make linebreaks with enter
I'm currently developing a web app with django and I have some forms where the users can enter a lot of text (up to 5.000 chars). I'm doing this using a CharField in forms.py: from django import forms class text_form(forms.Form): ... longer_text = forms.CharField( max_length=5000, widget=forms.Textarea( attrs={ 'rows':10, 'cols':2, 'data-length':5000, }), help_text='Some help text', label = 'Label Text', required=True ) The problems I'm facing right now (and I couldn't solve them even though I read a lot of related SO question) are: 1) I want the users to see a larger field (multiple rows) where they can insert text. Right now it's about maybe two rows and doesn't resize regardless the values I insert as rows value in attrs. 2) The users should be able to use the Enter key on their keyboard within those textareas to make a linebreak Any ideas how to achieve this? Thanks! -
updating a webpage every minute
I have a python function that crawls a website and returns a dictionary every minute. I want to show this dictionary in a table on a website and in case of any change in the crawled data to update the website and make a chrome notification. I don't know how it can be possible. -
DRF field validation on subset of Model's field
Allow me to first sketch the relevant parts of my Django/DRF project using some relevant snippets (Note that the following code snippets do not result in working code, but are there to show the overall structure of my problem): models.py class Sample(models.model): property_one = models.CharField(max_length=10, validators=property_one_validators) property_two = models.CharField(max_length=10, validators=property_two_validators) property_three = models.CharField(max_length=10, validators=property_three_validators) property_four = models.CharField(max_length=10, validators=property_four_validators) serializers.py class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' views.py class SampleViewSet(viewsets.ModelViewSet): serializer = SampleSerializer @action(detail=True, methods=["get"]) def method_one(self, request, pk): # Require property_one and property_three in request.data @action(detail=True, methods=["get"]) def method_two(self, request, pk): # Require property_one and property_two in request.data @action(detail=True, methods=["get"]) def method_three(self, request, pk): # Require property_two and property_four in request.data As you can see various subsets of the Sample model's parameters are used within the available API requests. What I would like to do is validate the required parameters within each API request using their respective validators (e.g. validate property_one with property_one_validators defined in models.py). From what I understand from the Serializer documentation, you are able to use validate to validate a complete filled in Model class (e.g. with property_one to property_four), but I would want use the same Serializer or at least its functionality to … -
How to include user_id (foreignKey) when posting an new record?
I'm new to python Django rest-framework, I'm facing this problem when creating a new address: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (21, full name, 123456789, any, any, any, any, any, any, f, null). This is The address model: from django.db import models from django.contrib.auth.models import User class UserAddress (models.Model): user = models.ForeignKey( User, related_name='addresses', on_delete=models.CASCADE) full_name = models.TextField(default='') phone = models.CharField(max_length=30, default='') city = models.TextField() province = models.TextField() street = models.TextField() description = models.TextField() postcode = models.CharField(max_length=20) country = models.CharField(max_length=100) is_default = models.BooleanField(default=True) class Meta: db_table = 'user_addresses' And this is the serializer: from rest_framework import serializers from user_action.models.address import UserAddress class UserAddressSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = UserAddress fields = ['id', 'full_name', 'phone', 'city', 'province', 'street', 'description', 'postcode', 'country', 'is_default'] And the POST method: @api_view(['POST']) @permission_classes((IsAuthenticated,)) def createUserAddress(request): user = request.user if request.method == 'POST': serializer = UserAddressSerializer(data=request.data) if serializer.is_valid(): newAddress = serializer.save() else: return Response(serializer.errors) return Response(serializer.data) Thanks in advance. -
Querying Parent from the foreign key django
I have the following models : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' # unique identifier, changed to email (default was username) REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() # custom manager for interacting with database def __str__(self): return self.email class Refer(models.Model) : referred_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default='admin', related_name='reffered_by') referrals = models.ManyToManyField(CustomUser, related_name='refferals', blank=True) unique_ref_id = models.CharField(max_length=8, blank=True, default=generate()) def __str__(self) : return f'Referred By: {self.referred_by}' I want to implement referral system using this, I have unique_for_id field (example 'exbvagtl'), how can i create new referral under that user? Something like : Refer.objects.create(referred_by= CustomUser.objects.get(Refer__unique_for_id='exbvagtl')) Better model designs, resources and improvements are heavily welcomed! -
Django query annotation to serialize data to the network
Here I have data as listed below. category order_no status cat1 11 success cat1 12 success cat1 12 success cat2 11 success cat2 11 success cat1 15 success cat3 50 failed And I want to aggregate data like as tabled below. O/P- Order_no category order type total order successful failed 11 cat1 2(composite) 1 1 0 11 cat2 2(composite) 2 2 0 12 cat1 1(single) 2 2 0 15 cat1 1(single) 1 1 0 50 cat3 1 (single) 1 0 1 if any order no is associated with two different categories(like cat1,cat2) then its order_type will be 2(composite) otherwise it will be 1(single) Now I am trying to write Django query in viewset to serialize the data to the jquery datatables. However, my query is getting some different results or giving error. queryset = Model.objects.annotate(order_no=F('order_no'),category=F('category'),\ order_type=Count('category','order_no',distinct=True),total_orders=Count('category'),\ total_success_order=Count('service_status', filter=Q(service_status='success')),\ total_failed_order=Count('service_status', filter=Q(service_status='failed'))) What approach should I follow ... and I can not use raw SQL queries due to project limitations. -
how to use temporary database for every user in django
so i am learning Django and making a todo application but i am stuck with a problem. I am storing every task on sqlite3 database(default by django) with models but when anyone store any task it is also visible to other person also how can i fix that? models.py:- from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title -
how do i disable browser back button after login?
def login(request): if request.session.has_key('is_logged'): return redirect('/') if request.method == 'POST': email = request.POST['email'] psw = request.POST['psw'] user = auth.authenticate(username=email, password=psw) if user is not None: auth.login(request, user) request.session['is_logged'] = True return redirect('/') else: messages.info(request, 'invalid user name or password') return redirect('login') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('/') how do i disable browser back button after login? is it good idea to disable backbutton from preventing logged users ? after login it redirects to the home page and from home page if i click browser back button it goes the previous page login.