Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model ImageField default value
I made a model which has an image field and it is allowed to be blank. How can I have a default image for the model when no image is set for it? class Product(models.Model): picture = models.ImageField(blank=True) -
how to access parent object from admin tabularinline in Django admin
I need to access the parent object of an item to be able to filter the dropdown Fk fields inside the inline object based on it is a parent. here is my code : models.py class Match(models.Model): date_time = models.DateTimeField() home_team = models.ForeignKey('teams.Team',related_name="home_team_team",on_delete=models.PROTECT) away_team = models.ForeignKey('teams.Team',related_name="away_team_team",on_delete=models.PROTECT) league = models.ForeignKey(League,on_delete=models.CASCADE,null=True) class Goal(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) date_time = models.DateTimeField() team = models.ForeignKey("teams.Team",on_delete=models.PROTECT,null=True,blank=True) player = models.ForeignKey('players.PlayerProfile',related_name="goal_maker",on_delete=models.PROTECT,null=True,blank=True) assistant = models.ForeignKey('players.PlayerProfile',related_name="goal_assist",on_delete=models.PROTECT,null=True,blank=True) admin.py #this is my inline class class GoalInline(nested_admin.NestedTabularInline): model = Goal fields = ['date_time','team','player','assistant'] extra = 1 show_change_link = True def formfield_for_foreignkey(self, db_field, request, **kwargs): print(f"data {self.model}") if db_field.name == "team": kwargs["queryset"] = Team.objects.filter() #i need to perform filtering here return super().formfield_for_foreignkey(db_field, request, **kwargs) #my parent class @admin.register(Match) class MatchAdmin(nested_admin.NestedModelAdmin): # form = LeagueForm readonly_fields = ['date_time','home_team','away_team','league'] list_display = ["league","home_team","away_team",] search_fields=["home_team","away_team","league"] list_filter=['league','date_time',"home_team","away_team"] inlines=[GoalInline] def get_inlines(self, request, obj=None): if obj: return [GoalInline] else: return [] -
django-tinymce doesn't show up in admin
I can't get the django-tinymce module gui to show up in the admin of my django project. Here's settings.py (tinymce settings are at the end): import os from pathlib import Path # 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/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'notices.apps.NoticesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'imagekit', 'leaflet', 'nested_admin', 'tinymce' ] 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', ] ROOT_URLCONF = 'orag.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'orag.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'xxxxxx', 'NAME': 'xxxxxx', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxxx', 'HOST': 'localhost' } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'fr-FR' TIME_ZONE = … -
I want to filter public feeds by the multiple tags (saved in user's preferences)
I have a list of tags (preferenced by the USER). tags_list = ["animals", "city", "chemicals", "Wealth Management", "Crypto", "Stocks"] and a Feed model and Its tags class FeedModel(models.Model): entity_id = models.BigAutoField(primary_key=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=250) image_url = models.TextField(null=True) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # mostly 5 tags per feed class NewsTags(models.Model): id = models.BigAutoField(primary_key=True) feed = models.ForeignKey(FeedModel, on_delete=models.CASCADE, related_name='tags') tag = models.CharField(max_length=100) # animals, city, finance,... I want to filter feeds by the given tags and order by created_at. so that My requirement is filtered feed must be on the top and the remaining feed below the filtered feed also with order_by created_at. q = Q() for tag in tags_list: q |= Q(tags__tag__icontains=tag) q1 = Q(*remaining feed apart from filtered by the tags*) _feeds = FeedModel.objects.filter(q|q1).order_by("created_at") How can I get feed data filtered by tags like Facebook, Instagram feed by the user behavior,... Please answer, how can I do it best? -
How to customize django admin site like this?
Hello, I would like to know how to proceed to have a customization like this with django Anyone know what should i do? -
serialize dictionary with dynamic key
I would like to create a django rest framework serializer, in order to serialize this dict: "series": { "real": "Real", "forecast": "Forecast", "upper_ci": "Upper CI", "lower_ci": "Lower CI" } The problems is that real, forecast, upper_ci, lower_ci are all dynamic keys, and there might be other different keys. -
Implementing a Python file in Django
I'm pretty new to Django and html. I want to import the following code in Django: import csv with open('FILE.csv', newline='') as csvfile: CSVFILE = list(csv.reader(csvfile)) df = pd.DataFrame(CSVFILE, columns= ['A','B','C','D']) while 1>0: select_color = df.loc[df['A'] == input()] print (select_color) What I want to achieve, is a webpage with a form, where you can fill in "A", which would thereafter display 'A','B','C','D'. What is the best way to treat this? -
Associating user id to courses that the user create
My django project basically allows users to create its own courses. So, I am trying to associate a user id to the courses that the user created so that it will display only the courses that the user has created when the user wanted to view all the courses that he/she has created. However, it returns an error saying "Cannot assign "1": "Course.user_id_id" must be a "User" instance.". I have been trying to find the solution for days & could not figure out. models.py class Users(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic= models.ImageField(upload_to='media/profile_pic',null=True,blank=True) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20,null=False) Country = models.CharField(max_length=20,null=False, blank=True) Company = models.CharField(max_length=20,null=False, blank=True) City = models.CharField(max_length=20,null=False, blank=True) State = models.CharField(max_length=20,null=False, blank=True) Zip_Code = models.IntegerField(blank=True, default="1") Telephone = models.IntegerField(blank=True, default="1") Extension = models.CharField(max_length=20,null=False, blank=True) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def get_id(self): return self.user.id def __str__(self): return self.user.first_name class Course(models.Model): CATEGORY = ( ('IT & Software', 'IT & Software'), ('Mathematics', 'Mathematics'), ('Science', 'Science'), ('English', 'English'), ('Bahasa Melayu', 'Bahasa Melayu'), ) LEVEL = ( ('Easy', 'Easy'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced'), ) LANGUAGE = ( ('English', 'English'), ('Bahasa Malaysia', 'Bahasa Malaysia'), ('Chineese', 'Chineese'), ) CERTIFICATE = ( ('Yes', 'Yes'), ('No', 'No'), ) user_id_id = models.ForeignKey(User, on_delete = models.CASCADE) media = models.ImageField(upload_to = … -
Django Factory Boy object does not exist
I have an issue regarding factory boy using in the testing of my Lets assume I have this three models: Class Company(models.Model): name = str Class Domain(models.Model): company = ForeignKey(ref=Company) name = str created_at = datetime Class Record(models.Model): domain = ForeignKey(ref=Domain) name = str created_at = datetime CompanyFactory(factory.django.DjangoModelFactory): name = str DomainFactory(factory.django.DjangoModelFactory): company = factory.SubFactory(CompanyFactory) name = str created_at = datetime RecordFactory(factory.django.DjangoModelFactory): domain = factory.SubFactory(DomainFactory) name = str created_at = datetime Having this, when I'm testing the Record views, at the begginning of every view I check that the Domain object is, in fact, related to the Company object such as: try: domain = Domain.objects.get(domain=domain_id, company__id=company_id) except ObjectDoesNotExist: return Response( data={"message": "Domain isn't related to the company provided."}, status=status.HTTP_403_FORBIDDEN ) But this code always returns an ObjectDoesNotExist exception when I make the testing with pytest+factory-boy but when I do manual testing runs fine. Have you experienced something similar? What I'm missing here? Thanks in advance. -
Update plotly graph and text when button is clicked in django
I want to implement a graph manipulation using django. Specifically, I want to be able to update the graph when the update button is clicked, and display the current update count. The following is a simple view of the problem. Thank you. here is my source code If there is any missing information, please point it out. index.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- plotly JS Files --> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' /> </head> <body> <div id="update-num">0 update</div> <button type="submit" id="upadate-bt">update</button> <div class="graph" id="scatter-graph">{{ graph| safe }}</div> </body> </html> graphdata.py import numpy as np import plotly.graph_objects as go np.random.seed(2) N = 10 def get_graphdata(): x = np.random.rand(N) y = np.random.rand(N) return x, y def get_scatter_figure(): print('create figure') x, y = get_graphdata() fig = go.Figure() trace = go.Scatter(x=x, y=y, mode='markers') fig.add_trace(trace) fig.update_layout(title='graph title', width=500, height=500) fig.update_xaxes(title='x') fig.update_yaxes(title='y') trace.on_click(show_point) return fig def show_point(trace, points, selector): print('cliked point') views.py from xml.etree.ElementInclude import include from django.shortcuts import render from . import graphdata def index(request): fig = graphdata.get_scatter_figure() plot_fig = fig.to_html(fig, include_plotlyjs=False) return render(request, 'graph/index.html', {'graph':plot_fig}) -
How to Fetch and Publish the latest data and list data in django
I am currently working on django , Need some help how to achive my below goal I need to publish the latest data and list data in a web app . Below is the set of steps i followed Created the Model.py import datetime from statistics import mode from django.db import models Create your models here. class documents(models.Model): author= models.CharField(max_length=30) title=models.CharField(max_length=50) description=models.TextField() creation_date=models.DateTimeField() update_date=models.DateTimeField() View.py from django.shortcuts import render from django.views.generic.list import ListView from .models import documents # Create your views here. class documentlist(ListView): template_name='app/document_list.html' model=documents context_object_name='document' HTML snippet {% extends 'base.html' %} {% block title %} MY HOMEPAGE {% endblock %} {% block css %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> {% endblock %} {% block content %} <nav class=" navbar navbar-dark bg-primary"> <a class="navbar-brand mb-0 h1" href="#">MEDICARE</a> </nav> {% for d in document %} <td>{{d.title}}</td> {% endfor %} {% endblock %} How can we render both latest data and list of data from a model class in django?I am clear about rendering the list data using listview . can someone help in understanding how to display the latest data from the list to the listview.html Thanks,Sid -
How to create multiple pages if there were too many for one page?
I'm working on a django project trying to create a forum. Now when a certain number of objects (thread-previews) is reached on one page, I want a second (and then third page etc) page created and some of these objects should go to these next pages (page 2, then page 3 etc.) and the url for the second page should be something like "mysite.com/fourum/topic/2" and so on. And then there have to be some buttons to navigate to page 2, page 3 etc. This would be relevant code: gaming.html {% extends "forum/index.html" %} {% load static %} {% block title %} Gaming {% endblock %} {% block content %} <div class="main-container"> <h1 class="heading">Forum: Gaming</h1> {% for obj in object %} <div class="username">{{obj.username}}</div> <div class="date">{{obj.date}}</div> <div class="topic">{{obj.topic}}</div> <div class="title"><a class="link" href="{{obj.slug_titel}}">{{obj.title}}</a></div> <div class="content">{{obj.content}}</div> {% endfor %} </div> {% endblock %} views.py def gaming(request): obj = Threads.objects.filter(topic="gaming") context = { "object": obj, } return render(request, "forum/gaming.html", context) -
AssertionError: Class RegisterSerializer missing "Meta" attribute
I am getting this error "AssertionError: Class RegisterSerializer missing "Meta" attribute" when using Django Rest API. I did make all migrations but can't figure out how to fix this error. The /register part of this application is where I am getting the error. serializers.py from rest_framework import serializers from rest_framework.validators import UniqueValidator from rest_framework_jwt.serializers import User from .models import Movie class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('pk', 'name', 'description', 'year', 'rating') class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, style={'input_type': 'password'}, validators=[validate_password]) password2 = serializers.CharField(write_only=True, style={'input_type': 'password'}, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name']) user.set_password(validated_data['password']) user.save() return user urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from rest_framework_jwt.views import obtain_jwt_token from api import views from api.views import RegisterView urlpatterns = [ path('admin/', admin.site.urls), path('auth/', obtain_jwt_token), path('', views.movie_list), url(r'^api/movies/$', views.movie_list), url(r'^api/movies/(?P<pk>[0-9]+)$', views.getMovie), path('register/', RegisterView.as_view(), name='auth_register'), ] models.py from django.db import models from django.utils import timezone # Create … -
AttributeError at /Addarticle/ 'bool' object has no attribute '_committed'
views.py from django.views.generic.edit import CreateView,UpdateView class ArticleCreatViews(CreateView): model = Article template_name = 'addpost.html' fields = '__all__'**strong text** urls.py from . import views path('Addarticle/', views.ArticleCreatViews.as_view(), name="add_post"), Model.py from django.db import models from django.urls import reverse from django.utils.text import slugify # Create your models here. class Article(models.Model): Title = models.CharField(max_length = 150) Article = models.TextField() slug = models.SlugField(unique=True,null=True) feature_img = models.ImageField(upload_to="images",default=True) Published_date = models.DateField(auto_now=True, auto_now_add=False) def __str__(self): return self.Title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('home', args=(str(self.id))) I am facing this AttributeError at /Addarticle/ 'bool' object has no attribute '_committed' How can I resolve this error -
I am not able to migrate mysql database
I connected two databases in my project PostgreSQL and MySQL. In MySQL, I have my all models in the models folder. So I want to migrate them that I can see tables in the MySQL database and put some data in it. When I run the migrate first then there is the table name called django_migrations is created. And whenever check my databases using MySQL Command Line then this is the only table I see. I don't know why I am not able to see my other tables. I want to know what am I doing wrong that my PMS database is not migrating. When I run python manage.py makemigrations pms then this is showing: Migrations for 'pms': pms\migrations\0001_initial.py - Create model Assignment - Create model BankAccount - Create model City - Create model Country - Create model House - Create model HouseOffering - Create model HouseOwnership - Create model Invoice - Create model InvoiceItem - Create model InvoiceParticipation - Create model InvoicePaymentParticipation - Create model Lease - Create model Locality - Create model Payment - Create model PaymentAdjustment - Create model PaymentBill - Create model PmsSubscription - Create model Society - Create model TenantRentPaymentBill - Create model User And … -
Django: How i can delete the white space between the background image and the origin page also Page number appear (Page undefined of undefined)
Am still learning and I need some help please, I have searched and try much solutions but they don't work with me, I want to set a background image and page number in the footer(I Have use wkhtml2pdf library): Here it's the code <!doctype html> <html lang="en"> <head> <style type="text/css"> body{ background-image: url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/...'); margin:0px; background-size: cover; background-position: left top; padding-top:0px; max-height: max-content; } #divb { font-size: 12px; font-family: Arial; } div.footer { display: block; text-align: center; position: running(footer); @page { @bottom-center { content: element(footer) } } } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body style="border:0; margin: 0;"> <div id="divb"> <p><strong>Materials :</strong> {{ materiel }}</p> .........(the rest of calling the data) </div> <div class='footer'> Page <span id='page'></span> of <span id='topage'></span> <script> var vars={}; var x=window.location.search.substring(1).split('&'); for (var i in x) { var z=x[i].split('=',2); vars[z[0]] = unescape(z[1]); } document.getElementById('page').innerHTML = vars.page; document.getElementById('topage').innerHTML = vars.topage; </script> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> <script> window.load = function() { window.status = 'render-pdf'; }; </script> </body> </html> and here it's the result : the was a white space between the background image and the origin page , also the number of page appear to me (Page undefined of undefined), How i can adjust the background-image … -
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: no such file or directory: unknown
Hope you all are well. I want to run my seed.sh file in docker, I am using windows operating system. The file is in this path encast/scripts/docker/backdoor/seed.sh I am using this command docker exec -it encast-api ../scripts/docker/backdoor/seed.sh and I am getting this error PS C:\Users\Lenovo\> docker exec -it api ../scripts/docker/backdoor//seed.sh OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: no such file or directory: unknown -
which is the file word referring to here in this code
Here i have file in request.data['file'] and self.request.data.get('file') is this file referring to FileField in the model i need to upload file_2 as well how can i implement the code models.py: class FileUpload(models.Model): """Represents file upload model class.""" owner = models.CharField(max_length=250) file = models.FileField(upload_to='csv_uploads/%y/%m') created = models.DateTimeField(auto_now_add=True) file_2 = model.Filefield(upload_to='csv_uploads/%y) def __str__(self): """Return file name.""" return self.file.name views.py class FileUploadView(APIView): permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser, FormParser,) def post(self, request, *args, **kwargs): request.data['owner'] = request.user.id file_serializer = FileSerializer(data=request.data) if request.data['file'] is None: return Response({"error": "No File Found"}, status=status.HTTP_400_BAD_REQUEST if file_serializer.is_valid(): data = self.request.data.get('file') -
Only the First Button works in Django loop
The div only appears if the first button is clicked. Its works as i wanted but only for the first button in loop. When i manually put display = "block" it appears though on bith loop. What i want is to toggle the class "bg-model" by clicking on the class "editTime". Any help would be appreciated. Thanks in advance... HTML <h4>Appointments</h4> {% if upcomming_appointments %} {% for d in upcomming_appointments %} <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <h6 class="mb-0"> <ion-icon name="medkit"></ion-icon> Appointment with <strong>{{d.PatientName}}</strong><a class="btn btn-info " id="sessionBtn" href="{% url 'medicalReport' d.id %}">Start Session</a> </h6> <span class="text-secondary"> Date: <strong>{{d.appoitmentDate}}</strong> <br> Time: <strong>{{d.appoitmentTime}}</strong><br> Symptoms: <strong>{{d.symptoms}}</strong><br> Comment: <strong>{{d.Comments}}</strong><br> </span> <a id = "changeTime" class="editTime">Change time</a> <a class="btn btn-info " id="logoutBtn" href="{% url 'delete_appointment' d.id %}" onclick="return confirm('Are you sure you want to cancel this appointment? This action is irreversible.')">Cancel Appoitment</a> <div class="bg-modal"> <div class="modal-contents"> <div class="close">+</div> <form method="POST"> <h5>Change Appointment Time</h5> {{d.id}} <input type="hidden" name="SessionID" value="{{d.id}}"> <input type="time" id="timeChange" class="input" placeholder="Time"> <button type="submit" class="loginBtn">Submit</button> </form> </div> </div> </li> JS document.querySelector('.editTime').addEventListener("click", function() { document.querySelector('.bg-modal').style.display = "flex"; }); document.querySelector('.close').addEventListener("click", function() { document.querySelector('.bg-modal').style.display = "none"; }); views.py def doctorProfile(request): upcomming_appointments = Appoitment.objects.all().filter( DoctorEmail=request.user, appoitmentDate__gte=timezone.now()).order_by('appoitmentDate') past_appointments = Appoitment.objects.all().filter( DoctorEmail=request.user, appoitmentDate__lt=timezone.now()).order_by('-appoitmentDate') g = request.user.groups.all()[0].name if g == … -
Django Admin Search field reverse lookup
I have following models: class Policy(models.Model): name = models.CharField(max_length=40) def __str__(self) -> str: return self.name class Meta: verbose_name_plural = 'Policies' class Statement(models.Model): name = models.CharField(max_length=40) policy = models.ForeignKey( to=Policy, on_delete=models.CASCADE, related_name='statements' ) action = models.CharField(max_length=64) resource = models.CharField(max_length=128) and following simple model admin: class PolicyAdmin(admin.ModelAdmin): inlines = [StatementInline] search_fields = [name,] What I want to achieve is to enable search functionality on Policy change list, through which I can search Policy with the name field of Statement model in addition to policy name. -
Django: Use different serializers for different (inherited) models in one endpoint
I have this models (for ilustration only): class Customer(models.Model): created = models.DateTimeField(auto_now_add=True) class Person(Customer): first_name = models.CharField(max_lenght=40) last_name = models.CharField(max_length=40) # More data related to a person class Company(Customer): company_name = models.CharField(max_length=100) # More data related to a company As you can see, I can have two "types" of customers, but they are both "customers" (I think this is a textbook example of inheritance). Everything works fine at the database level, but now I need to create an endpoint that will "dinamically" show the customer data based on which "type" of customer it is. Something like this: [ { "id": 1, "first_name": "John", "last_name": "Doe" }, { "id": 2, "company_name": "Big buck" }, { "id": 3, "first_name": "Jane", "last_name": "Doe" } ] When working within my project, I use things like: customer = Customer.objects.get(pk=100) if hasattr(customer, 'person'): pass # Do some stuff elif hasattr(customer, 'company'): pass # Do some other stuff # Do common stuff related to both customer 'types' So far, I've managed to work around by using different endpoints for "Person" and "Company" customers, but now I need to get both "types" of customers in a single endpoint. And I can't figure out how to write a serializer … -
How to bind models and form json structure?
I'm trying to implement rest api using django rest framework. I want to form a specific JSON, having the ability to receive a nested array with a set of objects. serializers.py class CarListSerializer(serializers.ModelSerializer): # option = serializers.StringRelatedField(many=True) class Meta: model = Car fields = ('id', 'model', 'mark', 'option') models.py class Car(models.Model): model = models.CharField(max_length=200) mark = models.CharField(max_length=200) option = models.ForeignKey('Option', related_name='option', on_delete=models.PROTECT, null=True) class Meta: unique_together = ['model', 'mark', 'option'] class Option(models.Model): color = models.CharField(max_length=200) engine = models.CharField(max_length=200) transmission = models.CharField(max_length=200) Expected Result: [ { "id": 1, "model": "Toyota", "mark": "Prado", "option": [ {'color': 'black', 'engine': '4.2', transmission: 'auto'}, {'color':'white', 'engine': '5.0', transmission: 'auto'} ] }, { "id": 2, "model": "Mazda", "mark": "CX-7", "option": [ {'color': 'white', 'engine': '3.5', transmission: 'auto'}, {'color': 'black', 'engine': '4.2', transmission: 'auto'} ] } ] -
How to copy queryset by splitting field value when calculating Django ORM
I am using django. If there are two or more people in the teacher field, that is, if the special character "/" is included, I want to copy the row by splitting it based on "/". [views.py] counts = Research.objects.values('teacher').annotate(**annotations).values('teacher', *annotations.keys()) The result of the current code is: <QuerySet [{'teacher': 'Helen', 'A': 1, 'R_A': 1}, {'teacher': 'Aron/Cyrus', 'A': 0, 'R_A': 0}, {'teacher': 'Daisy', 'A': 1, 'R_A': 1}, {'teacher': 'Mindy', 'A': 2, 'R_A': 0}]> The result I want to get is: <QuerySet [{'teacher': 'Helen', 'A': 1, 'R_A': 1}, {'teacher': 'Aron', 'A': 4, 'R_A': 2}, {'teacher': 'Cyrus', 'A': 4, 'R_A': 2}, {'teacher': 'Daisy', 'A': 1, 'R_A': 1}, {'teacher': 'Mindy', 'A': 2, 'R_A': 0}]> It looks like an ORM change is required. I've been searching for over 2 hours, but I can't get a solution. Does anyone know how to solve it? -
How can I redirect a user to the dashboard instead of HTTP/something/some page, after a user is successfully loggedin in Django?
http://127.0.0.1:8000/cases instead of redirecting to home pages, it's directly sending us to cases tab. -
how to keep current image file on update form django
I am making an update profile page that conclude change picture, name, and email. everytime I tried to change email or name without changing picture, it erase the picture column. How can I prevent this to happen? I've tried to put value on input file, but then I found out that input file will not read the value and always give back C://fakepath// forms.py : class UpdateForm(forms.Form): name = forms.CharField( max_length=255, required=True, help_text="Required, name" ) email = forms.CharField( max_length=254, help_text="Required. Inform a valid email address." ) avatar = forms.ImageField(required=False) views.py : class Account(LoginRequiredMixin, FormView): model = CustomUser form_class = UpdateForm user = None template_name = 'settings/account.html' def get(self, request, *args, **kwargs): self.user = get_object_or_404(CustomUser, id=kwargs["pk"]) return super(Account, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.user = get_object_or_404(CustomUser, id=kwargs["pk"]) return super(Account, self).post(request, *args, **kwargs) def form_valid(self, form): self.user.email = form.cleaned_data["email"] self.user.name = form.cleaned_data["name"] self.user.avatar = form.cleaned_data.get('avatar') self.user.save() messages.add_message( self.request, messages.SUCCESS, "Update {} user success".format(self.user.name) ) return super(Account, self).form_valid(form) Templates : <form action="{% url 'Account-list' user.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input accept="image/*" name="avatar" type='file' id="imgInp" /> <label for="" class="field-label">Full Name</label> <input type="text" name="name" id="name" class="field-style" value="{{user.name}}" placeholder="Write name here..."> <label for="" class="field-label">Email Registered</label> <input type="text" name="email" id="email" class="field-style" value="{{user.email}}" …