Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parallel with Django using gevent
I'm trying to run some tasks in parallel in a Django view. Specifically, running queries from different databases at the same time. I've implemented the code, and the queries still run in series. To test, I've created simple parallel code: from gevent.pool import Pool def test(request): def run(i): print("Running " + str(i)) for j in range(1, 100000000): x = 2 / 2.2 pool = Pool(50) pool.map(run, range(1, 10)) The code also runs in series to my surprise Any idea what I'm doing wrong ? Is there some Django internal processes that blocks multi-threading ? How would I go about implementing parallel processes if gevent is not the answer ? -
how to know when an activity date has passed - django
so i'm still on my todo list and i want to know when an activity has passed so as to flag it as expired. my views.py def progress(request): activities = ToDo.objects.all() today = timezone.localtime(timezone.now()) context = { 'activities' : activities, 'today' : today, } return render(request, 'percent.html', context) in my templates i have it as: {% for activity in activities %} {% if activity.end.date < today.date %} {{activity}} <br> {% endif %} {% endfor %} i'm going to add my models.py for referencing class ToDo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) todo = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True) created = models.DateField(auto_now=True) end = models.DateField() start = models.DateField() completed = models.BooleanField(default=False) def __str__(self): return f'{self.owner} - {self.todo}' or would it be easier to add an expired boolean field to my models? i'm so confused -
How to import a object of another model (A) inside model (B) in Django?
I want to create a new object in model B when specific condition are met in Model A, I am new to Django so that I am unable to figure out how exactly I can achieve this. For example I have two models( Product and Product Variant), when specific condition on Product Variant is met then I want to calculate new object value in Product Model. My product model is like this: PRODUCT_TYPE = ( ('s', 'simple'), ('v', 'varaible') ) class Products(models.Model): name = models.CharField(max_length=250,null=True, blank=True,) slug = models.SlugField(max_length=200, unique=True,null=True) short_description = HTMLField() description = HTMLField() category = models.ForeignKey(Categories, related_name="products",on_delete=models.SET_NULL,null=True,blank=True,) brand = models.ForeignKey(Brands,on_delete=models.CASCADE, default=None, null=True, blank=True,) warranty_support = HTMLField() product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50) And my Product Attribute Model is like this: class ProductVariant(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None) managed_stock = models.IntegerField(choices=STOCK_MANAGED, default=0) stock = models.IntegerField(default=None) stock_threshold = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) sku = models.CharField(max_length= 250, default=None) sale_price = models.DecimalField(max_digits=10, decimal_places=2) sale_start_date=models.DateField(auto_now_add=False, auto_now=False, default=None) sale_end_date=models.DateField(auto_now_add=False, auto_now=False,default=None) I am trying to create regular_price and sale_price on Product model if product_type is variable and if sale_end_date is greater than today. I want to set the price from the variant which has lowest price. I tried doing … -
Django Rest Framework returning duplicate data when returning a nested json response
I have a pricing table that contains the following fields: id, date, price_non_foil, price_foil, card_id. This table holds pricing data for each card for each day. For Example: "23a6c413-7818-47a8-9bd9-6de7c328f103" "2021-12-08" 0.24 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "c51a72ab-f29f-4465-a210-ff38b15e83a1" "2021-12-05" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "17289b71-3b73-4e16-a479-25a7069a142e" "2021-12-09" 0.38 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "fa88f619-ec32-4550-9a57-c77b6e1a8e11" "2021-12-07" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "f996d6cb-7d98-415c-bd70-2fca8f4e03a5" "2021-12-06" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "2f8c00f3-4d47-478d-a653-7d7a476e9bae" "2021-12-09" 0.43 3.33 "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" "15b20912-4103-4e08-8f91-fed820b761af" "2021-12-05" 0.66 5.08 "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" Currently there is pricing data for 5 dates for each card. I am trying to create an endpoint to return the latest 2 prices for each card using Django rest framework. I have managed to get the response to be nest under the card id, but my issue is that it returns multiple card ids, I assume based on the number of pricing data records for each card. views.py class individual_set_pricing(ListAPIView): serializer_class = SerializerSetsIndividualPricing def get_queryset(self): code = self.kwargs.get('code', None) qs = magic_sets_cards_pricing.objects.filter(card_id__set_id__code=code.upper()).values('card_id') return qs serializers.py class SerializerSetsIndividualPricing(serializers.ModelSerializer): card = serializers.SerializerMethodField('get_card') class Meta: model = magic_sets_cards_pricing fields = ['card_id', 'card'] def get_card(self, obj): date = magic_sets_cards_pricing.objects.filter(card_id=obj['card_id']).values('date', 'price_non_foil', 'price_foil').order_by('-date')[:2] return date Response [ { "card_id": "3a261180-c1b3-4641-9524-956be55bee7a", "card": [ { "date": "2021-12-09", "price_non_foil": 1.15, "price_foil": 1.54 }, { "date": "2021-12-08", "price_non_foil": 0.43, "price_foil": 1.62 } ] }, { "card_id": … -
Django ORM my ID growth non linear when save() data into model
In my django project i have a very strange behaviour from a model related to the Primary id field values in db. I have this model: class Results(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) def __str__(self): return self.device class Meta: indexes = [ models.Index(fields=['device', 'unit', 'proj_code', 'read_date']), ] well, in a .py file i save data into this table like this: try: p = Results(device=Device.objects.get(mac_id=macid), proj_code=projid, res_key=datalist[x]['key'], read_date = topic_date, unit=unit_ck) p.save() except IntegrityError as e: if 'UNIQUE constraint' not in e.args[0]: pass except ObjectDoesNotExist: pass so, data where saved in db but if i inspect the "id" field i see strange behaviours like these: |id|Others... |1 |data |2 |data |3 |data |11|data |12|data !99|data I don't know why but my id does not growth linear as i expected. Have someone experienced the same behaviour? How can i force save data with inear id growth? So many thanks in advance Manuel -
How do you change a many-to-many field for a form in django?
I don't know why the below code is not working in the def form_valid of my Modelview: lesson = Lesson.objects.all().first() for i in lesson.weekday.all(): form.instance.weekday.add(i) form.instance.save() Here, weekday is a many to many field. However, the form just saves what the user submitted for weekday, not the changed version above using lesson.weekday. I hope you guys could help me out, and please leave any questions you have. -
javascript addEventListener and click function not working for me on Anchor tag <a>
i hava also tried jquery but not worked for me i dont know why. this is my javascript code ''' var cartLinks = document.getElementsByClassName('update-cart') console.log(cartLinks) for (var i = 0; i < cartLinks.length; i++) { console.log('enterd in loop') cartLinks[i].addEventListener("click", function () { console.log('print...') var productId = this.dataset.product console.log(productId) }) } ''' this is the tag where i want to use. ''' <a href="#" data-product={{product.id}} data-action="add" data-toggle="tooltip" class ="update-cart" title="Add To Cart"><i class="ion-bag"></i></a> ''' this is how i used script in my code. ''' <body> some code some scripts <script src="{% static 'js/cart.js' %}"></script> </body> ''' -
Django : q error in django filter while i am passing parameters
queryset = self.filters[name].filter(queryset, value) KeyError: 'q' class PostFilter(filters.FilterSet): q = filters.CharFilter(method='my_custom_filter', label="Search") class Meta: model = Post fields = {'title': ['icontains'], "body": ['icontains'], } # fields ={'title':['exact', 'icontains'], # 'content':['icontains']} def my_custom_filter(self, queryset, name, value): return Post.objects.filter( Q(title__icontains=value) | Q(body__conntains=value) ) -
Django membership site with site-wide product discount
I want to create a membership site with Django where subscribed members will automatically have a site-wide discount on all products. The subscription plans will come from Stripe, but I'm not sure how to implement this site-wide discount in Django. Can anyone please help? -
Returning labels within validation errors in Django rest framework
When there are some validation errors on a request, DRF returns a dict object containing all the errors, something like this: { "first_name": [ "This field may not be blank." ], "last_name": [ "This field may not be blank." ], "email": [ "This field may not be blank." ] } Is there anyway to change this behavior and make it to automatically return field names in each error? something like this: { "first_name": [ "First name field may not be blank." # <<< The label of field: first_name ], "last_name": [ "Last name field may not be blank." ], "email": [ "Email field may not be blank." ] } or even a list: [ "First name field may not be blank.", # <<< The label of field: first_name "Last name field may not be blank.", "Email field may not be blank.", ] Note that I have more than of 80 end-points and serializers; I can't re-define all fields that are being automatically generated by ModelSerializers to add error_messages parameter. first_name = serializers.CharField( write_only=True, min_length=5, error_messages={ "blank": "First name field cannot be empty.", "min_length": "First name field is too short.", }, ) -
Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins
Help Reason given for failure: Origin checking failed - https://praktikum6.jhoncena.repl.co does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. -
Error 404 while creating page to upload csv file to django model
I am trying to create a page so I can upload csv files to django model- MODELS.PY from django.db import models class March(models.Model): name = models.CharField(max_length = 60, choices=name_choice) march = models.CharField(max_length = 60, blank = True) may = models.CharField(max_length = 60, blank = True) def __str__(self): return self.name VIEWS.PY import csv, io from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.shortcuts import render from django.http import HttpResponse from .forms import CustomerForm, CustomerForm222, CustomerForm45 from . import models @permission_required('admin.can_add_log_entry') def contact_upload(request): template = "contact_upload.html" prompt = { 'order': 'Order of CSV should be name, march, may' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): message.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter = ',' , quotechar = "|"): _, created = Contact.objects.update_or_create( name=column[0], march = column[1], may = column[2] ) context = {} return render(request, template, context) URLS.PY from django.urls import path from .views import contact_upload from . import views urlpatterns = [ path('', views.index, name="index"), path('book/<int:book_id>', views.book_by_id, name='book_by_id'), path('upload-csv/', views.contact_upload, name = "contact_upload"), ] HTML TEMPLATE: <form method="post" enctype = "multipart/form-data"> {% csrf_token %} <label>Upload a File </label> <input type … -
TypeError: argument cannot be of '__proxy__' type, must be of text type
from django.utils.safestring import mark_safe import bleach @register.filter() def safer(text): return mark_safe(bleach.clean(text, tags=_ALLOWED_TAGS, attributes=_ALLOWED_ATTRIBUTES)) -
How do I post jobs on social media platform like LinkedIn, monster.com, indeed etc. etc. using django rest api's
I have a Django model which stores jobs and its various fields. Now I want to post that jobs in social media's. Can anybody advise me or guide me to how to implement it using rest API's. Thank you! -
How do you modify manytomanyfield in form in django?
I was wondering how you can change the value of a many-to-many field in a django form. Preferably, I would like to change the value within the def form_valid of my Modelview. Here is a part of the form_valid in my view that I am having trouble with: lesson = Lesson.objects.all().first() for i in lesson.weekday.all(): form.instance.weekday.add(i) form.instance.save() Here, weekday is a many-to-many field. However, the form saves the "submitted" values of the weekday by the user, and not the changed one as shown in the above code. Interestingly, the below code works, although it is not a many-to-many field: form.instance.name = lesson.name form.instance.save() Thank you, and please leave any questions you have. -
Django Not able to add default value to VersatileImageField
class Product(models.Model): name=models.CharField(max_length=128) photo = VersatileImageField(blank=True,null=True,upload_to="Product/",default='default.jpg',ppoi_field='photo_ppoi') photo_ppoi=PPOIField() I am not able to bring default value and ppoi_field together. showing following error . Error: str object has no attribute ppoi Exception Location : versatileimagefield\widgets.py Seems like exception throwing while django trying to set ppoi value to string type ('default.jpg') which is set for my default image in media folder Is there any different way to set default value to versatileImage field . I am wondering ,It works for different projects I have worked on !! -
django-admin startproject myapp . gives me a big error
Traceback (most recent call last): File "/Users/x/Dev/tryDjango/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/init.py", line 371, in execute_from_command_line utility.execute() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/management/templates.py", line 117, in handle django.setup() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/init.py", line 16, in setup from django.urls import set_script_prefix File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/init.py", line 1, in from .base import ( File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/urls/exceptions.py", line 1, in from django.http import Http404 File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/http/init.py", line 5, in from django.http.response import ( File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/http/response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/serializers/init.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/core/serializers/base.py", line 6, in from django.db import models File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/init.py", line 3, in from django.db.models.aggregates import * # NOQA File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/expressions.py", line 486, in class TemporalSubtraction(CombinedExpression): File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/expressions.py", line 487, in TemporalSubtraction output_field = fields.DurationField() File "/Users/x/Dev/tryDjango/lib/python3.10/site-packages/django/db/models/fields/init.py", line 155, in init if isinstance(choices, collections.Iterator): AttributeError: module 'collections' has no attribute 'Iterator' -
get value from a django form using javascript
I was trying for a long time to figure out how to get the value from a django.form using javascript, however I didn't get any straight answer to it. here is my project: views.py: from django.shortcuts import render, redirect from .forms import TextForm from .Functions import GetData def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TextForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... print("is valid") text = form.cleaned_data['date'] x = GetData(text.day, text.month, text.year) x.getInfo() context = { 'text': text, 'form': form, } return render(request, 'index.html', context) # if a GET (or any other method) we'll create a blank form else: form = TextForm() print("not valid") return render(request, 'index.html', {'form': form}) forms.py from django import forms class TextForm(forms.Form): date = forms.DateField(widget=forms.SelectDateWidget(), label="inputDate") let's say the html file is very basic, like this: <form action=" " method="post" id="form"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> SO the main thing, that I need, is to get the date value from the form -
Celery running in asyncio context
I'm running a Django app that uses Channels and Celery. I am having a non-deterministic issue where sometimes my Celery tasks are being run from the asyncio event loop. I get errors like this: [2021-12-08 20:02:23,699: ERROR/MainProcess] Signal handler <function switch_schema at 0x7f1ce3c09d30> raised: SynchronousOnlyOperation('You cannot call this from an async context - use a thread or sync_to_async.') Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/app.py", line 48, in switch_schema tenant = task.get_tenant_for_schema(schema_name=schema) File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/task.py", line 43, in get_tenant_for_schema cached_value = get_tenant_model().objects.get(schema_name=schema_name) File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 431, in get num = len(clone) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. It doesn't always happen and it doesn't always throw on the same line. Does anybody know why this is happening and how to prevent it from happening? -
Failed to access formData in Django. Uploading Files With VueJS and Axios + Django
I have used code of Uploading Files With VueJS and Axios. I am using backend code Django uploaded images save into database. In after submit and before submit i am able to see images uploaded in console. But After submit i am not able to access formData into django backend. Below is snippet code Template code <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <h2>Multiple Files</h2> <hr/> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label> <span>Files</span> <input type="file" multiple name="file" @change="handleFileUploads($event)" /> <ul v-if="files.length"> <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li> </ul> </label> <div> <img v-for="image in images" :src="image" /> </div> <br /> <button @click="submitFile()">Submit</button> </form> </div> <script> new Vue({ el: '#app', data() { return { files: [], images: [], } }, computed: { filesNames() { const fn = [] for (let i = 0; i < this.files.length; ++i) { fn.push(this.files.item(i).name) console.log('fn'); console.log(fn); } return fn } }, methods: { handleFileUploads(event) { this.files = event.target.files; this.images = [...this.files].map(URL.createObjectURL); console.log('images'); console.log(this.images); let formData = new FormData(); for (var i = 0; i < this.files.length; i++) { let file = this.files[i]; formData.append('files[' + i + ']', file); } console.log('formData'); console.log(formData); console.log('values'); console.log(formData.values()); for (var value of formData.values()) { console.log('value'); console.log(value); } }, submitFile() { … -
How to set user access restrictions in Django
first question. Is there a way to set access rights for a function without giving a conditional expression in django template? Currently, the code below is the code I wrote. If user click the "Click" text, a modal window is created depending on the condition, and if the condition is not met, a message window indicating that you do not have access rights is displayed. However, I think it is unnecessary to enter these conditions every time. {% if request.user.first_name in class.teacher|split:"/" %} <div data-toggle="modal" data-target="#relation_{{ class.id }}" class-id="{{ class.id }}">Click</div> {% else %} <a onclick="alert('You do not have access rights..');" class="col-form-label col-10 show-whitespace" style="cursor:pointer">Click</a> {% endif %} Second question. This example is similar. Through the conditional expression in the template, if the job of the current login account is 'principal', the Principal button is displayed. If it is not the principal job, the Principal button is not displayed on the screen. However, even if it is not a principal, user can connect by entering the '/class/principal/list' url directly. Is there a workaround? {% if job_title == 'principal' %} <a class="btn nav-link nav-link-button" href="/class/principal/list"> <span>principal</span> </a> {% else %} <a class="btn nav-link disabled nav-link-button" href="/class/principal/list"> <span>principal</span> </a> {% endif %} -
how to upload multiple files and use charfields at the same time in django rest framework?
Im pretty new in this field, so I will try to explain this the best way I can. Im trying to upload two different optional files (this means that it is not required to upload them) and also have two optional CharFields as inputs in the same API method. I can better explain this by showing what my views.py, my serializers.py is like and how I would like to be able to enter it in postman. With this, I can upload a file, but after this I have a traceback return None as HttpResponse, because the code cannot continue. views.py class FileUploadView(APIView): parser_classes = (FileUploadParser,) @swagger_auto_schema(request_body=FileSerializer, responses={ HTTP_200_OK: PostSuccessResponseSerializer, HTTP_400_BAD_REQUEST: PostErrorResponseSerializer } ) def post(self, request): # Upload two different OPTIONAL files file_1 = request.data.get('file', None) file_2 = request.data.get('file_2', None) # CharField optional inputs user_input = request.data.get('user_input') or '' foo_char = request.data.get('model_filename') or '' # Do something with the files ... # do something with the CharFields inputs ... return Response(f'Success!', status=HTTP_200_OK) serializer.py class FileSerializer(serializers.Serializer): file = serializers.FileField(allow_empty_file=False, use_url=False) user_input = serializers.CharField() foo_char = serializers.CharField() Postman -
Capital gains calculatation
Does any one knows older version of "capital-gains" python library. This support python3.9+ version. Or any other python library that i can use for capital gains calculation. Can anyone help me? -
How to properly manage categories in django admin?
I have register my models in admin.py as admin.site.register(Food_Gallery) admin.site.register(Gym) admin.site.register(Gym_Gallery) admin.site.register(Gym_Pricing_Plans) admin.site.register(Gym_Programs) admin.site.register(Trainer) admin.site.register(Farm) admin.site.register(Farm_Gallery) admin.site.register(Farm_Products) This shows all the models in a single page in django admin I want to categorize these models into certain categories and display their respective models.How to manage this? Certain examples as Food Gym Farm -
Why is `csrf_exempt` not needed when using django-rest-framework?
When I make a POST request with Postman, I receive an error Forbidden (CSRF cookie not set.) class BooksView(View): def post(self, request): If I use csrf_exempt the error does not occur from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='dispatch') class BooksView(View): def post(self, request): However, this error does not occur at all when I use django-rest-framework from rest_framework.views import APIView # /books class BooksView(APIView): def post(self, request): What is django-rest-framework and the APIView class doing in relation to csrf?