Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'QuerySet' object has no attribute 'requestedDate'
I just want to filter the CustomerPurchaseOrder(inputdate) to CustomerPurchaseOrderDetail(requestedDate). How do i do that? This is my current views.py record = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) date = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) status = CustomerPurchaseOrderDetail.objects.filter(profile__in=client.values_list('id')) \ .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=date.requestedDate) class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customerdeliveryaddress = models.ForeignKey(CustomerDeliveryAddress, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Delivery Address") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") requestedDate = models.DateField(auto_now_add=True) class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") products = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerPurchaseOrder") inputdate = models.DateField(auto_now_add=True) This is my full traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\decorators.py" in wrapper_func 42. return view_func(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in client 116. .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=records.requestedDate) Exception Type: AttributeError at /client/ Exception Value: 'QuerySet' object has no attribute 'requestedDate' -
Not lazy Queryset calls outside methods
I use Django in work and I'm still learning about some of its features - recently I ran into a problem with a Queryset call in one of my DetailView classes. While the code ran perfectly for me, it broke on the CI pipeline set to initialize a project from scratch. I got the answer that it's because of the non-lazy evaluation of said call - to be precise, it roughly looked like this: class MyListView(ListView): queryset = ( MyModel.objects.all() .exclude(some_type_field__in=[ContentType.objects.get_for_model(MyReferenceModel)]) .distinct() ) template_name = #... In addition, I was told not to write Queryset calls that are not lazily evaluated outside of methods - and that the reason is that the Python interpreter executes code module by module. I don't understand this part, however. How methods has anything to do with it? Why is it an issue if the code above, tries to actually hit the database? To specify my question further, I show what was the solution I got: class MyListView(ListView): model = MyModel def get_queryset(self): return ( super() .get_queryset() .exclude(some_type_field__in=[ContentType.objects.get_for_model(MyReferenceModel)]) .distinct() ) template_name = # ... What's the actual difference between the two? I need to understand this problem better, and Django wiki was no help. -
How can you customize the response message of the post in django?
I am trying to make a membership API using django rest frameworks.I made a code and checked that the function was working properly. In my current code, if the data of the email, password, and username are empty, the message is given as follows. { "email": [ "This field is required." ], "username": [ "This field is required." ], } But after talking about this with my team's client developers, they said it was better to give a unified message as below. { "message": "email field is required." } How can I customize the value like this? Here's my code. class customSignUpView (GenericAPIView) : serializer_class = customRegisterSerializer def post (self, request) : user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user = User.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('emailVerify') absurls = F'http://{current_site}{relativeLink}?token={token}' email_body = F'Hi {user.username} Use link below to verify your email \n{absurls}' data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email'} Util.send_email(data) return Response({'message': 'check your email.'}, status=201) -
Problem appending corresponding data on monthly basis in django
Please i need your help on this, i have made a queryset to get all months and corresponding total amounts for each month made, but the issue i face is that all amounts is only being received by the current month even when the order is created and assigned to a separate month. I am actually thinking of appending corresponding amounts made for each month but i feel there i am making some little error. This is my view queryset2 = PurchaseOrder.objects.values('created_on__month').annotate(sales_sum= Sum('po_amount')).order_by('created_on__month') data = { r['created_on__month']: r['sales_sum'] for r in queryset2 } zero = Decimal(0) data = { datetime.date(1900, m, 1).strftime('%b'): data.get(m, zero) for m in range(1, 13) } This was the queryset i got: {'Jan': Decimal('0'), 'Feb': Decimal('0'), 'Mar': Decimal('0'), 'Apr': Decimal('0'), 'May': Decimal('0'), 'Jun': Decimal('0'), 'Jul': Decimal('0'), 'Aug': Decimal('0'), 'Sep': Decimal('449670'), 'Oct': Decimal('0'), 'Nov': Decimal('0'), 'Dec': Decimal('0')} This is my model class PurchaseOrder(models.Model): created_on = models.DateTimeField(auto_now_add=True) po_amount = models.DecimalField(max_digits=10, decimal_places=2) Kindly help on this Thanks Oyero -
Django 3.1 admin interface styling issue
I just upgraded to Django 3.1 and with the new admin interface, seems like there are lot of styling changes. I have too many filters and now I am unable to see everything..Basically, it got cut after some point. I have read the docs and they are suggesting to manually change css files. Just Curious if there is any permanent fix for this? Note :- Everything was fine in my previous Django version 3.0.1. -
Invalid syntax error in view.py in django
I can't figure out what i've done wrong here. In my views.py. def register(request): if request.method == 'POST' form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) -
Index Already Exists Error in Django Migrations
I deleted the db.sqlite3 and all the migrations/* files in all apps except the initial.py file. After which I tried to run the command python3.8 manage.py makemigrations product After which I ran the command python3.8 manage.py migrate product I am getting this following error: sql SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations" param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c374dc0> sql SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations" param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c374dc0> Operations to perform: Apply all migrations: product Running migrations: Applying product.0001_initial...sql INSERT INTO "django_migrations" ("app", "name", "applied") VALUES (%s, %s, %s) param ['product', '0001_initial', '2020-09-23 06:05:03.633327'] self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c30ddc0> sql CREATE INDEX "product_product_category_id_0c725779" ON "product_product" ("category_id") param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c30db80> Traceback (most recent call last): File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: index product_product_category_id_0c725779 already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) … -
Can you stop Django automatically reverting a manual Migration?
I have a Model file which has a change which isn't being picked up by DJango makemigrations. I created a manual migration following this answer, but if we run makemigrations afterwards Django creates a new auto migration reverting our manual changes. Is there a way to manually make a migration and tell DJango to ignore relevant parts of the code when generating future migrations? -
DRF: how to render relative urls as hyperlinks in the browsable api?
I am exposing my api through an api gateway. So absolute urls is a problem. I want to change it to allow for relative urls, but also want the relative url's to be picked up by the browsable api so when a browser views results - it can click the link. Instead of having to copy the link and add it to the browser url bar. Is there a way to do this with Django Rest Framework? I know that the rest api for AWX does it somehow. -
Model object creation test fails in Django
I have done some testing before to create an object of a model, but this one keeps failing. This is the model I want to test: class Contact(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) subject = models.CharField(max_length=200) message = models.TextField() contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(default=0, blank=True, null=True) and this is the test code: class ContactTest(TestCase): def test_contact_create(self): url = reverse('contacts:contact') user = User.objects.create_user({ 'username': 'asif', 'email': 'asif@mail.com', 'password': 'asif123!!' }) response = self.client.post(url, { "name": "marrydoe", "email": "marrydoe@mail.com", "subject": "Test", "message": "This is a test message", "contact_date": timezone.now(), "user_id": user.id, }) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') I get this traceback error, I tried to trace the problem but couldn't find where the problem resides. Creating test database for alias 'default'... System check identified no issues (0 silenced). .....................D:\GitHub\Portfolio\lib\site-packages\django\db\models\fields\__init__.py:1367: RuntimeWarning: DateTimeField Contact.contact_date received a naive datetime (2020-09-23 11:38:22.746360) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" [2020-09-23 11:38:22,750] log: ERROR - Internal Server Error: /contact/ Traceback (most recent call last): File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "D:\GitHub\Portfolio\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "D:\GitHub\Portfolio\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'None' not found. … -
How to make appear date picker for date and time and radio button for gender select?
I want my form to have date picker appear and also the radio button for gender select. How can I make it appear on my form without writing whole HTML code for whole form. I am using the default form provided by django. I dont want to write whole code for just two fields. Is it possible? I want to learn as well. class Passenger(models.Model): book_id = models.OneToOneField(Booking, on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateTimeField() Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) # Gender = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.First_name This is my bookmessenger view. def bookpassenger(request): # form = AirlinesAddUpdateForm if request.method == 'POST': # obj = Booking.objects.get(id=pk) form = PassengerForm(request.POST or None) if form.is_valid(): form.save() print('we are good') messages.success(request, 'Successfully added') return redirect('booking') This is my default form extracted from django itself. <form action="{% url 'bookpassenger' %}" method="POST"> {% csrf_token %} {{form|crispy}} <input type="submit" class=" btn btn-success " name="Submit"> </form> -
Is it possible to modify default tabbing system for a django template system?
I'm Using Jet https://github.com/geex-arts/django-jet/ for my dashboard but I'm having one issue. On the admin page, when I perform a Save and add another action, the object gets saved and the page reloads. After the reload, the active tab becomes the last tab that I was editing. Is it possible to make it default to the first Tab after the reload and only for the Save and add another button? Every time the page reloads from the Save and Add another button, I want it to default to the Format tab. -
How to display data Today, Yesterday and last 7 Days in Django?
I want to display data of today, yesterday and last 7 days, please let me know how I can do it. I am trying this....but it's displaying me only the last 7 days data, but I want to display data in my HTML file according to today, yesterday and last 7 days datas= Mymodel.objects.filter(created_on_gte=datetime.now()-timedelta(days=7)).count() here is my HTML file, where I am displaying data... <p>{{datas}} today</p> <p>{{datas}} Yesterday</p> <p>{{datas}} Last 7 Days</p> -
How to redirect to other template and submit the form with value passed from the original template in django
I am creating a youtube clone project in Django and I am stuck at one part. I want to implement youtube like functinality where when clicked on #tags it takes that tag as a value to search and renders the searched videos containing tags. I have implemented the search functionality using Haystack. I am able to search videos from home page(like youtube's). What I want now is when I click on tags from video playing page, tag value should come to my homepage(or view) and the search form in home template should accept its value and search it(the tag should be searched exactly like when we search it from home page manually). views.py class HomeView(SearchView): template_name = 'core/home.html' form_class = SearchForm def get_context_data(self, **kwargs): context = {} context['videos'] = Video.objects.all() context.update(kwargs) return super().get_context_data(**context) class VideoView(DetailView, FormView): template_name = 'core/video.html' form_class = React def get_object(self, **kwargs): return Video.objects.get(id=self.kwargs['id']) def get_context_data(self, **kwargs): context = {} if self.object: context['object'] = self.object context['likes'] = self.object.userprofile_set.count() #likes count by ManyToManyField reverse reference context['comments']=self.object.comment_set.all() #comments by ForeignKey reverse reference if self.request.user.is_authenticated: if self.object.userprofile_set.filter(id=self.request.user.userprofile.id).exists(): context['likestatus'] = True else: context['likestatus'] = False context.update(kwargs) return super().get_context_data(**context) def get_success_url(self): return reverse('core:videoview',kwargs={'id':self.kwargs['id']}) def post(self, request, *args, **kwargs): form = self.get_form() if … -
getting list index out of range when function is being called Django
I am trying get total here, whenever i add the new record i got the error i don't know why i got list index out of range i m calling the function in admin.py this is my model file class Buyer(models.Model): buyer_name = models.CharField(max_length=256,unique=True) def __str__(self): return self.buyer_name def buyerdebittotal(self): queryset = Buyer.objects.filter(policybuyer__buyer_id = self.id).annotate(total=Sum('policybuyer__buyerdebit',)) return queryset[0].total class Policy(models.Model): buyer = models.ForeignKey(Buyer,on_delete=models.DO_NOTHING,related_name='policybuyer') buyerdebit = models.FloatField(default=0) def get_absolute_url(self): return reverse("insurance:updatepolicy", kwargs={"id": self.id}) -
Why can't I find the Dockerfile?
I'm making a Python (Django) and MySQL project. After creating some files, I get an error when I run the command. docker-compose up -d ERROR: Cannot locate specified Dockerfile: Dockerfile Why am I getting an error when I have a Dockerfile in the current directory? MYAPP -django --__init__.py --asgi.py --settings.py --urls.py --wsgi.py -docker-compose.yml -Dockerfile -manage.py -requirement.txt -wait-for-in.sh docker-compose.yml version: '3' services: db: image: mysql:5.7 command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci volumes: - .:/var/www/django restart: always environment: MYSQL_ROOT_PASSWORD: django MYSQL_DATABASE: django MYSQL_USER: django MYSQL_PASSWORD: django web: build: django command: sh -c "./wait-for-it.sh db:3306; python3 manage.py runserver 0.0.0.0:8000" volumes: - .:/var/www/django ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /var/www/django WORKDIR /var/www/django ADD requirements.txt /var/www/django/ RUN pip install -r requirements.txt ADD . /var/www/django/ -
Why after assigning data to a variable outside the ajax block, the variable remains empty [duplicate]
I'm trying to load data for chart drilldown with ajax, in success block i'm assign data to data_by_days(declared outside ajax block), but after ajax block this variable is empty chart.listen('pointClick', function (e) { let pointId let data_by_days=[] if (e.point.get('drillDown')!=null) { chart.getSeries(0).data(e.point.get('drillDown')); } else { pointId = e.point.get('x') $.ajax({ url: '/month_drill_down/', method: 'POST', data: {pointId: pointId}, success: function (data) { data_by_days = data; console.log(data_by_days) }, error: function (d) { console.log(d); } }); console.log(data_by_days) chart.getSeries(0).data(data_by_days); } }); chart.container('container3').draw(); } -
Pie chart of chart.js is not showing label while using ajax
I am working with Chart.Js to show a pie chart. I need to call ajax for fetching data from my database. ajax function: function monthlyAttendanceReport(){ $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-user-monthly-attendance-report" %}', data: { 'employee_id': '{{ employee.id }}', 'month': month, 'year': year }, dataType: 'json', success: function (data) { chart(); } }); } pie.js: function chart(){ // Get pie chart canvas var context = $("#monthly-attendance-status-pie-chart"); //pie chart data var monthlyAttendanceStatusdata = { labels: ["match1", "match2", "match3", "match4", "match5"], datasets: [{ label: "Attendance Status", data: [10, 50, 25, 70, 40], backgroundColor: [ "#DEB887", "#A9A9A9", "#DC143C", "#F4A460", "#2E8B57" ], borderColor: [ "#CDA776", "#989898", "#CB252B", "#E39371", "#1D7A46" ], borderWidth: 1 }] }; //create Chart class object var monthlyAttendanceStatusChart = new Chart(context, { type: "pie", data: monthlyAttendanceStatusdata, }); } $(document).ready(function() { $("#selected-month").html(initCurrentMonth()); $('#month-next-btn').attr('disabled', true); // chart(); monthlyAttendanceReport(); }); when I try this lines of code I find that pie chart is generating but without anylabel.. But when I call chart() function in document ready scope and do not call ajax function, pie is generating with all the labels. So, when I use ajax request, no label is showing. But when I do not … -
How to upload multiple images in django, group them per post and display them per post
class Iphones(models.Model): image = models.ImageField(upload_to='images/') class SelliPhone(forms.ModelForm): class Meta: model = Iphones fields = ['image'] widgets ={'image':forms.FileInput(attrs={'class': 'custom-file', 'multiple': True}) -
Setting a forms initial value to a value not in form choices
I'm trying to set the initial value of a form to something that was one of the choices, but is now no longer available. Here is my forms.py choices: list_DB_genius_status= ( ('Bound', 'Bound'), ('Cancelled', 'Cancelled'), ('Closed', 'Closed'), ('Declined', 'Declined'), ('Extended', 'Extended'),) and my class: DB_Genius_Status = forms.TypedChoiceField(label = 'DB Genius Status', choices=list_DB_genius_status) in views.py, I try to set the initial value to "Expired", as this is the default value, but on load it defaults to "Business Exception" def RPA_tool(request, Policy_Number): RPAPolicy = getRPADetails(Policy_Number) print(RPAPolicy) policyNumber = (RPAPolicy.loc[RPAPolicy.index[0], 'Policy_Number']) geniusTransactionType = (RPAPolicy.loc[RPAPolicy.index[0], 'Transaction_Desc']) RPAStatus = (RPAPolicy.loc[RPAPolicy.index[0], 'Status_Desc']) form = RPA_tool_form(initial={'Policy_Number':policyNumber, 'RPA_status': 'Expired'}) return render(request, 'admin_tool/RPA_tool.html', {'form':form}) RPA_tool.html: {% extends "home/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class = "content-section"> <form method ="POST"> {% csrf_token %} <Fieldset class="form-group"> <legend class="border-bottom mb-4"> Edit RPA Details </legend> {{form|crispy}} </Fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Submit </button> </div> </form> </div> {% endblock content %} Is there a way to set the default value to "Expired" or to another value that isn't defined in choices? -
i just want to slide, but i dont know how
since days i try to find a proper code to slide this images in the template but i couldnt make it happen, i need your help bro, lets make it burn. Models 1 : class MyFamily(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) update = models.DateField(auto_now=True) title = models.CharField(max_length=100) explanatipon = models.TextField(blank=True) photo1 = models.ImageField(upload_to='posts/photos/') photo2 = models.ImageField(upload_to='posts/photos/') photo3 = models.ImageField(upload_to='posts/photos/') photo4 = models.ImageField(upload_to='posts/photos/') photo5 = models.ImageField(upload_to='posts/photos/') active = models.BooleanField(default=True) @property def photos(self): photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5] return [photo for photo in photos if photo is not None] def __str__(self): return str(self.title)[:30] profile : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) views : def photo(request): myfamily = MyFamily.objects.filter(active=True) context = { 'myfamily':myfamily } return render(request, 'posts/create-form.html') template : <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for photo in myfamily.photos %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <img class="d-block w-100" src="{{ photo.url }}" alt="First slide"> </div> {% endfor %} </div> </div> -
In-memory caching using Cherrypy wsgi server
I use Django to serve my model/application. To improve the response time for coming requests, i use django lrucache_backend caching to cache the model in memory like this: In my model.py file: from django.core.cache import caches model = caches.get(model_cache_key) ## get model from cache if model is None: model = Estimator.load_model_bytes(self.trained_model_file) cache.set(model_cache_key, model, None) ## save model in the cache django SETTINGS.PY : CACHES = { 'default': { 'BACKEND': 'lrucache_backend.LRUObjectCache', 'OPTIONS': { 'MAX_ENTRIES': 1001, 'CULL_FREQUENCY': 1001 }, 'NAME': 'just-a-test' } } Since django runserver is not a production ready server, i want to use Cherrypy to serve my django application. I have 2 questions: Is Cherrypy a good choice to serve my django application that receives high load ? How do i implement in-memory caching using Cherrypy ? Note: I do not want to use any reverse proxy server infront of WSGI server. -
In query set can we use distinct with exclude and orderby in django
I am working in a django project. The query set is longestPendingTask = WorkAssignment.objects.filter(isActive=True,client_id = request.session["clientId"],expectedDate__lte=today).exclude(status="Completed").order_by("expectedDate") It is having exclude and order_by. I want to use distinct to show only unique records, but it does not work. Also the field in distinct is foreign key from another table. Please guide me how to show distinct records. -
Django rest framework's StringRelatedField is throwing KeyError
I have the following model classes. class Categories(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='category_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) class Meta: unique_together = ('business', 'name') class Menu(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='menu_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) description = models.CharField(max_length=128) category = models.ForeignKey(Categories, related_name='menus', on_delete=models.CASCADE) price = models.IntegerField() class Meta: unique_together = ('business', 'name', 'category') def __str__(self): return '%s %s %s' % (self.name, self.price, self.description) and I have imported these classes as following as they are located in a separate package Categories = apps.get_model('business', 'Categories') Menu = apps.get_model('business', 'Menu') and this is my serializer class class GetCategoriesSerializer(serializers.ModelSerializer): menus = serializers.StringRelatedField(many=True) class Meta: model = Categories fields = ('name', 'menus') and views is class GetCategories(generics.ListAPIView): """ Returns a list of businesses to the user. It'd read only and no authentication is needed """ permission_classes = [ReadOnly] queryset = Categories.objects.values() serializer_class = GetCategoriesSerializer and url has the following path('customer/<str:pk>/categories', GetCategories.as_view()), I am getting the following error KeyError: 'menus' I looked into the DRF example and this seems to be a simple thing to achieve. https://www.django-rest-framework.org/api-guide/relations/#api-reference But I am kind of stuck at this point. Am I doing anything wrong? Thanks in advance for any help. -
I need a good way to divide a list in Django list view
Hi i'm quite new in django I'm making a student man\ agement program. Currently, the paging and search function have been coded as query and It works in combination , but since we receive new students every year, school_year is important. I want to see the student list by school_year that I want by pressing the year on the top right. I've been thinking about implementing it as a query, but it seems too complicated(I think it's too complicated to combine with the queries that have already been created.), and it's too unnecessary to make a listview for each grade. pls give me some good idea or solution thanks ! listveiw template IMG my views.py here ''' class StudentList(ListView): model = Student template_name = 'student/orders.html' context_object_name = 'students' paginate_by = 12 def get_queryset(self): keyword = self.request.GET.get('keyword') if keyword: object_list = self.model.objects.filter( Q(name__icontains=keyword) | Q(email__icontains=keyword) | Q(student_mobile__icontains=keyword) ) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): context = super(StudentList, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 # Display only 5 page numbers max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if …