Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
column "user_id" of relation "checkout_order" does not exist
I am trying to attribute orders to particular user accounts which I have already created.I have gone through the process I did on a previous app but it is not working and keeps throwing up the following error. I think it is something to do with the placement of the user foreignkey but I cant figure it out or find any other posts on here related to it. My model.py file is as follows. from django.db import models from babysitters.models import Babysitter from django.contrib.auth.models import User class Order(models.Model): user = models.ForeignKey(User) def __str__(self): return "{0}".format(self.date) class OrderLineItem(models.Model): order = models.ForeignKey(Order, null=False) babysitter = models.ForeignKey(Babysitter, null=False) quantity = models.IntegerField(blank=False) price = models.IntegerField(blank=False) def __str__(self): return "{0} {1} {2} @ {3}".format(self.quantity, self.babysitter.firstName, self.babysitter.quantity, self.babysitter.price) My forms.py is from django import forms from .models import Order class MakePaymentForm(forms.Form): MONTH_CHOICES = [(i, i,) for i in range(1, 13)] YEAR_CHOICES = [(i, i,) for i in range(2018, 2036)] credit_card_number = forms.CharField(widget=forms.TextInput(attrs= {'placeholder':'Credit card number'}), max_length=16, label='Credit card number', required=True) expiry_month = forms.ChoiceField(label="Month", choices=MONTH_CHOICES) expiry_year = forms.ChoiceField(label="Year", choices=YEAR_CHOICES) cvv = forms.CharField(widget=forms.TextInput(attrs= {'placeholder':'cvv'}), max_length=3, label='Security code (CVV)', required=True) stripe_id = forms.CharField(widget=forms.HiddenInput) class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('user',) and views.py is from django.contrib import … -
Django REST ModelSerializer --- General Question
I am working through a tutorial that includes the building of an articles app. I have an Article model that I am serializing and I am curious about why I need to explicitly set certain fields when using a ModelSerializer. Her is my model: from django.db import models from core.models import TimestampedModel class Article(TimestampedModel): slug = models.SlugField(db_index=True, max_length=255, unique=True) title = models.CharField(db_index=True, max_length=255) description = models.TextField() body = models.TextField() author = models.ForeignKey('profiles.Profile', on_delete=models.CASCADE, related_name='articles') def __str__(self): return self.title Pretty standard stuff. Next step is to serialize the model data in my serializers.py file: class ArticleSerializer(serializers.ModelSerializer): author = ProfileSerializer(read_only=True) # Three fields from the Profile app description = serializers.CharField(required=False) slug = serializers.SlugField(required=False) class Meta: model = Article fields = ( 'author', 'body', 'createdAt', 'description', 'slug', 'title', 'updatedAt', ) Specifically, why do I need to explicitly state the author, description, and slug fields if I am using serializers.ModelSerializer and pulling those fields in from my model in my class Meta: below? Thanks! -
Forward Based On Domain Name With Elastic Beanstalk
I have two domains - example.com example2.com I want to redirect any traffic from example.com to example2.com. I was forwarding using DNS records, but if anyone goes to https://example.com, it won't forward any traffic. Is it possible to set a configuration within ebextensions to accomplish this? -
How to link tags to search results in a Django Blog?
I am building a blog in django and am using django-taggit. I'm trying to figure out how to tie the link of a tag to the search result page that shows all of the posts using that tag. I already have the search page created, I know how to filter queries to the page to bring the correct results, and know how to link to the page itself {% url 'search' %}. But how would I pass queries to the page from the template? For instance, if I have a post tagged "dog" I want users to be able to click on the tag "dog" and be taken to the search page that only has results for posts also tagged "dog". The django documentation does not have examples of this. And every tutorial resource so far has been focused on the filtering and displaying of the search page itself rather than linking to it with desired queries in an <a> tag instead of a <form>. -
Django: Save JSON to database using Fetch/Post
In a Django app, I want to save JSON to the database using the fetch/post API, and I'm having CSRF verification troubles. I have a model "Job" with a field that should hold JSON. class Job(models.Model): job_id = models.IntegerField() setup_json = models.CharField(max_length=100000, blank=True, null=True) The JSON is generated thru user interactions on a page. When the press a "save" button I want to write the JSON to the setup_json field of the proper job. I don't want to use a form, because the JSON is stored in JavaScript and not written anywhere on the page. So I get the CSRF token from the template to use directly: {% csrf_token %} <script type="text/javascript"> const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value; </script> (Note: in my "settings.py" file I added the line CSRF_USE_SESSIONS = True in order to use this technique.) Then I have my save button call a function like this: function onPressSave() { fetch(`webapp/api/save-json/${jobId}`, { method: "POST", headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRF-Token": csrftoken, "Content-Type": "application/json; charset=utf-8", Accept: "application/json" }, credentials: "same-origin", body: JSON.stringify("test json") }); } I get a "POST 403 (Forbidden)" error in the console. Any help would be greatly appreciated! -
Cache large a Queryset in Django rest framework
i faced with problem. I have endpoint, which gives all objects, about(600). When first request I get all elements, but if after request create new a records, created record will not receive. But why? After reload server, created records is receive and missing pagination for this endpoint. Thanks -
Debug Django application in VSCode
I'm trying to debug a Django app within Visual Studio Code and the breakpoints are not being hit and I have the following error: pydev debugger: warning: trying to add breakpoint to file that does not exist: c:\projects\code\testapp_env\testapp\polls\views.py (will have no effect) The launch.Json has the following format: { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": false, "program": "${workspaceFolder}/testapp/manage.py", "console": "integratedTerminal", "args": [ "runserver" ], "django": true, "env": {}, "envFile": "${workspaceFolder}/.env" }, Thank you in advance -
Experience with Django or other frameworks?
**hi, what are your experiences with django? I want to start developing apps and web development. If you use other frameworks which ones would you suggest? I really want to create apps and write programs. I even think of quitting university because of this. ** -
Ignore any redirect when POSTing from Python Requests module?
I use this script to access my Django server and retrieve a CSRF token which then simply attempts to POST data to a view: #!/usr/bin/env python2.7 import sys, time import requests username = 'root' password = 'pass' fileName, userFolder, uploadFolder = sys.argv URL = 'http://127.0.0.1:8000/admin/login/' client = requests.session() # Retrieve the CSRF token first client.get(URL) # sets cookie if 'csrftoken' in client.cookies: csrftoken = client.cookies['csrftoken'] login_data = dict(username=username, password=password, csrfmiddlewaretoken=csrftoken, next='') r = client.post(URL, data=login_data, headers=dict(Referer=URL)) But in my Django development server's access log I see: [03/Dec/2018 17:44:17] "GET /admin/login/ HTTP/1.1" 200 1637 [03/Dec/2018 17:44:17] "POST /admin/login/ HTTP/1.1" 302 0 Not Found: /accounts/profile/ [03/Dec/2018 17:44:17] "GET /accounts/profile/ HTTP/1.1" 404 9904 What I don't understand is why I keep getting an additional Get and 404? Is it possible to configure my Python request to ignore any kind of redirect signal regardless it be for a get or post or session.get? I have tried adding allow_redirects=False to client.get(URL, allow_redirects=False) but that did not help. My POSTs are working fine, I'm simply trying to eliminate the additional GET request as it's unnecessary clutter. Thanks. -
Javascript correctly scoped in nested include template in Django
How do I get the level 3 template to have the same scope as level 1/base? base.html <html> <head> {% block inline-scripts %}{% endblock inline-scripts %} </head> <body> {% block content %} Default Content{% endblock content %} <body> </html> level1.html {% extends "base.html" %} {% block inline-scripts %} {% this will get loaded %} <script src='some/file.js'></script> {% endblock inline-scripts %} {% block content %} Level 1 Content {% include 'level2.html' with whatever=variables %} {% endblock content %} level2.html Level 2 HTML {% include 'level3.html' with whatever=variables %} level3.html Level 3 HTML - How do I get the JS here to have the scope of the level 1/base {% block inline-scripts %} {% this will NOT get loaded %} $(document).ready(function() { //Current error //Uncaught ReferenceError: $ is not defined //Do some stuff }) {% endblock inline-scripts %} <script> manuallyEnteringJS.doesntWorkEither </script> -
Django: Programmatically asociate a user instance with a group, on save
After a user is saved, I need to make sure that its instance is associated with a group by default. I have found two ways to achieve that: Overriding the model's save() method models.py: from django.contrib.auth.models import AbstractUser, Group class Person(AbstractUser): def save(self, *args, **kwargs): super().save(*args, **kwargs) to_add = Group.objects.get(id=1) # get_or_create is a better option instance.groups.add(to_add) Capturing a post_save signal: signals.py: from django.conf import settings from django.contrib.auth.models import Group from django.db.models.signals import post_save from django.dispatch import receiver @receiver( post_save, sender=settings.AUTH_USER_MODEL, ) def save_the_group(instance, raw, **kwargs): if not raw: to_add = Group.objects.get(id=1) # get_or_create is a better option instance.groups.add(to_add) Are these methods equal in achieving their goal? Is there a better one in Django terms of "Good Practice"? -
Sort a python Django query with zero always first, then positives, then negatives
I have Django objects set up like: class Example(models.Model): count = models.CharField(default="0") So if I have some objects ex1, ex2, ex3, ex4 that have count of -1, 0, 5, -6 respectively. I want to be able to query the objects and sort them into the order [0, 5, -6, -1] where any zeros come first, then positives, then negatives while also going in ascending order for each section. I was thinking about using something like Example.objects.order_by('count') but did not find a way to do that with a custom function like Ordering a Django queryset by the returned results of a method The other route I was looking at was something like below: objs = Example.objects.all() sorted_objs = sorted(objs, key = lambda o: int(o.count)) Is there a way to use the sorted method to sort the zeros first? I was unable to find one. The final way I am using is: objs = Example.objects.all() zero_objs = [] positive_objs = [] negative_objs = [] for obj in objs: if obj.count == 0: zero_objs.append(obj) elif obj.count < 0: negative_objs.append(obj) else: postitive_objs.append(obj) sorted_objs = zero_objs + sorted(postitive_objs) + sorted(negative_objs) This works but seems like it's not the best way to do this, so any … -
Django: Model object created with form returning DeferredAttribute on Object.stock_level
I have model called Item class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.DecimalField(max_digits=100, decimal_places=2) item_description = models.CharField(max_length=300) item_bought_price = models.DecimalField(max_digits=100, decimal_places=2) stock_level = models.IntegerField() restock_level = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I also have a form for website admin to add new item object from the website without going to /admin url forms.py class ItemForm(forms.Form): item_name = forms.CharField(label='Item name', max_length=200) item_price = forms.IntegerField(label='Price') item_description = forms.CharField(label='Item Description', max_length=500) item_bought_price = forms.IntegerField(label='Item bought price') stock_level = forms.IntegerField(label='Stock Level') restock_level = forms.IntegerField(label='Restock Level') def clean(self): cleaned_data = super().clean() item_name = cleaned_data.get('item_name') item_price = cleaned_data.get('item_price') item_description = cleaned_data.get('item_description') item_bought_price = cleaned_data.get('item_bought_price') stock_level = cleaned_data.get('stock_level') restock_level = cleaned_data.get('restock_level') views.py def add_item(request): if request.user.is_superuser: if request.method == "POST": form = ItemForm(request.POST) if form.is_valid(): item_name = form.cleaned_data['item_name'] item_price = form.cleaned_data['item_price'] item_description = form.cleaned_data['item_description'] item_bought_price = form.cleaned_data['item_bought_price'] stock_level = form.cleaned_data['stock_level'] restock_level = form.cleaned_data['restock_level'] item = Item.objects.create( item_name=item_name, item_price=item_price, item_description=item_description, item_bought_price=item_bought_price, stock_level=stock_level, restock_level=restock_level, ) item.save() return redirect('items:item_list') else: messages.error(request, 'Invalid form.') return redirect('site_admin:add_item') else: form = ItemForm() return render(request, 'Admin/add_item.html', {'form':form,}) else: return HttpResponse('Whoopsie!') I have one more function, where when item is ordered, quantity of items bought is subtracted from stock_level, It works fine with Item instances created through /admin, but with item instances created through form, when … -
What are the Django requirements to become a full stack dev.
To fully use Django would I need to know: HTML CSS3 JS JSON if yes, what else would i need to be comfortable using to fully be a full stack web dev? Thank you. -
Django OAuth Toolkit giving me "Authentication credentials were not provided" error
I've been trying for a while to get django Oauth toolkit to work but no matter what I get a 401 error and when I check the details it's the error in the title. Even though I'm obviously passing credentials views.py: class PostCarFax(viewsets.ModelViewSet): #authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication, authentication.BaseAuthentication] permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = CarFax.objects.all() serializer_class = CarFaxSerializer serializers.py: class CarFaxSerializer(serializers.ModelSerializer): class Meta: model = CarFax fields = ('vin', 'structural_damage', 'total_loss', 'accident', 'airbags', 'odometer', 'recalls', 'last_updated', 'origin_country') def create(self, validated_data): return CarFax.objects.create(**validated_data) settings.py import os import django_heroku from django.conf import settings settings.configure() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ts_0a3(d9$$g4h&_w#k$op7a)lg3@vrk!^fs!m-zv=))rw$=xi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] '''import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django django.setup()''' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'oauth2_provider', 'rest_framework', 'rest_framework.authtoken', ] 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', 'oauth2_provider.middleware.OAuth2TokenMiddleware', ] ROOT_URLCONF = 'django_api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
How to add Tags in a django blog using taggit
am trying to add some tags in my post_list function i have installed taggit and tested it in shell it is working fine and am able to display the tags in the html template blog.html but the problem is that trying to add the url for a particular tag shows errors .NoReverseMatch at /blog/ Reverse for 'post_list' with arguments '('python',)' not found. 1 pattern(s) tried: ['blog\/$'] I have a blog category called python here are my works so far views.py def post_list(request,tag_slug=None): object_list=Post.objects.filter(status='Published').order_by("-created") recent_post=object_list[:6] categories = Category.objects.all().annotate(post_count=Count('post')) for category in categories: print(category.post_count) if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) page = request.GET.get('page', 1) paginator = Paginator(object_list, 3) try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context={ 'items':items, 'recent_post':recent_post, 'categories':categories, } return render(request,"blog.html",context) blog.html <div class="widget"> <h3 class="badge">TAGS</h3> <div class="tagcloud"> {% for obj in items %} {% for tag in obj.tags.all %} <a href="{% url 'post_list' tag.slug %} ">{{ tag.name }}</a> {% if not forloop.last %}, {% endif %} {% endfor %} {% endfor %} </div> </div> help please -
Token matching query does not exist
I am trying to set up a way to add friends on a social media type site, but something is wrong and I don't know what is going on. Here is my model: class Friend(models.Model): #static variables for friend_status attribute FORMER_FRIENDS = 0 FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) Here is my URL: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), Here is my class-based view: class AddFriend(APIView): def get(self, request, username): user = Token.objects.get(key='token string').user friend = User.objects.get(username=username) #check for friendship instance new_friend, created = Friend.get_or_create(friend_A=user, friend_B=friend) When I try to access the endpoint I get the following output: DoesNotExist at /friend_request/brian Token matching query does not exist. Setting up friend relationships is proving more difficult than I expected. Please advise. -
Python Django Multi Level Join Query
Task Details I am working on creating a custom API to fetch data from three tables, based on provided key info. Background To elaborate, I've three data tables - Client, Account and Client_accounts and their structure looks like this: Client ID (Integer) Primary Key display_name (varchar) Accounts ID (Integer) Primary Key nickname (varchar) Client_Accounts Client_ID (Integer) Foreign Key -> ID from client table Account_ID (Integer) Foreign Key -> ID from accounts table In intend to pass a client ID to my API and want to fetch all the accounts (and accounts names) owned by that client. The SQL query that I am trying to replicate looks like this: select cl.id as client_id, cl.display_name, ac.id as account_id, ac.nickname as account_name from datahub_clients cl join datahub_client_accounts cl_ac on cl.id=cl_ac.client_id join datahub_accounts ac on cl_ac.account_id=ac.id where cl.id=15 ; Done so far This is what I used to fetch the client's name API, by passing the client_id: ##### For endpoint - get_client_name @api_view(['GET', 'POST']) @permission_classes((AllowAny,)) def get_client_name(request): try: if request.method == 'GET': list_of_account_ids = Client_Accounts.objects.filter(client_id=request.GET['id']).values_list('account') needed_accounts = Accounts.objects.filter(id__in=list_of_account_ids).values('id','nickname') return Response({'requested client id':request.GET['id'],'identified client name': 'detailed info to go here'}, status=status.HTTP_200_OK) else: return Response({'status':'error','message': 'Facepalm moment!'}, status=status.HTTP_403_FORBIDDEN) Problem Statement 1) In the code above, I … -
Accessing a related object from a different database in Django
Consider the following two related models, User and Tier: class User(models.Model): tier = models.OneToOneField(Tier) class UserTier(models.Model): tier = models.IntegerField(related_name='tier') Suppose there are two databases, 'default' and 'replica', and we have an instance user of User. I assume that the default related field lookup, user.tier, would use Django's default router to look up the UserTier in the default database. One could do UserTier.objects.using('replicate').get(user=user) similar to https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset, but this seems inefficient as we are querying all UserTier objects instead of just looking up the related one-to-one field. Is there a way to do the related object lookup directly, something like (in pseudocode) user.tier(using='replica')? -
module path in uwsgi is one layer up - how to indicate that
My initial uwsgi.ini location looked like this parent |-uwsgi.ini |_main | |_wsgi.py |_scripts Since uwsgi.ini was right next to the main folder I had this parameter in my uwsgi.ini and it worked module=main.wsgi <---This works since it was next to main Now I just moved the uwsgi.ini file into the scripts folder so its no longer right next to the main folder that contains wsgi.py. Because of that I had to change the module parameter in the file. This is the new parameter module=../main.wsgi <----This does not work since its not next to main anymore - What do I do ? I think this is wrong as I am getting an error. I am not sure how to indicate the module path now that I moved the wsgi.ini into the scripts folder. Any suggestions ? -
Python loop interrupted by time.sleep
I am facing a weird issue in my python (django) app. I have implemented my method to change flags I have in firebase. But I wanted my method to wait for a few seconds before changing another flag. My method without the two time.sleep(10) lines works perfectly. But when I put them there for some reason it only iterates each loop one. This is my code: def gameController(session_id): db = firestore.client() round_col = db.collection(u'Session').document(session_id).collection(u'Rounds') round_docs = round_col.get() iCounter = 0 jCounter = 0 for i in round_docs: iCounter += 1 round_ref = round_col.document(i.id) question_col = round_ref.collection(u'Questions') question_doc = question_col.get() for j in question_doc: jCounter += 1 #time.sleep(10) question_ref = question_col.document(j.id) question_info = question_ref.get().to_dict() question_info['isDoneSubmitAnswer'] = True question_ref.set(question_info) #time.sleep(10) question_info = question_ref.get().to_dict() question_info['isDoneChooseAnswer'] = True question_ref.set(question_info) round_info = round_ref.get().to_dict() round_info['isDone'] = True round_ref.set(round_info) return (iCounter, jCounter) It really does not make sense to me. The method returns (1,1) if I uncommented both of time.sleep(10) lines. If I uncommented only one of them it returns (2,6). If I keep it as is it returns (3,9) which is the correct behavior. In this firebase session, I have 3 different Rounds and 3 different questions within each round. Thank you guys. -
How do I implement a U2F login process into Django?
I've been researching around on how to implement U2F hardware authentication into a Django application. The documentation for libraries such as a python-based Yubico one seem like they are missing some important information (located here) or I am misunderstanding something. According to this picture on their official documentation, you are supposed to follow the workflow where you first verify username and password then issue a challenge (a public key I think?) server-side. Next, you pass that challenge up to the u2f-api.js javascript library, client-side (documentation for javascript library here and here) where it invokes u2f.sign() or u2f.register() methods. After that, the client side handles the magic of inserting the hardware key and touching it then passes a response back down to the server. Where I am stumped is what python code do I need to call to actually create a challenge and/or register and store the device information ?? Any and all help is welcome to point me in the right direction. Please correct me if I am wrong about anything too. -
How to use one model as source for 'choices' in another model?
I have 3 models: User, UserProfile and Programme. User holds the names of all users; class User(AbstractUser): first_name = model.Charfield(...) last_name = model.Charfield(...) ... UserProfile contains the attributes associated with each user (e.g. sales manager(sm), program manager(pm), delivery manager(dm) etc. class UserProfile(model.Model): user = model.ForeignKey(User, on_delete...) sm = model.BooleanField(default = False, editable=True...) pm = model.BooleanField(default = False, editable=True...) dm = model.BooleanField(default = False, editable=True...) A User may have any combination of UserProfile attributes. For example: User-1: sm User-2: sm, pm User-3: dm User-4: sm, dm ... Every programme in Programme must have a user assigned for each of sm, pm, dm so my challenge is finding a way to generate a 'choices' list for each of sm, pm and dm limited to Users with the appropriate attribute. class Programme(model.Models): programme_name = models.Charfield(...) AND ESSENTIALLY: sm = only users with userprofile.sm = True pm = only users with userprofile.pm = True dm = only users with userprofile.dm = True I've tried adding a function to UserProfile then referencing it in Programme: UserProfile(model.Models): .... def get_pm(self): pm_list = [] pm = UserProfile.objects.filter(pm=True) for i in pm: pm_list.append(i.user.last_name) return pm_list and in Programme: Programme(model.Models): pm = models.Charfield(choices=UserProfile.get_pm, ... but this generates the error: … -
How to use SlugRelatedField for incoming request (deserialise) and full serialiser for response for related fields
My db model is of events and each event is connected to a venue. When I retrieve a list of events I use: venue = VenueSerializer(read_only=True) When I post to my drf endpoint I use: venue = serializers.SlugRelatedField( allow_null=True, queryset=Venue.objects.all(), required=False, slug_field='id') However this causes that in the response I recieve from the post request, the venue is serialised as a slug field. I want it to use the VenueSerialiser for the response. I came accross https://stackoverflow.com/a/49035208/5683904 but it only works on the Viewset itself. #serializer_class = EventSerializer read_serializer_class = EventSerializer create_serializer_class = EventCreateUpdateSerializer I need to build this functionality into the serialiser itself since it is shared with other components. -
Poor Performance for Form Rendering In Django 1.11
My site has a navbar with an advanced search widget (beside the search field), which renders on every page. For each request, a context_processor creates the form so it can be available on that page in the navbar. This form has about a dozen selects with a total of several hundred options. Most of those options are for the currency and country selects, along with about 80 other options. There is an even larger list for "stores" but it is loaded via AJAX so it should not be a factor here. Performance was fine on Django 1.8, but after upgrading to 1.11 I noticed with NewRelic that 200+ ms are now being used between the following: Render/django/forms/widgets/select_option.html Render/django/forms/widgets/select.html Render/django/forms/widgets/attrs.html This seems to be related to 1.11's change to Template-based Widget Rendering, however the only pages I could find talking about related problems were about Django Toolbar which I do not run in production. I am and already using the Cached Template Loader (which is now default), however I don't know if this helps here. I cannot easily cache this form because as you can see in the code, I set a number of defaults based on the request. Why is …