Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to allow post request in django rest framework correctly?
How to allow post request in django rest framework correctly? Now I get an error while create POST request to api/v3/exchange/order (use POST) Traceback (most recent call last): File "/home/skif/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/skif/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/skif/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/skif/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/skif/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/home/skif/PycharmProjects/beex2/app_ccxt/external_api.py", line 44, in post return getattr(self, self.name)(request) File "/home/skif/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/skif/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/views.py", line 478, in dispatch request = self.initialize_request(request, *args, **kwargs) File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/views.py", line 382, in initialize_request parser_context=parser_context File "/home/skif/.local/lib/python3.6/site-packages/rest_framework/request.py", line 160, in __init__ .format(request.__class__.__module__, request.__class__.__name__) AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `app_ccxt.external_api.ApiExternalCCXT`. [08/Jul/2019 15:40:31] "POST /api/v3/exchange/order HTTP/1.1" 500 44749 I try to change request instance to HttpRequest and nothing changed. my code in external_api.py: from django.shortcuts import render from django.http import HttpResponse … -
Integrate Coverall or Codecov in my application using Docker container
I've been trying to integrate code-coverage in my Django application.. The build is successfull and all the tests are successfull but when i check coveralls.io or codecov.io there is no data.. I have searched everything, added a .coveragerc but still nothing helps. Dockerfile FROM python:3.7-alpine MAINTAINER abhie-lp ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev musl-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app WORKDIR /app COPY ./app /app RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D ABHIE RUN chown -R ABHIE:ABHIE /vol/ RUN chmod -R 755 /vol/web USER ABHIE docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" .travis.yml language: python python: - "3.6" services: - docker before_script: - pip install docker-compose - pip install coveralls - pip install codecov - docker-compose run --user='root' app chmod -R 777 . script: - docker-compose run app sh -c "coverage run --source=. manage.py test" - docker-compose run app sh -c "flake8" after_success: - coveralls - codecov .coveragerc [run] … -
Can't redirect to view using form action method
I'm trying to go to /show_columns/ from /app/chooser/ by setting form action in /app/chooser/ to /dostuff/ but it goes to /app/chooser/dostuff/ instead this is my form in html template <form action="{% url 'learning_logs:show_columns' request.fl "{{ fl }}" %}"> When I click on that submit button it takes me to /columns/extcsv/show_columns when I actually want to go to /show_columns. -
String field based on M2M field in same model
I need to fill a CharField based on M2M field (For grouping proposes). For that I overwrite the save method (for create and update cases). In update case, only works for old M2M selection. In the create case, shows me an error: "maximum recursion depth exceeded". I think the logic isnt taking the form params, but can't find how to access them. Here's my code: class Content(models.Model): specifications = models.ManyToManyField(Specification, blank=True) string_specs = models.CharField(max_length=250, null=True, blank=True) def save(self, *args, **kwargs): if self.pk: self.string_specs = " - ".join([str(element) for element in self.specifications.all().order_by('id')]) super().save(*args, **kwargs) else: self.string_specs = " - ".join([str(element) for element in self.specifications.all().order_by('id')]) super().save(*args, **kwargs) -
image filed return null [duplicate]
This question is an exact duplicate of: image filed returns null if you know how can i fix this,please help me...I have a model like this; I'm trying to create sign up with these fields: username first name last name email address profile image class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=50) Email = models.EmailField(_('email address'), unique=True) Address = models.CharField(max_length=100, default="") UserProImage = models.ImageField(upload_to='accounts/',blank=True, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['Email', 'first_name', 'last_name', 'Address', 'UserProImage'] def __str__(self): return "{}".format(self.username) def get_image(self, obj): try: image = obj.image.url except: image = None return image def perform_create(self, serializer): serializer.save(img=self.request.data.get('UserProImage')) and for this model I wrote a serializer like so: class UserCreateSerializer(ModelSerializer): Email = EmailField(label='Email Address') ConfirmEmail = EmailField(label='Confirm Email') class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'Address', 'UserProImage', 'Email', 'ConfirmEmail', 'password', ] extra_kwargs = {"password": {"write_only": True} } objects = PostManager() def __unicode__(self): return self.username def __str__(self): return self.username def validate(self, data): return data def perform_create(self, serializer): serializer.save(self.request.data.get('UserProImage')) return self.data.get('UserProImage') def validate_email(self, value): data = self.get_initial() email1 = data.get('ConfirmEmail') username = data.get('username') email2 = value if email1 != email2: raise ValidationError("Emails must match.") user_qs = User.objects.filter(email=email2) username_qs = User.objects.filter(username=username) if user_qs.exists(): raise ValidationError("This user has already registered.") if username_qs.exists(): raise … -
is it possible to calculate quantities with price in ManyToMany relation ship in django
i'm trying to create a POS(point of sale) when someone buying multi items for example : mac book ; 900$ ,quantity;3 > 900*3=2700$ , hp pro book;800$,quantity;2 > 800*2 = 1600 class Product(models.Model): product_name = models.CharField(max_length=30) price = models.PositiveIntegerField(default=0) def __str__(self): return self.product_name class Store(models.Model): items = models.ManyToManyField(Product) quantity = models.PositiveIntegerField(default=1) is it possible !? or if not is there another way to achieve the same result -
How to send responses in Wit.ai and integrate it with Django?
I've built a Watson bot previously. Their bot building interface has this section called "Dialog" where u could add multiple responses to a single intent trigger. However I fail to find anything like this in Wit.ai Some tutorials taught me to generate replies with IF ELSE statement, Also making ECHO bot. But then whats the point of this platform? If there is any other way to do it, and I'm unaware, please help. Also I need to integrate it with Django, is it possible? If yes, please share the sources. But most importantly how do I generate multiple replies like DialogFlow and Watson? -
Is there any resource on a environment setup for DJANGO and VueJS . I dont find much resources online can anyboody help me with that
I got some articles related to django and vue environment setup. But it isn't Much clear about how to set up environment and how do they interact with each other. An articles on medium which uses existing environment setup. -
How to supply an argument to an URL correctly in Django template?
I am trying to create an API endpoint that accepts the argument cc. The view for this endpoint in module api is: def cc_details(request, cc): return JsonResponse({'cc': cc}) The URL is: urlpatterns = [ path('api/cc_details/<int:cc>', api.cc_details, name='cc_details'), ] I am calling the URL from the template like this: async function get_cc_details(cc) { let url = new URL("{% absurl 'core:analyzer:cc_details' %}" + "/" + cc) const response = await fetch(url) const json = await response.json() console.log(json) } The custom absurl to return absolute URL is: from django import template from django.shortcuts import reverse register = template.Library() @register.simple_tag(takes_context=True) def absurl(context, view_name): request = context['request'] return request.build_absolute_uri(reverse(view_name)) However, when I try to navigate to the index page of my app, I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'cc_details' with no arguments not found. 1 pattern(s) tried: ['api/cc_details/(?P[0-9]+)$'] It will work fine if I just manually go to http://127.0.0.1:8000/api/cc_details/123 for example. My guess is that I am not supplying the argument to the URL in JS function correctly. How can I fix that? -
How do they run these commands in python console within Django project?
How do they run these python commands in python console within their django project. Here is example. I'm using Windows 10, PyCharm and python 3.7. I know how to run the project. But when I run the project, - console opens, which gives regular input/output for the project running. When I open python console - I can run commands, so that they execute immidiately, but how do I run python console, so that I can type some commands and they would execute immediately, but that would happen within some project? Example from here: # Import the models we created from our "news" app >>> from news.models import Article, Reporter # No reporters are in the system yet. >>> Reporter.objects.all() <QuerySet []> # Create a new Reporter. >>> r = Reporter(full_name='John Smith') # Save the object into the database. You have to call save() explicitly. >>> r.save() # Now it has an ID. >>> r.id 1 -
Submit the form to django-ajax
I have an app for Django. a simple number converter from roman to decimal and vice versa. I did the convector itself, making it a module. I could not make an Ajax request so that everything was without an update. viewes.py from . import decroman def home(request): data = { 'title': 'Convector', } return render(request, 'convector/convector.html', data) def res(request): if request.method == "GET": if 'InputConvert' in request.GET: num = decroman.decroman(request.GET['InputConvert']) result = num.result data = { 'convert': request.GET['InputConvert'], 'result': result, 'title': 'Result', } return HttpResponse(result) # return render(request, 'convector/result.html', data) else: return HttpResponseRedirect('/') def res(request): if request.method == "GET": if 'InputConvert' in request.GET: num = decroman.decroman(request.GET['InputConvert']) result = num.result data = { 'convert': request.GET['InputConvert'], 'result': result, 'title': 'Result', } return HttpResponse(result) # return render(request, 'convector/result.html', data) else: return HttpResponseRedirect('/') In the beginning, the essence is that when you start, the home method is displayed. After filling and sending to HTML, a redirect to the page with the answer takes place. convector.html <form action="/result/" method="get" class="form-group"> <div class="form-row"> <div class="form-group col-md-5"> <div class="form-group"> <label for="InputConvert">Enter numbers</label> <textarea class="form-control" id="InputConvert" rows="10" required name="InputConvert"></textarea> </div> </div> <button type="submit" class="btn btn-primary">Converting</button> <div class="form-group col-md-5"> <label for="OutputConvert">Convert</label> <textarea class="form-control" readonly id="StaticResult" rows="10"></textarea> </div> </div> </form> … -
How do I set up a virtualenv that I've inherited
I've inherited a virtualenv and need help getting it running on MacOSX. There's no documentation provided so I'm not sure if it is complete, but need help getting it going. I need help making sure the virtualenv is complete with all dependencies, database, etc. Project should be: Python 2.7 Django 1.3 PostgreSQL Looks lik I can get the virtualenv activated by: $ cd app $ source bin/activate However, doesn't look like it's using Python from within the virtualenv: $ which python /usr/bin/python I've also tried: echo $PATH /virtualenv/app/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin $ pip freeze lists out global packages, not ones originating from within the virtualenv Thanks in advance. Here are the directories and files contained within the virtualenv: |-app |---bin |---include |-----python2.7 |---lib |-----Django-1.3 |-------django |---------bin |-----------profiling |---------conf |-----------app_template |-----------locale |-----------project_template |-----------urls |---------contrib |-----------admin |-------------locale |-------------media |---------------css |---------------img |-----------------admin |-----------------gis |---------------js |-----------------admin |-------------templates |---------------admin |-----------------auth |-------------------user |-----------------edit_inline |-----------------includes |---------------registration |-------------templatetags |-------------views |-----------admindocs |-------------locale |-------------templates |---------------admin_doc |-------------tests |-----------auth |-------------fixtures |-------------handlers |-------------locale |-------------management |---------------commands |-------------tests |---------------templates |-----------------registration |-----------comments |-------------locale |-------------templates |---------------comments |-------------templatetags |-------------views |-----------contenttypes |-------------locale |-----------csrf |-----------databrowse |-------------plugins |-------------templates |---------------databrowse |-----------flatpages |-------------fixtures |-------------locale |-------------templatetags |-------------tests |---------------templates |-----------------flatpages |-----------------registration |-----------formtools |-------------locale |-------------templates |---------------formtools |-------------tests |---------------templates |-----------------formwizard |-----------gis |-------------admin |-------------db |---------------backend |---------------backends |-----------------mysql |-----------------oracle |-----------------postgis |-----------------spatialite |---------------models … -
It is possible to associate f keys (F1 F2 F3 ecc) to a link in template?
Is possible use f key to open specific link in django? I'm using keydowm $(document).ready(function(){ $("body").keydown(function(key) { if (key.which == 113) { // F2 key // here my link like {% url 'test' %} } }); }); TY -
how woul i get rid off this error "OSError: [WinError 123] The filename,"
Am creating a project, When I run the server I get the error named "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect", but before this there is another error which pops up "ModuleNotFoundError: No module named 'dep.urls' ". I have tried this several times by just creating project, an app and mapping to the urls without writting any code and run it but i get the same error above Am using django 2.2.3, python 3.6.8 and mysql 5.7.26. In the previous version of django(2.1.8) was working fine, I have tried to google a lot what I have found is that in the newer version of django there is the new way of mapping to the urls. Am pretty sure that the solution of my problem is in this link. When I open the described file, I don't find where to edit, what is being said is not available in the file. Please help!! urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('dep.urls')), path('admin/', admin.site.urls), ] -
django filter through object after loop in template
I have a page that displays a snapshot of projects in a list of boxes, each box has project owner, title date, that kind of thing, there is also a window within that separates the updates into 7 categories, the updates are in a separate table. Looping through the projects is fine, but the updates come from all the projects. How do I filter out the other projects? I can post my code, but I have done this 2 or 3 times in the past month with no response so suspecting that my structure is completely wrong -
I need help in converting urlpatterns url to their path equivalents
I am helping a friend with a project and I am having trouble converting urlpatterns url to their path equivalents. Any help? I've managed the first part. `path('store', views.product_list, name='product_list'),` But the rest seems challenging urlpatterns = [ url(r'^store', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), ] -
Diplay ModelForm in html
I am creating a webapp in which a user can create a project, inside each project he can answer a set of question(in my app, I call them secondquestions). I am trying to use ModelForm to ease the creation of the form by following this guide: https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/ Howver I do not understand how I can display in my html my form. secondquestions/views.py def secondquestionstoanswer(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == "POST": form = SecondquestionForm(request.POST) if form.is_valid(): form.save() return render(request, 'secondquestions/secondquestionstoanswer.html', {'project':project}) secondquestions/models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from projects.models import Project from django.db import models from django.forms import ModelForm class Secondquestion(models.Model): second_one = models.TextField() second_two = models.TextField() second_three = models.TextField() second_four = models.TextField() second_five = models.TextField() second_six = models.TextField() second_seven = models.TextField() second_eighth = models.TextField() second_nine = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) class SecondquestionForm(ModelForm): class Meta: model = Secondquestion fields = ['second_one', 'second_two', 'second_three', 'second_four', 'second_five', 'second_six', 'second_seven', 'second_eighth', 'second_nine'] secondquestions/secondquestionstoanswer.html {% extends 'base.html' %} {% block title %}First set{% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> {% endblock %} My problem: In my html I just … -
SECRET_KEY settings not empty but returning empty on Wagtail
I just installed wagtail-blog on my project and added blog to the INSTALLED_APPS and url(r'^blog/', include('blog.urls', namespace="blog")), to the main urls.py. Once I migrated, it returned django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I double checked my base.py and it has a string on the SECRET_KEY but is still returning the error. Here's the MIDDLEWARE and INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'global', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.contrib.styleguide', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'bootstrap3', 'copyright', 'landing', 'registration', 'blog', ] MIDDLEWARE = [ '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', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] -
Tablesorter's filter_selectSource removes options not available for current page with server-side pagination and select options preparation
I'm preparing arrays with options for Tablesorter's filter_selectSource in Python/Django. Because initially it worked very strange for me when I switched to server-side filtering. The dropdown options did show up only when I've type one symbol in one of the 'search' filters and then every time it showed select options available one step before. And then I've decided to try and make most of the work on server-side players.views def skaters_averages_json(request, page, sort_col, filt_col, rookie_filt): start = utils.PAGE_SIZE_2*(page - 1) end = start + utils.PAGE_SIZE_2 skaters = Skater.objects.select_related('team') filtering = utils.filter_columns(filt_col) if filtering: skaters = utils.apply_filters(skaters, filtering) if utils.rookie_filter(rookie_filt): skaters = skaters.filter(rookie=True) sorting = utils.sorting_columns(sort_col) one_page_slice = utils.sort_table(sorting, skaters)[start:end] skaters_json = json.loads(serializers.serialize('json', one_page_slice, use_natural_foreign_keys=True)) domain = request.get_host() total_rows = skaters.count() data = utils.process_json(domain, skaters_json, total_rows, page) data['filter_select'] = { **utils.filter_select_opts(skaters, 3, 'position_abbr'), **utils.filter_select_opts(skaters, 4, 'team__abbr'), **utils.filter_select_opts(skaters, 5, 'nation_abbr'), } return JsonResponse(data, safe=False) players.utils def filter_select_opts(skaters_query, col_number, field_name): uniques = list(skaters_query.values_list(field_name, flat=True).distinct()) return {col_number: sorted(uniques, key=lambda x: (x is None, x))} So my JSONResponse looks like this. Page 1 { "total": 41, "rows": [ [row 1] ... [row 25] ], "filter_select": { "3": [ "C", "D", "LW", "RW" ], "4": [ "ANA", "BOS", "BUF", "CAR", "CBJ", "CGY", "CHI", "COL", "DAL", "EDM", … -
distinct doesn't work when I'm use order_by
How to solve this problem? Without sorting everything works. With sorting - no. I found similar questions, read the documentation, but could not be resolved. Here, as I tried. credits = credits.filter(hot=False).order_by('creditpayment__rate', '-creditpayment__period_to').distinct() credits = credits.filter(hot=False).order_by('creditpayment__rate', '-creditpayment__amount_to', '-creditpayment__period_to').distinct('creditpayment__rate', 'creditpayment__period_to') https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct -
django modal not showing up
modal not showing up JS file $(function () { $(".js-create-node").click(function () { $.ajax({ url: 'create/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); }); url file path('create/', mainapp.nodeCreate, name='node_create'), view file def nodeCreate(request): form = NodeForm() context = {'form': form} html_form = render_to_string('includes/partial_node_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) there is no error, it just doesnt show the modal up i am just trying to imiate https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html steps -
Android - Handling different types of JSON data from Django backend
I get the following output from a request: { "allposts": [ { "created": "2019-07-08T12:25:34.732217Z", "description": "My First ImagePost", "id": 1, "imagepostdata": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "owner": "http://127.0.0.1:8000/users/getUserById/1/", "profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "type": "ImagePost", "url": "http://127.0.0.1:8000/posts/getImagePostById/1/" }, { "audio": "http://127.0.0.1:8000/media/Audios/None/placeholder.3gp", "clique": "http://127.0.0.1:8000/cliques/getCliqueById/1/", "created": "2019-07-08T12:25:56.748829Z", "id": 2, "image": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "owner": "http://127.0.0.1:8000/users/getUserById/1/", "profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "text": "My First TextPost", "type": "TextPost", "url": "http://127.0.0.1:8000/posts/getTextPostById/2/", "video": "http://127.0.0.1:8000/media/Videos/None/placeholder.mp4" } ] } The first item in the JSON array represents an image post and the second item represents a text post. I have image and text posts as post type. Here, you can see that the server gives the requesting client the different types collected as one output. The fields of the items can be different. For ex.: imagepostdata vs. textpostdata. Now, I am not sure how to define the model classes in my Android project. I use Retrofit as networking library combined with Gson. My question: It is enough to write the ImagePost and TextPost model classes separately and let Retrofit/Gson handle the rest ? Or should I copy/paste the output to http://www.jsonschema2pojo.org/ and get only one model class for the different items. I am asking because in the callback methods for the Retrofit request, I have to provide also the model … -
How to fix mixed content error in Swagger?
I am running Django RF backend application on Gunicorn. When trying to fetch data from Swagger I get "TypeError: Failed to fetch" In console this error is reported: Mixed Content: The page at 'https://****.com/swagger/' was loaded over HTTPS, but requested an insecure resource 'http://****.com/v2/products/'. This request has been blocked; the content must be served over HTTPS. I tried everything I found and could think of including: Adding secure_scheme_headers = { 'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} to Gunicorn and USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to Django settings. But nothing helps. Swagger for Django: drf-yasg==1.12.1 -
nested serializer (depth/level 3) is it possible to connect 2 already connected serializer to another
trying to add 3rd nested serializer using django rest framework how to add 3rd nested realation in given code given below #models.py class Category(models.Model): cate_id = models.AutoField(primary_key=True) cate_name = models.CharField(max_length=45) class Meta: managed = False db_table = 'category' class SubCategory(models.Model): sub_cate_id = models.AutoField(primary_key=True) sub_cate_name = models.CharField(max_length=45) sub_fk = models.ForeignKey('Category', models.CASCADE, db_column='sub_fk') class Meta: managed = False db_table = 'sub_category' class Products(models.Model): pro_id = models.AutoField(primary_key=True) pro_name = models.CharField(max_length=45) description = models.CharField(max_length=45, blank=True, null=True) price = models.IntegerField() quantity = models.IntegerField() pro_cate_fk = models.ForeignKey('Category', models.CASCADE, db_column='pro_cate_fk') pro_sub_fk = models.ForeignKey('SubCategory', models.CASCADE, db_column='pro_sub_fk') image = models.CharField(max_length=205) class Meta: managed = False db_table = 'products' #serializer.py why cant they provide proper info from rest_framework import serializers from .models import Category,SubCategory,Products class ProductsSerializer(serializers.ModelSerializer): # x= ChildTable.objects.all().values class Meta: model = Products fields = ('pro_id','pro_name','description','price','quantity','image') class SubCategorySerializer(ProductsSerializer): products_set = ProductsSerializer(many=True, read_only=True) class Meta: model = SubCategory fields = ('sub_cate_name','sub_cate_id','products_set') class CategorySerializer(SubCategorySerializer): subcategory_set = ProductsSerializer(many=True, read_only=True,) # pro_subcate_set = SubCategorySerializer(many=True, read_only=True) class Meta(): model = Category fields = ('cate_name','cate_id','subcategory_set') got this error while attempting is it possible to connect 2already connected serializer to another serializer Got AttributeError when attempting to get a value for field `pro_name` on serializer `ProductsSerializer`. The serializer field might be named incorrectly and not match … -
Ajax call on Save in Django Admin
How to call Ajax on save and continue in the Django admin model? Any hack or third party for calling ajax on saving the model with all type of fields in Django admin?