Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detail: Unsupported media type "application/json" in request in django and Vue JS
I am trying to upload a file in my website . However, i got an error Unsupported media type "application/json" in request in python django backend. Not too sure if it is frontend problem or backend problem. But in the django backend , it shows that the API has unsupported media type. Can anyone help me this ? frontend <v-file-input type="file" label="Attachment" multiple prepend-icon="" prepend-inner-icon="mdi-file" v-model="inputs[i].value" :outlined="outlined" > </v-file-input> models.py class ClinicVisit(models.Model): upload_attachment = models.FileField(null=True , blank=True, upload_to='uploads/') views.py class ClinicVisitList(generics.ListCreateAPIView): serializer_class = ClinicVisitSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = ClinicVisitFilter permission_classes = [permissions.IsAuthenticated,] pagination_class = LargeResultsSetPagination ordering = ['-created_at'] parser_classes = [MultiPartParser, FormParser] queryset = get_user_model().objects.all() def get_queryset(self): return ClinicVisit.objects.based_on_access_level(self.request.user) def post(self, request, format=None, *args, **kwargs): file_serializer = ClinicVisitSerializer(data=request.data,instance=request.user) if file_serializer.is_valid(): file = request.FILES['file'] file_serializer.save() print('hello') return response.Response(file_serializer.data, status=status.HTTP_200_OK) else: print('error') return response.Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
Heroku Postgis - django releases fail with: relation "spatial_ref_sys" does not exist
Since Heroku changed their extension schema management (https://devcenter.heroku.com/changelog-items/2446) deployments to our existing django 4.0 application fail with the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedTable: relation "spatial_ref_sys" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 106, in handle connection.prepare_database() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 26, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "/app/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/__init__.py", line 544, in execute return real_execute(self, sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "spatial_ref_sys" does not exist Has anyone experienced the same issue? Is there … -
add manual parameters using drf-yasg, modelviewset
how do I add a manual parameters using drf-yasg? I need two parameters for product id and quantity this is what it looks like right now Swagger api, this is what i want to achieve RestFrameWorkBrowsableAPI. I've tried to add manual parameters with swagger_auto_schema decorators, but nothing changes. this is my views class OrderItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete','head', 'options'] def get_serializer_class(self): if self.request.method == 'PATCH': return UpdateOrderItemSerializer elif self.request.method == 'POST': return AddOrderItemSerializer return OrderItemSerializer def get_queryset(self): return OrderItem.objects.filter(order_id=self.kwargs['order_pk']).select_related('product') def get_serializer_context(self): return {'order_id': self.kwargs['order_pk']} this is my serializers class AddOrderItemSerializer(serializers.ModelSerializer): #product_id = serializers.IntegerField() product_id = openapi.Parameter('product', in_=openapi.IN_QUERY, type=openapi.TYPE_NUMBER) @swagger_auto_schema(manual_parameters=[product_id]) def save(self, **kwargs): order_id = self.context['order_id'] product_id = self.validated_data['product_id'] quantity = self.validated_data['quantity'] try: order_item = OrderItem.objects.get( order_id=order_id, product_id=product_id) order_item.quantity += quantity order_item.save() self.instance = order_item except OrderItem.DoesNotExist: self.instance = OrderItem.objects.create( order_id=order_id, **self.validated_data) return self.instance class Meta: model = OrderItem fields = ['id', 'product_id', 'quantity'] -
Use different delete behavior in admin-django and models.CASCADE
I have two Django models, one referencing the other with a ForeignKey. Something like this: class Data(models.Model): [some fields] class Backup(models.Model): data_source = models.ForeignKey(Data, on_delete=models.CASCADE) storage_destination = models.ForeginKey(S3Bucket, on_delete=models.CASCADE) The behavior I want is that After the deletion of a "Data" instance, Its backups get deleted from the S3 bucket (I can handle this by invoking a Temporal workflow like DeleteFromS3Workflow, no Django hack is needed), and after the completion of DeleteFromS3Workflow, the "Backup" model gets deleted from the database. Beyond this, I want to be able to delete a "Backup" object from Django admin without invoking the Temporal workflow and directly deleting the object from the database (the thing uncustomized delete() method of the model does). Overwriting the delete() method on the "Backup" model doesn't satisfy this as long as it deletes the model before the completion of workflow and this behavior is mutual in both cases. -
how to use prefetch_related or select_related with multitable inheritance
hey guys i have these models class Product(models.Model): ....... class Course(Product): ......... class Book(Product): ......... class Cart(models.Model): product = models.ForeignKey(Product) what I want is to prefetch the products with the Cart objects i know we can do this Cart.objects.select_related('product') but how do we also get the product to children too without making an impact on the performance and if i get it's children how can get it's child when accessing the product like: cart_instance.product.its_child -
how to Update the value of another model in Django Models
i want Contract_bills_amount field in class contract update from bills_mount field in class bills ? #Contract class Contract(models.Model): Contract_code = models.CharField(max_length=200) Contract_rec = models.DateTimeField('contract date ') Contract_total_amount = models.FloatField('total amount') Contract_deposit= models.FloatField('deposit') Contract_remainder_amount=models.FloatField('Contract remainder amount',null=True,blank=True) Contract_bills_amount=models.FloatField('bills_amount',null=True,blank=True) Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE) Contract_car = models.ForeignKey(Car, on_delete=models.CASCADE) def save(self, *args,**kwargs): a=self.Contract_total_amount b=self.Contract_deposit self.Contract_remainder_amount=a-b super(Contract,self).save(*args,**kwargs) def __str__(self): return self.Contract_code #Bills class bills(models.Model): bills_Contract = models.ForeignKey(Contract, on_delete=models.CASCADE) Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE) bills_code = models.CharField(max_length=200) Contract_rec = models.DateTimeField('date') bills_mount= models.FloatField('amount') def __str__(self): return self.bills_code strong text -
django CBV doesnt pagginate with editing context
View down below should show the tasks for the logged user but when I paginate the tasks I got Cannot filter a query once a slice has been taken. how should I filter the context to avoid the error for pagination? class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' template_name = 'TaskList.html' paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) return context -
django inspectdb-generated gitlab models throws errors when making migrations
i have generated inspectdb models for my django project. They are models generated from gitlab postgres database extracted by pg_dump. So now i have models.py file having something like 8k lines, and when trying to make migrations i get multiple errors. Some of the examples are: (They are mostly the same just with different variables) trackApp.Appearances.favicon: (fields.E121) 'max_length' must be a positive integer. or trackApp.AnalyticsDevopsAdoptionSegments.namespace: (fields.E304) Reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.namespace' clashes with reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.display_namespace'. I would be able to fix this by hand, but having a 8k lines long file makes this impossible. Is there any trick i could use to "mass-fix" these errors? -
unknow `runcrons` when running `python3 manage.py runcrons
When I run python3 manage.py runcrons, this message appears: "Unknown command: 'runcrons'". I run python3 manage.py help and couldn't find runcrons in the list of commands. How can I add runcrons to manage.py enter image description here -
Failed to push to heroku - Requested runtime (ÿþpython-3.8.0) is not available for this stack
When I try and push my django app to heroku I get the following error: Requested runtime (ÿþpython-3.8.0) is not available for this stack (heroku-20). This looks like an error with runtime.txt - I've tried changing the formatting from UTF-16 to UTF-8 which was suggested elsewhere. "ÿþ" was not included in my runtime.txt so this I why I think it's an encoding issue Does anyone know why this is occuring? Cheers! -
Problem with install GeoDjango Could not find the GDAL library
I followed with instruction: https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/ for Windows 10 I downloaded Postgres and added installed Postgis. Then OSGeo4W in the folder C:\OSGeo4W and maked point Modify Windows environment I create new project and one application. In settings.py added: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'geo', }, } After run py manage.py runserver I get a error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIB RARY_PATH in your settings. I add (Python Root)\Lib\site-packages\django\contrib\gis\gdal\libgdal.py "gdal305", becauuse this file i have in C:\OSGeo4W\bin. I get a error: FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal305.dll' (or one of its dependencies). Try using the full path with constructor syntax. (this path is good ) In settings.py I add: GDAL_LIBRARY_PATH = r'C:\OSGeo4W\bin\gdal505', but I'm showing the same error as before. So I try in settings.py: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] And I still get … -
Django reverse error when passing additional variable
I am attempting to pass variables through different django views. The error I am getting is: Reverse for 'download_file' with keyword arguments '{'path_id': '19', 'filename': 'TESTCE-DCNCE-01.conf'}' not found. 1 pattern(s) tried: ['download/(?P<filename>[^/]+)/\\Z'] I have this working code: This is my view.py def report(request, pk_test): order = Order.objects.get(id=pk_test) path_id = str(order.id) outpath = 'orchestration/outputs/' + str(order.id) files_configs = glob.glob(outpath + '/*.conf', recursive=True) files = [] for each_file in files_configs: head, tail = path.split(each_file) files.append(tail) context = { 'order': order, 'files_configs': files, 'path_id': path_id, } return render(request, 'orchestration/report.html', context) Here is my report.html: {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' filename=each_files_configs %}">{{ each_files_configs }}</a> {% endfor %} This is my views.py, which is linked to the href: def download_file(request, filename=''): if filename != '': When I run the code like ths, it works fine. If I then add the additional parameter 'path_id' as below, I get a reverse error. Surely path_id is no different from passing in filename? {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' path_id=path_id filename=each_files_configs %}">{{ each_files_configs }}</a> {% endfor %} This is my views.py, which is linked to the href: def download_file(request, path_id='', filename=''): if filename != '': -
Django graphene - Unable to query union field
In my application I have 2 models: class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100, null=False) email_id = models.EmailField(null=False) class UserGroup(models.Model): created_by = models.EmailField(null=False) An UserGroup can be created by an Employee or by the "System". So, the possible values for "created_by" are: "employeex@mail.com" "System" Now, I want to expose this property in graphql. From the graphql, I want to be able to get the properties of created_by (like firstName, lastName etc) if created_by is an Employee. Otherwise I want to get String in the graphql response. Here is what I have done so far: import graphene from graphene_django.types import DjangoObjectType from models import Employee, UserGroup class EmployeeObjectType(DjangoObjectType): class Meta: model = Employee class UserGroupCreatedBy(graphene.Union): class Meta: types = (EmployeeObjectType, graphene.String, ) class UserGroupType(DjangoObjectType): created_by = graphene.Field(UserGroupCreatedBy) def resolve_created_by(self, info): if self.created_by == "System": return self.created_by return Employee.objects.get(email_id=self.created_by) class Meta: model = UserGroup query { userGroups { createdBy { ... on EmployeeType { firstName } } } } When I request the graphql API, this is the error that I am getting: ERROR:django.request:Internal Server Error: /graphql Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 113, in __call__ response = self.process_request(request) … -
not found url when use persian/arabic slug in django
database: mysql database Collation encode: 'utf8_persian_ci' django version: last version python version: 3.7.12 Point: It work well in local host but not working in real host Error : models.py : class blog(models.Model): slug = models.SlugField(max_length=255,allow_unicode=True,unique=True) title = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self): return f'title: {self.title}' Views.py : def blogViews(request,slug): if blog.objects.filter(slug=slug).count() > 0: post = blog.objects.get(slug=slug) context = { 'post': post, } return render(request,'blog/post_detail.html',context) else: return HttpResponseNotFound() i tried these: 1- change get_bytes_from_wsgi encode in django/core/handlers/wsgi.py return value.encode('ISO-8859-1') to return value.encode('UTF-8') 2- django setings.py: ALLOW_UNICODE_SLUGS = True How do I fix it? -
Django modelform initial value doesn't work
def createProject(request): form = ProjectForm() initial_data = { 'responsible':request.user.username } yonetici = Project(host=request.user) if request.method == 'POST': form = ProjectForm(request.POST, instance=yonetici,initial=initial_data) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'base/project_form.html', context) i tried many solutions but i couldnt make it work where am i doing wrong? -
How can I get a text in a particularly element in RichTextField Django?
Actually I have a TOC page in which data is dynamic. There is a RichTextUploading Field for this but the problem is that I have a sidebar on page which will anchor to the heading in RichTextField. I have to get the heading value and give it a id for anchoring it. How can I do that? Thanks -
Django - ModuleNotFoundError: No module named 'csvexport'
So I'm working on adding an admin function to a Django project so that I can export the model instances to csv. It is all working fine locally whilst using Docker. But when deploying I get this internal server error: It states that the package is not installed, but when accessing the Django shell (poetry run python3 manage.py shell) and importing the package (from csvexport.actions import csvexport) everything works fine. I'm stuck for quite some time now on this and cant figure out what is going wrong. Anyone had some kind of problem like this with poetry package managing? settings.py: INSTALLED_APPS = [ ... 'csvexport', ] model: from csvexport.actions import csvexport from django_summernote.admin import SummernoteModelAdmin class FundAdmin(SummernoteModelAdmin): ... actions = [csvexport] -
How Django Implement tier selection
Is that Django have any feature that can implement tier selection? the form like this, first, user select the first field says gender, then the next category field will list out all the category belongs to this gender says Male. -
multiple event targets on same parent element not working
I have been dealing with this problem for quite some time. It's been a great way to learn Javascript, but I'm just done and need help before I end up in prison for something dumb. I need the inline formset's delete checkbox checked before removing the parent element (form). I am using Django's inline formsets and refuse to use jquery to handle this because I want to learn good ol' vanilla Javascript. I have tried all kinds of combinations and solutions with nothing to show. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <form id="all-add-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> {{ sun_bool.sunday|as_crispy_field }} {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday Timeslot </button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %} const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm … -
Invalid HOST header: 'ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'. You need to add 'ec2-13-233-105-50.ap-south-1.amazonaws.com' to ALLOWED_HOSTS
I have been getting this error even when I added the public ipv4 address added to the allowed hosts. I don't know what I am doing wrong. This is My settings.py code. I'm trying to run this application in amazon ec2 instances. Using bitbucket code deploy pipeline. but my code giving this unusual error. """ Django settings for Cycatz project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'] ENV = "dev" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cycatzapp', 'rest_framework', 'corsheaders', 'ebhealthcheck.apps.EBHealthCheckConfig', 'drf_yasg' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Cycatz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Whats the best strategy to upload and process big macros file
I have a project which allow user to upload macros files, about 30Mb each file. After uploading a file I need to process it like open that workbook then pick a sheet then insert the data inside to database. I realize that just open the workbook with openpyxl is taking too much time. So what's the best way to do this, do I need to run it concurrently in the background or any other option and how to achieve that. I'm using Django btw. Thanks in advance -
Django shell history commands always come from top
I've been having issues in trying to use older Django shell history commands, be it from previous shell session or current. If I press UP arrow key, they show the first lines in the ~/.ipython/profile_default/history.sqlite, and not the last one I pressed enter on. A couple of things I've tried are: Removed ipython history file, touched it again but same problem. Re-installed Ipython in venv. Tried using shell from a different project. Tried using shell_plus from django-extensions. Nothing seemed to fix the issue. Does anyone have a clue how to fix this? -
Testing cursor.execute with sql script called
Function to test def get_adgroups_not_taked_share( campaign_ids: List[str], src_table: str, spend_src_table: str ) -> List[Tuple[str, str]]: loses_adgroups: List[Tuple[str, str]] = [] with RedshiftCursor() as cursor: cursor.execute( """ SELET some_data from some_table WHERE some_condition """ ) for row in cursor.fetchall(): loses_adgroups.append((row[0], str(row[1]))) return loses_adgroups There is a test for this function import pytest from my_ap import get_adgroups_not_taked_share @pytest.fixture def campaigns_redshift_cursor_mock(mocker): cursor_mock = mocker.MagicMock() cursor_mock.fetchall.return_value = [ ('hs_video544', '123123123', 100), ('hs_video547', '123123123', 50), ] rs_cursor_creator = mocker.patch('google_panel.logic.clean_creative.RedshiftCursor') rs_cursor_creator.return_value.__enter__.return_value = cursor_mock return rs_cursor_creator @pytest.mark.django_db def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): campaign_ids = ['1111', '2222', '3333'] result = get_adgroups_not_taked_share(campaign_ids, 'test_table', 'spend_src_table') assert result == [('hs_video544', '123123123'), ('hs_video547', '123123123')] Now I want to add a new feature to test the sql script. Checking that the correct sql query is being called. something like def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): ...... query = """SELET some_data from some_table WHERE some_condition""" campaigns_redshift_cursor_mock.execute.assert_called_with(query) But got E AssertionError: Expected call: execute('query') E Not called -
DJANGO FILTERING ON FORIEGN KEY PROPERTIES
I HAVE 2 MODELS class Cart(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE,blank=True, null=True) user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True) quantity = models.IntegerField(default=1) class Item(models.Model): restaurant = models.ForeignKey(Restaurant,on_delete=models.CASCADE,null=True, blank=True) name= models.CharField(max_length=100) is_active = models.CharField(max_length=30,null=False,default=True) is_avaliable = models.CharField(max_length=30,null=False,default=True) price = models.CharField(max_length=30,null=False,default=0) WHERE cart is using restaurant as a foreign key in views.py def post(self,request,*args,**kwargs): userid = request.user.id res= request.data.get('restaurant', False) cartItem = Cart.objects.filter(user=userid,item__restaurant__contains=res) it is throwing an error saying raise FieldError( django.core.exceptions.FieldError: Related Field got invalid lookup: contains [02/Aug/2022 08:37:45] "POST /placeorder HTTP/1.1" 500 118627 what i want to do is Get all cart objects which has user id = userid and item.restaurant = restaurant id ... can someone help me i referred this page https://stackoverflow.com/questions/1981524/django-filtering-on-foreign-key-properties but i doesnt seems to work! -
How to make API post request when using django-countries package
I came across this package called django-countries and the the features it provides look nice. Now I'm trying to test it out in a react application but I'm having issues making API post request when trying to post a named country to the database. Instead of CharField I used countryField() provided by the package. I have tried several format to make post request from postman but I keep having the error:"country_name" is not a valid choice. One of the ways I have tried out is this: { "country": "country_name" } How do I go about it. Since I'm using react, will be better for me to use charField instead of using the django-countries package since I'll be using html select option to get the country of the user?