Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store user input using forms or models in Django?
I have a Django ML web app where the user inputs some values and the ML models calculates a value and return it. What I want to do is save those values entered by the user and later use those values to retrain the ML model. Basically the user input should be saved in the database and later I should be able to fetch it for retraining. I have a couple questions regarding this: 1.) Should I use forms for saving user input or should I use models? 2.) What is the difference between using forms or models for saving user input? Any links/material/tutorial would be appreciated! Thanks! -
Is it possible to make a web application with Tkinter? [duplicate]
I wrote a simple application with Tkinter which gets data from an .xlsc file and converts it to a document file. Now, I want to distribute my application as a web application. Can I do it without using Django? -
Django or python version issue: ModuleNotFoundError: No module named 'database'
when i try to start my Django project i get this error which i am unable to solve: ModuleNotFoundError: No module named 'database' The error stack: Traceback (most recent call last): File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 455, in execute self.check() File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/checks/caches.py", line 17, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'database' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/olw/candidatis/database-rest/manage.py", line 22, in <module> main() File "/home/olw/candidatis/database-rest/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() … -
Connect Django with Azure MS SQL Server DB using managed identity
How can I connect my Azure MS SQL Server Database to Django through managed Identity. Currently my Django settings.py file looks like this : DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'HPI_SI_DB', 'HOST': 'abcengine.database.windows.net', 'USER': 'xyz', 'PASSWORD': '*******', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', } }, 'DB2': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'HPI_SI_DB', 'HOST': 'abcdengine.database.windows.net', 'USER': 'xyz', 'PASSWORD': '*******', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', } } } -
How can I add Bootstrap class or css in the Ckeditor at Django for responsive?
I've taken RichTextField from CKEditor. But problem is, that the field is not responsive. It shows perfectly on the big screen but not on the mobile screen or the small screen. How can I responsive this for the mobile screen or the small screen? forms.py: from ckeditor.fields import RichTextField class update_product_info(forms.ModelForm): product_desc = RichTextField() class Meta: model = Products fields = ('product_desc') labels = { 'product_desc':'Description' } widgets = { 'product_desc':forms.Textarea() } settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar':'Custom', 'FontSize':20, 'toolbar_Custom': [ ['Undo','Redo'], ['Styles','Font','FontSize','Bold','Underline','Italic','HorizontalRule','Flash'], ['TextColor','BGColor'], ['Table'] ] } } Template: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{form.media}} {{form.as_p}} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button> </div> </form> -
Django Consecutive Days and Max Consecutive days Query
I have a following model. class CategoryModel(BaseModel): name = models.CharField(max_length=100) icon = models.ImageField(upload_to=upload_icon_image_to) description = models.CharField(max_length=100) user = models.ForeignKey(User,on_delete=models.CasCade) def __str__(self): return self.name The basic idea is that whenever a user added a category In one day whether being 1 or 20 records it is regarded as 1 streak and if the user again adds a new category then it is regarded as a +1 streak so current streak will be 2 and max streak is also 2 if user consecutively adds for 5 days streak is 5 days as it is max streak. I just want to display as { "current_streak":3, "max_streak":12 } here current streak is 3 but previous streak set was 12 so it regarded as max streak Any Idea how I can achieve this query? -
Change default cookies name Django
I've more than 2 website stored under same domain due to budget of buying SSL for different domains. Is their any way that I can change or add suffix in default cookies and session variable name in django to avoid the login session confusion between different django projects ? Example: https://www.lmarts.in/ (Project-1) http://trenzact.com (It will redirect to https://www.lmarts.in/trenzact/) (Project-2) This are 2 different django project server under single django domain. The webserver used is nginx *Projects are still in development Thanks in advance!! -
cloudinary won't upload image in browser and shows empty image box
I'm supposed to upload images using cloudinary in my django app, but they won't upload in the browser. I can upload them from admin perfectly fine, though. The problem is my 'choose file' button lets me choose an image, but it won't display in my browser. And when I make a post, whether its a regular post or one with a picture, an empty box shows up and I can't get rid of it. I'll attach a screenshot for reference and show my code. Sorry if my explanation is confusing, I'm still new. <input type="file" id="img-select"> <script src="static/js/file.js"></script> <script> const imgInput = document.querySelector('#img-select') const imgPreview = document.querySelector('.preview') const pickerBtn = document.querySelector('.upload') imgInput.addEventListener('change', function() { const file = this.files[0] if(!file) return const reader = new FileReader() reader.addEventListener('load', function() { imgPreview.src = this.result }) reader.readAsDataURL(file) }) </script> screenshot for further info, that image was uploaded through admin. and that empty box towards the bottom of the screen is what I'm having trouble with -
Set Common Fields in ModelSerializer
Hi i am fairly new at this so it might be a silly question Suppose i have many model serializer but for eg lets take 4 below is the code class ModelSerializer1(ModelSerializer): class Meta: model = Model1 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer2(ModelSerializer): class Meta: model = Model2 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer3(ModelSerializer): class Meta: model = Model3 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer4(ModelSerializer): class Meta: model = Model4 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] I have other fields in these model serializer but these five fields are common in all the serializer so can i create a BaseModelSerializer so that i can inherit that in these serializer and ill get these fields by default and i dont have to write it again and again. if anyone can help thanks in advance -
How to Rectify Permission Issues in Centos while Serving Django applications via Apache + mod_wsgi?
I have a Django App Configured with via Apache and mod_wsgi The app has issues when current mode is enforcing while running: sestatus [root@localhost html]# sestatus SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: enforcing Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 The error being shown on the webpage is: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. The error in logfile is: [Tue Jul 19 06:45:33.033587 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033591 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033592 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] During handling of the above exception, another exception occurred: [Tue Jul 19 06:45:33.033594 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033597 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] Traceback (most recent call last): [Tue Jul 19 06:45:33.033645 2022] [wsgi:error] … -
Same Dynamic Data coming in every column of webpage
I am doing CRUD using serializers, foreignkeys and I am trying to dynamically list the categories, sub_categories. For example category = 9-6 wear and its subcategories are kurta, skirtset, dress, kurtaset. I want these subcategories below only 9-6wear The issue is that other subcategories are also mentioning kurta,skirtset,dress and kurtaset which I dont want as shown below I have tried for hours but without much success below are my models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=30) category_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) below are the serializer class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" below is my shoppingpage function def shoppingpage(request): cat = Categories.objects.filter(isactive=True) category = CategoriesSerializer(cat,many=True) subcat = … -
django rest framework nested serializer crud operations . what required is to create a api which should be called only once to perform crud operations
models.py class User(models.Model): ROLE_CHOICES = ( ("admin","ADMIN"), ("staff","STAFF") ) username = models.CharField(max_length=256) password = models.CharField(max_length=256) firstname = models.CharField(max_length=256) lastname = models.CharField(max_length=256) email = models.CharField(max_length=256) role = models.CharField(max_length=256,choices=ROLE_CHOICES) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) phone_number = models.IntegerField() company_name = models.CharField(max_length=256) I want to use nested serializer here to do crud operations. -
Using flask, how can I return a row of data as a list
I am trying to get my route to return a row in a list format but it appears to be returning a concatenation of the row items. How can I return the row of data in list format? Here is what I want it to return: ['field1', 'field2', 'field3', 'field4', 'field5'] What it appears to return is: ['field1' 'field2' 'field3' 'field4' 'field5'] Here is my app.py file: from flask import Flask, render_template, json, redirect, request import pandas as pd # Flask constructor app = Flask(__name__) # Data setup salary_table = pd.read_csv("salaries.csv") salary_table.fillna('', inplace=True) headings = list(salary_table.columns) print(headings) data = list(salary_table.values) print(data) # Homepage URL call @app.route("/") def home(): return render_template("home.html", headings=headings, data=data) @app.route('/GetPlayerInfo/<row>') def GetPlayerInfo(row): return row # Listener if __name__ == "__main__": app.run(port=2509, debug=True) Here is my home.html file: <html> <head> </head> <body> <div class="tableContainerDiv"> <table class="table"> <tr class="header"> {% for header in headings %} <th class="cell">{{header}}</th> {% endfor %} <th>Info</th> </tr> {% for row in data %} <tr class="row"> {% for cell in row %} <td class="cell">{{cell}}</td> {% endfor %} <td><a href="GetPlayerInfo/{{row}}">Info</a></td> </tr> {% endfor %} </table> </div> </body> </html> -
Unable to write in a file after django app deployment on aws ec2 using nginx and gunicorn
I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:- lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it. filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp') cpp_code=open(filepath,"w") cpp_code.write(user_problem_code) cpp_code.close() I have tried to modify path in every possible way but got unlucky in every try I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application my project directory structure: online_judge_project/ account/ homesrc/ language/ /* directory containing files in which I want to write */ forcpp.cpp media/ oj/ settings.py problempg/ /* application containing views.py */ views.py static/ staticfiles/ template/ manage.py may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am … -
(django) how to flatten an array inside of a dictionary to an array only
I am currently trying to handle the nested data in django. In my case, I want to remove the key "event_log" and flatten it to a simple array of dictionary only. { "event_log": [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] } The outcome should look like this: [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] I have tried adding a to_representation method to the serializer: class EventDateSerializer(serializers.ModelSerializer): event_log = EventLogSerializer(many=True, read_only=True) class Meta: model = EventDate fields = ['event_log'] def to_representation(self, instance): data = super().to_representation(instance) flatten_data = data['event_log'] for item in flatten_data: for key, value in item.items(): data[key] = value return data However, it turns out this method can only flatten nested dictionary instead of array inside of dictionary. Has anyone got an idea on how to flatten the array inside of the dictionary? Much appreciated. -
How Check ManyRelatedManager is None
-models.py class Role: name = models.CharFiled(max_length=100) comp = models.ForeignKey(Company, models.CASCADE, related_name="comp_roles") users = models.ManyToManyField(User, related_name='user_roles', related_query_name='user_role', through='UserRole') class UserRole(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) based on certain conditions I have two queries -in api_views.py: 1-Role.objects.filter(comp_id=self.comp_id).prefetch_related('users') 2-Role.objects.filter(comp_id=self.comp_id) -RoleSerializer.py class RoleSerializer(serializers.ModelSerializer): users = serializers.SerializerMethodField() def get_users(self, obj): #users: ManyRelatedManager = obj.users logger.info(f"this is obj.users: {obj.users}") logger.info(f"this is n obj.users: {obj.users == None}") # hit the db: # if not obj.users.all(): # if obj.users.exists() == None: # no hit the db: # if obj.users.all() == None: # if obj.users == None: if obj.users.all() == None: logger.info(f"obj.users is None!") return None logger.info(f"obj.users is not None!") serializer = UserReadSerializer(obj.users.all(), many=True) return serializer.data Either obj.users == None log or obj.users.all() == None codition are always false! My question is how can I find out obj.users or obj.users.all() (in RoleSerializer/get_users) is None? so I can decide to return whether None or UserReadSerializer data. -
How create filter for queryset Python django
can someone explain to me how to create a query with 3 sums with different filters for the same column using django's queryset? I tried to create using: sum1 = Sum("price", filter=Q(coins__=1)) sum2 = Sum("price", filter=Q(coins__=2)) sum3 = Sum("price", filter=Q(coins__=3)) but regardless of the filter, it receives the same value for the three filters. My table: Coin-in-out a - 1 - 2 b - 0 - 2 c - 3 - 3 a - 2 - 3 I need a single dictionary that receives the summed value and grouped by coin. -
I don't know why javascript is not working in the below mentioned code for back to top button for the blog page
The javascript in the base footer file is not working and that's why the back-to-top button in the base file is not working as expected. the functionality and all is working in the back-to-top button but the button is not visible because through javascript, I am adding a class active but it is not adding in this page but the base file is also linked to another page and there everything is working fine. I am not able to figure it out why it is not working. Below is the main blog file where base-home-footer file is linked to. {% extends 'media/assets/base-media.html' %} {% load main %} {% load static %} <!-- title start --> {% block title %}Prishni- Our Blog{% endblock title%} <!-- title end --> <!-- header start--> {% block header %} {% include 'assets/base-home-header.html' %} {% endblock header %} <!-- header end --> <!-- Content Start --> {% block mediaContent %} {% load markdownExtras %} <div class="wrapper _bg4586 _new89" id="main-content" role="main"> <div class="_215cd2"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="course_tabs"> <nav> <div class="nav nav-tabs tab_crse justify-content-center"> <a class="nav-item nav-link active" href=" {% url 'media:ourBlog' %} ">Blog</a> </div> </nav> </div> <div class="title129 mt-35 mb-35"> <h1 align="center">Insights, ideas, … -
How to fetchData when react component is in viewport
I am working on a social media type of project, using ReactJS & django, I don't know how do pagination in react (load more post when end of the page is reached) I have implemented pagination on backend using drf api endpoint is something like: /post/api/?page=2 response is like: { "prev": true, "next": true, "data": [...] } -
Django FileField - I/O operation on closed file
I have a simple model Jour and the following model (JourAttachment): class JourAttachment(models.Model): jourreport = models.ForeignKey(JourReport,related_name="jourattachments", on_delete=models.CASCADE) file = models.FileField(null=False) When trying to create a Jour-instance, I add all the attachments the following way: View class JourReportListView(APIView): serializer_class = JourReportListSerializer permission_classes = (IsAuthenticated, ) def post(self,request,*args, **kwargs): user_making_request = request.user if not user_is_admin(user_making_request): return UserNotAdminResponse() attachments = request.FILES.getlist('attachment', None) serializer = JourReportCreateUpdateSerializer(data=request.data,partial=True,context={'attachments': attachments}) valid = serializer.is_valid(raise_exception=True) if valid: serializer.save() status_code = status.HTTP_201_CREATED return SuccessfulResponse(data=request.data, message="Jour report successfully registered!" ,status_code=status_code) return ErrorResponse() Serializer def create(self, validated_data): users = [] attachments = self.context['attachments'] if "additional_workers" in validated_data: users = [w.id for w in validated_data["additional_workers"]] del validated_data["additional_workers"] report = JourReport.objects.create(**validated_data) for a in attachments: JourAttachment.objects.create(file=a,jourreport=report) rerturn report This results in a ValueError: I/O operation on closed file and I have no idea why. -
How to pass a JSONResponse back to Django Template
I have this custom view function that would be automatically executed when the user violates my login policy (this is done via django-axes). I am unable to display my JSONResponse data on Django template. May I know if there is any workaround on this? HTML <form role="agent-login" class="login" id="agentloginform" action="{% url 'agent-login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" placeholder="Email address" name="email" class="form-control"> </div> <div class="form-group togglepassword-right"> <input type="password" placeholder="Password" name="password" class="form-control"> <i class="glyphicon glyphicon-eye-open form-control-feedback" id="togglePassword"></i> </div> <p class="text-danger text-center" id="lockout-error" style="display:none;"> {{ errors.password }} {{ login }}</p> <div class="form-group"> <button data-request="ajax-submit" data-target="[role='agent-login']" class="btn-1 " type="button" id="agent-submit"> Login now </button> </div> </form> custom view def user_lockout(request, credentials): """ Custom accout lockout message for django-axes. change custom_account_lockout_message accordingly to what you need. """ response_data = { "login": "Failed", "error": settings.CUSTOM_AXES_SOFT_LOCKOUT_MESSAGE, } return HttpResponse(JsonResponse(response_data)) I was thinking of using ajax to get my JSONResponse data. But because its a custom button that was done others, I might not be able to change it. This is what I have came up with $('#agent-submit').click(function(e) { console.log('pressed'); console.log($(this).serialize()) console.log(e) $.ajax({ type: 'POST', dataType: 'json', url: '{% url ' agent - login ' %}', data: $(this).serialize(), success: function(response) { var dd = jQuery.parseJSON(response) … -
Want to access a file which is in another docker container from anotherdocker container using python code
We have two docker containers. The first container is backend_device_service which we access using the command -> docker exec -it backend_device_service bash. On this backend_device_container we write our python code. Now I am writing an API which needs to access a file which is on another container rsyslog (server is same just the container is different). We access this container using the command -> docker exec -it rsyslog bash In this container at the path -> /var/log/CPE my file contains which I need to access. However I can access any path in the same container using the following piece of code:- class SysLogReader(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): content = os.popen('cat /app/sdwan_device_service/devices/views').read().strip('\n').lower() logger.info(f"\ncontent of the file:\n {content}\n") dir_path = os.path.dirname(os.path.realpath(__file__)) resp = {"success":True, "message" : f"Directoty path is {dir_path}"} return Response(resp, status=status.HTTP_200_OK) While my problem is how to access the file which is in another container rsyslog. -
How to add search in the Root pages header in Wagtail admin?
In wagtail admin, there are list of pages and subpages, from the side menu: Pages > Home > How can I add a search field to search for the child pages, as follows? Thanks -
Cart functionality in django
I'm building an ecommerce platform and I want to create the add to cart functionality in the website. But for some reason the quantity is not updating. Here's the views.py: def cart_detail_view(request, product_obj=None): if request.method == 'POST' and request.POST.get('action') == 'create-cart_product': cart_product_form = CartProductForm( request.POST, ) if cart_product_form.is_valid(): try: cart_product_obj = CartProduct.objects.get( product=product_obj, cart__id=request.session.get('cart__id'), ) cart_product_obj.quantity += cart_product_form.cleaned_data.get('quantity') except CartProduct.DoesNotExist: cart_product_obj = cart_product_form.save(commit=False) cart_product_obj.product = product_obj cart_product_obj.cart_id = request.session.get('cart__id') cart_product_obj.save() messages.error(request, 'something is wrong') return redirect('webshop:cart_detail_view') context = { 'cart_product_form': cart_product_form, } return render(request, 'webshop/cart_detail_view.html', context) This is my forms.py file class CartProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CartProductForm, self).__init__(*args, **kwargs) self.fields['quantity'].choices = tuple([(i, i) for i in range(1, 7)]) class Meta: model = CartProduct fields = ( 'quantity', 'product', ) widgets = { 'quantity': forms.Select(), 'product': forms.HiddenInput(), } I need to update quantity in my views but I don't understand how I am gonna do that? -
How to filter django queryset based on the serializer field value?
serializer class MyModelSerializer(serailizers.ModelSerializer): hrs = serializers.SerializerMethodField() get_hrs(self, obj): datetime = SomeModel.objects.filter(id=obj.id).last().datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" Now in the api there will be a filter paramter hr what it need to do is filter the queryset matching this above calculated hr. For example: @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: qs = qs.filter(hrs=hr) # hrs is not inside model return MyModelSerializer(qs, many=True).data Here hrs is not there inside the Model it's a serializer field above calculated. How can I filter like this from serialzier fields ? Any gudiance would be very helpful.