Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot route traffic with Minikube + ingress + Django
In my local development setup, I'm using Django as the webserver (a-la python manage.py runserver 8000) and I'm able to kubectl port-forward <django_pod> 8000 my traffic to my local dev machine so I can interact with my site by browsing to http://localhost:8000/whatever. I've configured my ALLOWED_HOSTS to include localhost to enable this. However, I'd like to avoid using port-forward and go the more proper route of running my traffic through the Kubernetes ingress controller and service. On the same Minikube cluster, I have ingress configured to point certain traffic urls to a very rudimentary nginx pod to confirm that my ingress+service+pod networking is working properly. All other urls should route to my Django app. In my ingress controller logs, I can see the traffic being sent to the service: 192.168.64.1 - [192.168.64.1] - - [22/Nov/2019:03:50:52 +0000] "GET /test HTTP/2.0" 502 565 "-" "browser" 24 0.002 [default-django-service-8000] [] 172.17.0.5:8000, 172.17.0.5:8000, 172.17.0.5:8000 0, 0, 0 0.000, 0.000, 0.000 502, 502, 502 aa2682896e4d7a2052617f7d12b1a02b When I look at the Django logs, I don't see any traffic hitting it. My ingress servicePort is 8000, the django-service port is 8000 (I've just let it default to ClusterIP), the pod's spec.containers.ports.containerPort is 8000, and the process has … -
upstream timed out (110: Connection timed out) while reading response header from upstream while running django application
I'm running django application using uwsgi and nginx using cronjob with command* * * * * /usr/local/bin/lockrun --lockfile /path/to/lock_file -- uwsgi --close-on-exec -s /path/to/socket_file --chdir /path/to/project/folder/ --pp .. -w project_name.wsgi -C666 -p 32 -H /path/to/virtualenv/ 1>> /path/to/success_log 2>> /path/to/error_logBut in nginx error log the above error is showing,how to fix this error can anybody help, due to this error the server is too slow and unable to work in screen??? -
Django auto-populating form field from API call
I am trying to auto-populate one field of a Django form based on the query response of an entry into another field. I would like to do so before the form is submitted, displaying the autopopulated value in the field and maintain the user's ability to edit. (Example, I type 'a handful of bananas' into the name field, when that field blurs it queries the api and fills the carbs field with the # of carbs a handful of bananas has) Right now I have the ajax function to query: $('#recipe-query').on('blur', function(event){ event.preventDefault(); console.log("blur") query_macros(); }); function query_macros(){ var dataStr = "APIKEYREDACTED" var ingredParam = encodeURI($('#recipe-query').val()) dataStr = dataStr + ingredParam if($('#recipe-query').val() && $('#should-query').val()){ $.ajax({ url: "https://api.edamam.com/api/nutrition-data", data: dataStr, type: "GET", dataType: "json", success : function(json){ console.log(json); console.log(json.totalNutrients.CHOCDF.quantity) $('#carbs-query').value = json.totalNutrients.CHOCDF.quantity; }, error : function(xhr, errmsg, err){ console.log(xhr.status + ": " + xhr.responseText); } }); } } this is the form class NutritionForm(forms.ModelForm): class Meta: model = Nutrition fields = ('food_name', 'autofill_macros', 'grams_of_fat', 'grams_of_protein', 'grams_of_carbs', 'date') widgets = { 'food_name': forms.TextInput(attrs={ 'id': 'recipe-query' }), 'autofill_macros': forms.CheckboxInput(attrs={ 'id': 'should-query' }), 'grams_of_fat': forms.TextInput(attrs={ 'id': 'fat-query' }), 'grams_of_protein': forms.TextInput(attrs={ 'id': 'protein-query' }), 'grams_of_carbs': forms.TextInput(attrs={ 'id': 'carbs-query' }) } and model class Nutrition(models.Model): food_name … -
Passenger Python web application could not be started ImportError
Running a python application on a shared server encountering the following error: Web application could not be started An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger. Please read this article for more information about this problem. Raw process output: Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 26, in import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno File "/usr/lib/python2.7/logging/init.py", line 26, in import sys, os, time, cStringIO, traceback, warnings, weakref, collections File "/usr/lib/python2.7/weakref.py", line 14, in from _weakref import ( ImportError: cannot import name _remove_dead_weakref Error ID 04438b96 Application root /home/groups/group1/2018/production Environment (value of RAILS_ENV, RACK_ENV, WSGI_ENV, NODE_ENV and PASSENGER_APP_ENV) development Server runs perfectly using runserver (python manage.py runserver) but seems to break when attempting to start with Passenger. Any help or pointers in the right direction would be extremely appreciated. -
Extend a model using OneToOneField
I'm trying to extend django-taggit Tag model to have an added_by (ForeignKey to User) field on it, so I can query all tags added by a particular user. So, I have created an app and in models.py there I have created another model, called MyTag and I have a OneToOneField to Tag on it: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from taggit.models import Tag class MyTag(models.Model): tag = models.OneToOneField(Tag, on_delete=models.CASCADE) added_by = models.ForeignKey(User, on_delete=models.CASCADE) @receiver(post_save, sender=Tag) def create_tag(sender, instance, created, **kwargs): if created: MyTag.objects.create(tag=instance, added_by=???) @receiver(post_save, sender=Tag) def save_tag(sender, instance, **kwargs): instance.mytag.save() The issue is, I can't access request.user from inside models.py. How do I overcome the issue, i.e. how do I properly extend django-taggit's Tag model to have added_by field on it? -
Hosting Django Rest framework on its own server
So I have an angular front end with an Django rest framework backend that's hosted on a single ubuntu 18.04 VPS box running apache. The front end is hosted on port 80 and the backend is at port 8000 and we noticed it seems like a lot of networks block port 8000. So what happens is if I logon on a public wifi you can see the front end but you can't access the backend. I need some guidance on how to make this work. Right now it's setup like so Api requests are: http://myapp.com:8000 In the future all API quests should be: http://myapp.com/api or maybe even a separate server that's http://api.myapp.com I'm asking for some guidance on this issue. Is there anyway to just make apache think that all requests are on port 80/443 and i don't need the 8000 anymore? and for a small app is that an okay practice? OR should I just run the backend on a separate server and if so how do I set that up? all guides seem to point to putting that on 8000. Any links and guidance on this issue would be appreciated. -
Django Categories and Breadcrumbs Issues
I am working on the categorization application in this link. Everything works normally on the admin side. However, I could not show the categories and breadcrumbs on front site. I'd appreciate it if you could help me. https://djangopy.org/package-of-week/categories-with-django-mptt/ -
How to do backward relationships lookup for all model objects in Django?
I want to have a list view of all products from Product model with their own image URLs from ProductImage model. Each product may have multiple images. models.py: class Product(models.Model): product_id = models.CharField(max_length=6) material = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(verbose_name='Active') def __str__(self): return self.name clsas ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) url = models.URLField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(verbose_name='Active') def __str__(self): return self.url I've been trying to implement the queries from this Django documentation. But the example specifically target an object by its id. How to do the same thing with all objects? b = Blog.objects.get(id=1) b.entry_set.all() # Returns all Entry objects related to Blog. Is it possible to do it without changing the Foreign Key relation into productimage = models.ManyToManyField(ProductImage) in Product model ? My current attempt on views.py: def product_list_view(request): products = Product.objects.all() images = products.productimage_set.all() context = { 'product_list': products, 'product_image_list': images } return render(request, 'product_visualizers/product_list.html', context) product_list.html template: {% for product in product_list %} <li> <p> {{ product.product_id }}: </p> {{ product.name }} - {{ product.material }} - {{ product.created_at }} - {{ product.enabled }} <p> {{ product_image_list.url }} </p> </li> {% endfor %} The error I got: AttributeError … -
Multi-tenant redirect to sub-domain based on User Id
I am implementing Django-tenant-schemas on a SaaS website I am building and am wondering how to allow users to login at the main site and be redirected to the tenant specific subdomain their user account exists at. e.g. User goes to www.mysite.com and tries to log in - because, after all, this is the site they expect to log in at - but their user account is actually associated with www.tenant1.mysite.com. How do I go about redirecting the user automatically when they attempt to log in at the main domain? I assume there is something very simple that I am not seeing. Thanks in advance! Note: I want the user to log in to their sub-domain and only their sub-domain, not as a user across all domains (which is what SESSION_COOKIE_DOMAIN does I believe). -
Why does Django tell me that a field clashes with a field in the base class when that field only exists in the subclass?
I am attempting to define some models that inherit from a base class with timestamps, but I'm getting the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/matt/Repositories/mtm/env/lib/python3.5/site-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: events.Event.location: (models.E006) The field 'location' clashes with the field 'location' from model 'home.timestampedmodel'. System check identified 1 issue (0 silenced). Here are my models: home/models.py from django.db import models class TimestampedModel(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) events/models.py from django.db import models from home.models import TimestampedModel class Location(TimestampedModel): name = models.CharField(max_length=200) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200) city = models.CharField(max_length=80, default='Chicago') state = models.CharField(max_length=2, default='IL') class Event(TimestampedModel): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) date_start = models.DateTimeField() date_end = models.DateTimeField(null=True, blank=True) location = models.ForeignKey(Location, on_delete=models.CASCADE) The code runs successfully when I have Location and Event inherit from models.Model, but this isn't how I want my code to be structured. events/models.py (works, but not desirable) from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address1 … -
How to use MySQL JSON type model in Django pymysql?
We are doing web development for simple internal use. (I'm a beginner developer.) I am utilizing Django 2.1, mysql 8.0, python 3.7, pymysql. I want to make a model using JSON type in MySQL. Is there a way? -
Django Users, groups and organizations for multi vendor app, how to?
I'm building a marketplace that allows users to sign up with a company or organization, add or invite other users to that company and manage those users. All users can create listings (products or service). Currently I have an abstract user model and a company model with a foreign key to the user, which works well if a company only has one user, it looks like this: class User(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=15) email = models.EmailField(unique=True) objects = UserManager() def __str__(self): return self.first_name class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100, unique=True) company_address = models.CharField(max_length=100, unique=True) company_website = models.URLField() company_verified = models.BooleanField(default=False) def __str__(self): return self.company_name What would be the best way to accomplish this, without giving the users permissions to the admin site? I've looked at using django-organizations, but the documentation seems poor and they don't support postgresql. -
Populate added_by field from CreateView
I have extended django-taggit TagBase model to include an added_by field as a ForeignKey to User: class TagBase(models.Model): name = models.CharField(verbose_name=_("Name"), unique=True, max_length=100) slug = models.SlugField(verbose_name=_("Slug"), unique=True, max_length=100) added_by = models.ForeignKey(User, on_delete=models.CASCADE) Everything works great, however I'm having an issue with populating that field from my CreateView. This is what I have tried: class NoteCreateView(LoginRequiredMixin, CreateView): model = Note fields = [ 'title', 'description', 'notebook', 'tags' ] def form_valid(self, form): form.instance.added_by = self.request.user form.instance.save() for tag in form.instance.tags.all(): tag.added_by = self.request.user return super().form_valid(form) but I'm getting an error: IntegrityError at /notes/1/create/ NOT NULL constraint failed: taggit_tag.added_by_id How do I properly autopopulate added_by field on my tag instances? -
How to properly fork django-taggit?
I want to make a small tweak to django-taggit - I want to add an added_by field on the Tag model as a ForeignKey to User, so I can list all tags added by a particular user. So, I cloned the repo into the folder where all the apps are and made the changes to the code, however I'm getting an error: /home/alex/.repos/codelib/github/hawk/src/hawk/hawk/settings.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'taggit' ...as a fix, I tried to … -
Django Stripe Fake Card Causes TemplateDoesNotExist Error
When a person types in a fake credit card into my Stripe payment form, I get an error page saying "TemplateDoesNotExist at /memberships/payment/ followed by membership/membership_payment.html". The following lines of code get executed: views.py: https://dpaste.de/8EUX#L77,78,79,80,81,82,83,84,85 html files: https://dpaste.de/2Y37 I need a way to not show that error page and redirect the user back to /memberships/ and display a card decline message instead. However, if a user types in a valid card, that redirect is correct. Otherwise maybe I need a way to validate the card is able to be charged to see if it is a real one before being able to submit the form. Traceback has been included in the dpaste link. I am using this github project as a baseline so all files are mostly the same (except for my dpaste code updates): https://github.com/danialbagheri/video-membership Any help would be greatly appreciated. -
Customers app and model in their own app away from staff users in django
i want to create app for my own customers and create custom user model for him i searched for make this and i reached an AbstractBaseUser,BaseUserManager class them contain all kind of main website users admin (staff users) with customers users in one model in customers app i want make an customers app and customers model on their own and staff users in their own app -
'NoneType' object has no attribute 'set_password' in django registration and login
I am entirely new to django. Trying to create login and registration system. User registers successfully, saved in database but I get this error after registering. "'NoneType' object has no attribute 'set_password'" views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) form.save() username = form.cleaned_data.get('username') fullname = form.cleaned_data.get('fullname') password = form.cleaned_data.get('password1') user = authenticate(request, username=username, password=password) messages.success(request, f'Welcome to blaza {fullname}') user.set_password(password) user.save() if user is not None: login(request, user) return redirect(reverse('home')) else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) When I remove "user.set_password" it works but registered users can not login with their credentials even when the username and password is correct, It says incorrect username and password. (only admin account, superuser can login). So I researched and had to add the user.set_password and user = form.save (I get warning that local variable user value is not used) forms.py class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50) fullname = forms.CharField(max_length=200) email = forms.EmailField(max_length=200) password2 = None class Meta: model = User fields = ('username', 'fullname', 'email', 'password1') def clean_password1(self): password1 = self.cleaned_data.get('password1') try: password_validation.validate_password(password1, self.instance) except forms.ValidationError as error: self.add_error('password1', error) return password1 Models.py class CustomUser(AbstractUser): class Meta: db_table = 'users' fullname = models.CharField(max_length=200) email … -
ml model on django and html
I have index.html <p>input an image</p> <p> <form> <input type="file" name="pic" accept="image/.jpg" onchange="loadFile(event)"></input> <img id="output"/> <script> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> </form> </p> <p> <form> <input type="submit" value="result"></input> </form> </p> views.py def test(request): if request.POST: d = request.POST.dict() img = d.get("pic") a=image_array(img) # convert image to array use to test model r=model(a) # return render(request, "./index.html",r) else: return render(request, "./index.html") how can I show the result of predict below the test button? -
Having both username and email but using email to authenticate users in django-rest-auth
With most tutorials, I see people use either email or username. I want to have both fields but using only the email to authenticate users with Django-rest-auth, as the email will be verified and is very important. but the username also has its importance in my app. models.py class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) fullname = fullname user = self.model( email=email, fullname=fullname, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, fullname, password, **extra_fields): return self._create_user(email, fullname, password, False, False, **extra_fields) def create_superuser(self, email, fullname, password, **extra_fields): user=self._create_user(email, fullname, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() def __str__(self): return self.email serializers.py class CustomRegisterSerializer(RegisterSerializer): ''' a custom serializer that overides the default rest-auth, and for the user to register himself ''' username = None email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) fullname = serializers.CharField(required=True) def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return … -
login isn't calling inactive json response
I am writting a signup based confirmation ,but after it log in it works, however it doesnt login at all . the issue isnt raising return JsonResponse({"message": "error"}) instead of return JsonResponse({"message": "inactive"}) , So I can response that over ajax, and tell the user in a fancy way to activate it def post(self, request): email= request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: if user.is_active: #request.session.set_expiry(60) login(request, user) return JsonResponse({'message': 'success'}) else: return JsonResponse({"message": "inactive"}) else: return JsonResponse({"message": "error"}) signup def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): with transaction.atomic(): user = form.save(commit=False) user.is_active = False user.save() email_subject = 'Next Step: Activate Your Account' current_site = get_current_site(request) html_message = render_to_string('email/activate.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail = EmailMessage(email_subject, html_message, to=[form.cleaned_data.get('email')]) mail.content_subtype = "html" mail.send() return JsonResponse({'message': 'success'}) else: return JsonResponse({"message":form.errors}) -
defautl image in the field "ImageField" - Django
I try to put an image in an ImageField by default. But I can't solve the problem. My first attempt at solution was the following: from django.contrib.staticfiles import finders result = finders.find('img/image.png') models.ImageField(upload_to = user_model_custom_upload, default = result) My second attempt at solution was the following: from django.conf import settings import os DEFAULT_AVATAR_PATH = os.path.join(settings.MEDIA_ROOT, 'images/no-avatar.png') models.ImageField(upload_to = user_model_custom_upload, default = DEFAULT_AVATAR_PATH) neither solution worked But something curious happens with the second method, is that at the time that Django searches for the image, the image path for Django is as follows: Not Found: /media/home/lcteen/Documents/Programming/Frameworks/Django/ibme_project/media/images/no-avatar.png I don't know what is currently happening, it's like the structure of my directories is in the media folder or something ... but my media folder doesn't change at all. Any solution? -
HTML5 video elements loading time
I just want to figure out why my website is serving video files without coherence. First of all, I have created my website on ODROID-XU4 and OS is Ubuntu. Also, using Django and Apache2 as Framework Anyway, here is my problem. Videos won’t start instantly when I click the play button But, funny thing is some video files with big size do play instantly. For example, when I upload 3GB of video(mkv) and click play button, it plays instantly. However, another video file which is only 1.8GB uploaded won’t be played before fully loaded. Please, I am waiting for answer from someone who had similar experience -
How do I create a Django admin section for managing content on an individual page, such as homepage?
I would like to allow an admin to edit content sections on a homepage, about page, or contact page. A content section with a changeable background image, or a content section with changeable text. Is there a built-in Django package that addresses this? If not, would you recommend another third-party Django integration? I have searched using similar questions and have found that there are very few related answers. -
Display Foreign Key linked models in Django rest framework
I have three models I would like to display with in a treeview Event Market Runner Runner Runner Market Runner Runner Event can have multiple markets and markets can have multiple runners. I would like to be able to get fetch these models from one api request to view and delete old events if necessary. I've tried to create a combined serialiser but I get an error saying url name not valid with Runner. I don't think it's right referencing Runner model in the combined serializer as the Runner url has changed to the same name as combined. { "events": "http://localhost:8000/api/events/", "markets": "http://localhost:8000/api/markets/", "runners": "http://localhost:8000/api/combined/", "balance": "http://localhost:8000/api/balance/", "combined": "http://localhost:8000/api/combined/" } What is the best way to go about this? class Event(models.Model): sport_id = models.CharField(max_length=15) event_id = models.BigIntegerField(unique=True) event_name = models.CharField(max_length=200) start_time = models.DateTimeField(null=True) status = models.CharField(max_length=13) class Market(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) market_id = models.BigIntegerField(unique=True) market_name = models.CharField(max_length=35) status = models.CharField(max_length=10) volume = models.FloatField(null=True) class Runner(models.Model): event = models.ForeignKey(Event, null=True, default=None, on_delete=models.CASCADE) market = models.ForeignKey(Market, null=True, default=None, on_delete=models.CASCADE) runner_id = models.BigIntegerField(unique=True) name = models.CharField(max_length=500) back_odds = models.FloatField(null=True) lay_odds = models.FloatField(null=True) class CombinedSerializer(serializers.ModelSerializer): event = EventSerializer() market = MarketSerializer() class Meta: model = Runner fields = ('id','runner_name','runner_id', 'name', 'event' ,'market') class … -
Django serializer show all fields for retrieve but hide fields from list
I have a Product model which I'm using to retrieve all products and single products. I need to have all columns returned when I query a single record but only some columns returned when I query all. # models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.CharField(max_length=150, blank=True, null=True) image_2 = models.CharField(max_length=150, blank=True, null=True) thumbnail = models.CharField(max_length=150, blank=True, null=True) display = models.SmallIntegerField() class Meta: managed = False db_table = 'product' # serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('product_id', 'name', 'description', 'price', 'discounted_price', 'image', 'thumbnail') # products.py import logging from django.db.models import F from django.contrib.auth.models import AnonymousUser from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.filters import SearchFilter from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from api import errors from api.models import Category, Product, Review, ProductCategory from api.serializers import ProductSerializer, ReviewSerializer logger = logging.getLogger(__name__) class ProductSetPagination(PageNumberPagination): page_size = 20 page_query_description = 'Inform the page. Starting with 1. Default: 1' page_size_query_param = 'limit' page_size_query_description = 'Limit per page, Default: 20.' max_page_size = 200 class ProductViewSet(viewsets.ReadOnlyModelViewSet): """ list: Return a list of products retrieve: Return …