Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add plain text to django form fields?
I wanna add just plain text to django forms. Like this image I have more than 50 questions and some questions belongs forexample personal questions so i wanna add plain text to like this red notice on the image. How to add just plain text field to my form. Here is my models.py file And here is my forms.py file [![enter image description here][2]][2] -
Swagger UI examples using drf-spectacular and x-www-form-urlencoded requests
Is it possible to generate a swagger UI page (and redoc for that matter) that has examples for both application/json and x-www-form-urlencoded request bodies? I can get examples for application/json, but not when selecting x-www-form-urlencoded as the request type fro the swagger/redoc UIs. I'm using the following decorator for the "create" method (in a ModelViewSet) @extend_schema(request=MySerializer) where MySerializer looks like the following... @extend_schema_serializer( examples=[ OpenApiExample( 'Example input', description='Creation of an alias', value={ 'user_id': 1234567890, 'obj_id': 288, 'alias': 'my alias' }, request_only=True, response_only=False, ), ], ) class MySerializer(serializers.Serializer): user_id = serializers.IntegerField() obj_id = serializers.IntegerField() alias = serializers.CharField(max_length=50) The swagger/redocs UIs will happily provide an example dropbox with "Example Input" for an application/json request body (whereby selecting the example will populate the json), but for x-www-form-urlencoded will just show a form to fill in, with no example dropbox in order to populate the fields. I can get examples (and their selection drop boxes) for query strings, i.e. when making GET endpoints that use OpenApiParameter e.g. @extend_schema( parameters=[ OpenApiParameter(name='q', description='Query string to search for', required=True, type=str, examples=[ OpenApiExample( 'Search query', value='foobar' ), ] ), ... ] ) where selecting a drop box entry will populate the text field. However, for x-www-form-urlencoded, this doesn't … -
How can I get libdbcapi_r.so, libdbcapi_r.dylib needed for sqlany-django?
I installed and configured sqlany-django, but have error Could not load dbcapi: Tried: dbcapi.dll, libdbcapi_r.so, libdbcapi_r.dylib. I installed sqlany-django with pip install sqlany-django. According to this I should run $ . /opt/sqlanywhere16/bin64/sa_config.sh , but I don't have a script sa_config.sh. I tried to download libdbcapi_r.so or libdbcapi_r.dylib but I can't find it even here. Then I'd like to add the path to library to LD_LIBRARY_PATH environment variable. How can I solve this? my system is Ubuntu 18.04 Django==1.9 sqlany-django==1.13 sqlanydb==1.0.11 -
Django: Loop through all attributes of a OneToOneField inside the template
I am trying to loop through all the related attributes of a OneToOneField inside a Django template but it gives an 'PropertyFeatures' object is not iterable error. This list of features is going to grow considerably and rendering them out individually with their own {% if %} statement is not a good idea. Is it possible to loop through OneToOneField attributes inside the template? Models class PropertyFeatures(models.Model): property = models.OneToOneField(Property, related_name="features", on_delete=models.CASCADE) is_pet_friendly = models.BooleanField(default=False) has_garden = models.BooleanField(default=False) Views def property_detailview(request, pk): template_name = "property/detail.html" property = Property.objects.get(id=pk) context = { "property": property, } return render(request, template_name, context) Template {% block content %} {% include "includes/navigation/navbar.html" %} <div class="container"> <h1> {{ property.title }} </h1> <div> {{ property.features.has_garden }} <-- This works {% for feature in property.features %} <-- This gives an error {{ feature }} {% endfor %} </div> </div> {% endblock content %} -
Django- admin login page should not affect the login of the website unless admin is login from the website
I want to separate login of admin and login of website. In django, admin login/logout affects website login/ logout basically I don't want this rather I want if admin is login the website gets automatically logout or when switch from admin to website the website require login. this the base.html page views.py for authentication -
Django chain filter show output in separate columns
Django chain filter show output in separate columns(html jinja) -
What am I doing wrong, Docker build is giving me this error " /bin/sh: -c requires an argument , The command '/bin/sh -c' returned a non-zero code: 2"
I am creating a docker file for my messaging-app, Here is my dockerfile. FROM python:3.9-alpine3.15 LABEL maintainer="Noor Ibrahim" ENV PYTHONUNBUFFERED 1 COPY ./message /message COPY ./requirements.txt /requirements.txt WORKDIR /message EXPOSE 8000 RUN RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home user ENV PATH="/py/bin:$PATH" USER user I am running this command docker build . I am getting this error while creating the build. I have tried different things but this error doesn't go away. Suggest me something I will be very grateful. Sending build context to Docker daemon 67.07kB Step 1/11 : FROM python:3.9-alpine3.15 ---> e49e2f1d4108 Step 2/11 : LABEL maintainer="Noor Ibrahim" ---> Using cache ---> 517b54d522ef Step 3/11 : ENV PYTHONUNBUFFERED 1 ---> Running in d8eb9d900584 ---> 29e281514398 Step 4/11 : COPY ./message /message ---> f84edc508eec Step 5/11 : COPY ./requirements.txt /requirements.txt ---> 608149cc5c42 Step 6/11 : WORKDIR /message ---> Running in b26ec4b33053 Removing intermediate container b26ec4b33053 ---> c608a04f1993 Step 7/11 : EXPOSE 8000 ---> Running in 8b4f7f49a3b8 Removing intermediate container 8b4f7f49a3b8 ---> a18f155d9320 Step 8/11 : RUN ---> Running in 6fa80a39c7d0 /bin/sh: -c requires an argument The command '/bin/sh -c' returned a non-zero code: 2 … -
I have some issue when creating django project. I cannot create new project, whenever I run a command, I get error
C:\Users\Dnyane\Documents\file_1>py -m django --version 4.0.1 C:\Users\Dnyane\Documents\file_1>django-admin startproject project_1 CommandError: [WinError 2] The system cannot find the file specified: 'C:\Users\Dnyane\Documents\file_1\project_1' -
`./manage.py migrate` fails with Postgresql while applying migrations for a built-in Django app
The built-in Django app that fails to migrate seems to be django.contrib.sites. Here's the full output of ./manage.py migrate: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, leasikApp, sessions, sites, socialaccount Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying leasikApp.0001_initial... OK Applying sessions.0001_initial... OK Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying socialaccount.0001_initial... OK Applying socialaccount.0002_token_max_lengths... OK Applying socialaccount.0003_extra_data_default_dict... OK Traceback (most recent call last): File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.errors.NumericValueOutOfRange: setval: value 0 is out of bounds for sequence "django_site_id_seq" (1..2147483647) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) … -
How to get only the desired array of list from template
I'm using the apexchart library, and I want to plot the monthly/per person enroll count as a line graph. I want to add only a list of 12 numbers to data in series , excluding the first argument name. I've been looking for a lot of ways to slice a list using JavaScript in a Django template, but I haven't been able to find a solution. Help. series: [{% for enroll in monthly_enroll_list %} { name: '{{ enroll.0 | safe }}', data: {{ enroll | safe }} },{% endfor %} ], -> result: series: [ { name: 'A' data: ['A', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'B', data: ['B', 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'C', data: ['C', 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'D', data: ['D', 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'E', data: ['E', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'F', data: ['F', 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, … -
django access model attribute by subscription
I have a Profile schema: class Profile(models.Model): likedArticle = models.ManyToManyField('articles.Article', related_name='liked_article_set', blank=True) staredArticle = models.ManyToManyField('articles.Article', related_name='stared_article_set', blank=True) likedQuestion = models.ManyToManyField('questions.Question', related_name='liked_question_set', blank=True) staredQuestion = models.ManyToManyField('questions.Question', related_name='stared_question_set', blank=True) there are tons of other like-able and star-able object (only two examples Article and Question provided above), which follows the naming convention of liked<Model._meta.app_label>. I am coding a method for like and dislike serialisation: def tree(model, user): return { 'liked': model in user.profile.likedArticle.all(), 'stared': model in user.profile.staredArticle.all(), } The method is much more than the minimal example provided above, which if I write profile.likedModel, I need to define a method in each Model class, this is tremendous and not pythonic. therefore, I seek for a way, to automate the queryset. here are some methods that I am aware: model.__class__ # Model Model._meta.object_name # return Model in type of str First, I tried subscription: user.profile[f'liked{model.__class__._meta.object_name}'].all() # TypeError: 'Profile' object is not subscriptable Then I tried __dict__ method: model.__dict__ # returns attributes, except for callable, and many to many manager not included in the result Besides going with eval or exec, is there any other ways? thanks for your help. -
How to split a string of one model field and map it to other form field in Django 3.x
My models.py looks like below class MyModel1(models.Model): id = models.AutoField(primary_key=True) tag = models.CharField(max_length=255) class MyModel2(models.Model): id = models.AutoField(primary_key=True) name = models.ForeignKey(MyModel1, on_delete=models.CASCADE) scope = models.CharField(max_length=255) my forms.py looks like below Myform1 = modelformset_factory( MyModel2, fields=('name','scope'), extra=1, my views.py looks like def index(request): template_name = 'main/scope1.html' if request.method == 'GET': formset = Myform1() for form in formset: pass ## tried to split here (but it affects my dropdown in template) ## form.fields['name'].queryset = ## form.fields['scope'].queryset = return render(request, template_name, { 'formset': formset }) Now the tag value in MyModel1 may or may not have a special character - like a-b . If - present in the name I want to split it and have name = a and scope = b of MyModel2 . I tried to manipulate it in the views but not sure how to do that such way my template dropdown shouldn't get affected . -
Save all data in database with one query in Django
I'm a new Django programmer. I write a API call with rest_framework in Django. when call this API, my program connect to KUCOIN and get list of all cryptocurrency. I want save symbol and name this cryptocurrencies in database. For save data to database, I use 'for loop' and in every for loop iteration, I query to database and save data. my code : for currencie in currencies: name = currencie['name'] symbol = currencie['symbol'] active = (False, True)[symbol.endswith('USDT')] oms = 'kucoin' try: obj = Instrument.objects.get(symbol=symbol, oms=oms) setattr(obj, 'name', name) setattr(obj, 'active', active) obj.save() except Instrument.DoesNotExist: obj = Instrument(name=name, symbol=symbol, active=active, oms=oms) obj.save() query to database in every for loop iteration have problem ,How can I solve this problem? Exist any way in Django to save data in database in with one query. Thank you for you help. -
I am having a port mapping issue in django while using docker
Here is my code. I am developing a Django website along with docker here are my codes: docker-compose for development, I am using two services here for charity-app and db, docker-compose.yml version: '3.9' services: charity: build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./charity:/charity - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme Here is my code for production deployment docker-compose-deploy.yml version: "3.9" services: charity: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: context: ./proxy restart: always depends_on: - charity ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: Here is my .env file DB_NAME=dbname DB_USER=rootuser DB_PASS=changeme SECRET_KEY=changeme ALLOWED_HOSTS=127.0.0.1 Here is my view from django.http import HttpResponse def homePageView(request): return HttpResponse("Hello, World!") Here is my urls.py for app named as core in django charity project from django.urls import path from core.views import … -
This model form is not getting saved when submitted ajax django
I need this form to get submitted but it is not i got the ajax code from the net i don;t know ajax or anything else but i am willing to learn ajax or j query if it is really required Template (only the essential bits): <form method="post" class="Comment_Form" id="Comment_Form"> {% csrf_token <div class="comment_builder">{{ comment|materializecss }}</div> <button class="btn waves-effect waves-light btnw" type="submit" name="submit" value=" {{ Img.id }}" id="submit">Comment<i class="material-icons right">send</i> </button> </form> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"> </script> <script type="text/javascript"> $( "form" ).on( "submit", function(e) { const dataString = $(this).serialize(); const the_effing_id = $('#submit').val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ type: "POST", url: "{% url 'Home' %}", contentType: 'application/json; charset=UTF-8', dataType: 'json', data: { dataString, 'the_effing_id':the_effing_id, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function () { alert("Saved") } }); e.preventDefault(); }); </script> Model code: class Comment(models.Model): not_post_method_ok = … -
How to unapply migrations or remove table programmatically? using schema_editor in migration file
I want to unapply migration file 1.py and apply 2.py and 3.py. How can I programmatically do it? Like using schema_editior in 2.py or in 1.py def remove_tables_from_1(apps, schema_editor): *function to remove* migrations.RunPython(remove_tables_from_1), -
Instance error Django Test models.py AttributeError: 'NoneType' object has no attribute
I am performing a Django test case for models.py file the models.py file looks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) … -
ImportError: cannot import name 'render_to_response' from 'django.shortcuts' - Django 3.2 Python 3.8
I am getting this error Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/djcelery/admin.py", line 11, in <module> from django.shortcuts import render_to_response ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/shortcuts.py) I got this when I upgraded Django from 2.2 to 3.2 My python version is 3.8. I am not using render_to_response anywhere in my code is it related … -
django.db.utils.OperationalError: (1074, "Column length too big for column 'value' (max = 16383); use BLOB or TEXT instead")
I am trying to host my website using FileZilla and PuTTY. For that, I have added the code in FileZilla remote site and I have created a database named jobs using following commands in PuTTY app. sudo mysql -u root #For Maria DB CREATE DATABASE jobs; GRANT ALL PRIVILEGES ON jobs.*TO 'hello'@'localhost'; flush privileges; exit Then python3 manage.py makemigrations command is executed and after that when I executed the python3 manage.py migrate command I got an error like this. django.db.utils.OperationalError: (1074, "Column length too big for column 'value' (max = 16383); use BLOB or TEXT instead") Can anyone suggest a solution to solve this issue? -
django graphene, arguments raise Unknow argument error for ObjectType
I have a arguements in mutation like class Arguments: id = graphene.String() detail = DetailType() Here DetailType is DjangoObjectType in my mutation function def mutation(parent, info, id, detail) I want to take value like this where detail is dictionary But Its giving me error like Unknown arguement detail What is the issue here ? Am I not allowed to create arguments from ObjectType ? -
Filtering Forms in Django
I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions. My model is this: class Region(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Salesman(models.Model): region = models.ForeignKey(Region, related_name='region', on_delete=models.CASCADE) name = models.CharField(max_length=40) surname = models.CharField(max_length=40) def __str__(self): return self.name class Rating(models.Model): RATING_CHOICES = [(i, str(i)) for i in range(1,6)] salesman = models.ForeignKey(Salesman, related_name='salesman', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) rating = models.IntegerField(choices=RATING_CHOICES, blank=False) sent_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.phone I found modified __init__ method for my forms.py: class RateAddForm(forms.ModelForm): class Meta: model = Rating def __init__(self, region_id=None, **kwargs): super(RateAddForm, self).__init__(**kwargs) if region_id: self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id) And also my views.py is this: def report_add(request, region_id): if request.method == 'POST': print(region_id) form = RateAddForm(request.POST, region_id=region_id) if form.is_valid(): message = "Thanks!" form.save() return HttpResponse(message) else: print("Something went wrong!") form = RateAddForm() else: form = RateAddForm(request.POST) return render(request, 'account/report.html', {'form': form}) It still shows me all salesmen on my database, even if i choose a region. How … -
Django rest framework Serializer returns null value even if there's object exist
when i hit the detail view or list view, it returns null each time. but i have 300+ address object in my database. The code attached here. Model: class Address(BaseModel): order = models.ForeignKey(Order, related_name='addresses', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) house = models.CharField(max_length=200) optional = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) postal_code = models.CharField(max_length=200) email = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address_type = models.PositiveIntegerField(choices=AddressType.choices(), default=0) Serializer class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' View class AddressDetailApiView(generics.RetrieveAPIView): queryset = Address.objects.all() serializer_class = AddressSerializer lookup_field = 'pk' Error TypeError at /api/v1/address-detail/293 'NoneType' object is not iterable N.B.: Object with ID 293 exist in my database. List view also return all the object but address all the object as null. -
How do I save django rest authorization token in db cache?
I am using 'rest_framework.authentication.TokenAuthentication', I am not allowed to use any other Token library. Is there a way to instruct Django to save an access token to db cache? Also, is there a command or library that will allow me to call for a new key to be generated? I have configured my backend cache as follows and would like Tokens saved here... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'TOKEN_cache_table', 'TIMEOUT': 600, #=10 minutes in second 'OPTIONS': { 'MAX_ENTRIES': 5 } } } -
how to filter data in different models in django?
my models class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) email_verified = models.BooleanField(default=False, blank=True) phone = models.CharField(max_length=200) phone_verified = models.BooleanField(default=False, blank=True) company_id = models.ImageField(upload_to=get_file_path_id_card, null=True, max_length=255) company_id_verified = models.BooleanField(default=False, blank=True) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name this is my model , how to filter data in multiple model? -
I keep getting "false" in my response body, even when the request is successful
My function in my viewset ... def create(self, request): context = {'request':request} serializer = StorySerializer(data=request.data, context=context) if serializer.is_valid(): story = serializer.create(request) if story: return Response(status==HTTP_201_CREATED) else: return Response(status==HTTP_400_BAD_REQUEST) Screenshot of the response a screenshot of my api response