Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wanna overrite the admin page
In the admin page when I create a property first I want to have a dropdown when I can choose the city and then another dropdown when I can choose a district where there are Districts that have ForeignKey key the city I selected class City(models.Model): name = models.CharField(verbose_name="Emri", help_text="E nevojshme", max_length=255, unique=True) ... class District(models.Model): city_id = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(verbose_name="Emri", help_text="E nevojshme", max_length=255, unique=True) ... class Property(models.Model): district_id = models.ForeignKey(District, on_delete=models.CASCADE) ... -
Pyscript make frameworks like django and flask obsolete
I am a beginner web developer and I would actually like to know if there is any use for framworks like django and flask since would you not be able to perform most python related operations with Pyscript. Would it not take the place of these frameworks as it is easier to use pyscript to interact with a database for example instead of having to call an output from python code using ajax and flask. -
Django - OperationalError at /admin/products/product/add/ no such table: main.auth_user__old
I'm currently working on my first Django project, and I'm following the tutorial guide made by Mosh in his video in Python for Beginners. The project is an online shop and I keep getting stuck when I'm adding new products to my products list(video time stamp - 5:41:07). I followed all his steps but kept getting stuck on the same part no matter how I looked for the answer. OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 4.0.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: D:\programming\phython projects\project_5(PyShop)\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: D:\programming\phython projects\project_5(PyShop)\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\\programming\\phython projects\\project_5(PyShop)', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\programming\\phython projects\\project_5(PyShop)', 'D:\\programming\\phython projects\\project_5(PyShop)\\lib\\site-packages'] Server time: Thu, 19 May 2022 07:49:11 +0000 this is my line of code views module in products package: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def new(request): return HttpResponse('New Products') url module in products package: from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] modules module in pyshop package: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url … -
django admin one models turn to multiple urls pages
Now i have a situation in separate models choices and display in admin with different url here it's my models action: class LogAction(Enum): BUY = "buy" REFUND = "refund" SEND = "send" RECEIVE = "receive" WITHDRAW = "withdraw" SUBSCRIPTION = "subscription" NONE = "none" my models: class TransactionLog(models.Model): ... action = models.CharField(max_length=32, choices=[(str(tag), tag.value) for tag in LogAction],default=str(LogAction.NONE), db_index=True) ... admin: class TransactionLogAdmin(admin.ModelAdmin): list_display = ( 'get_event_type', 'user', 'target_user', 'action', 'created_at','get_real_point','success', 'note') def get_event_type(self, instance: TransactionLog): if instance.action == str(LogAction.SUBSCRIPTION): return "SUBSCRIPTION" elif instance.action == str(LogAction.WITHDRAW): return "WITHDRAW" elif instance.action == str(LogAction.REFUND): return "REFUND" elif instance.action == str(LogAction.BUY): return "BUY" else: return instance.action get_event_type.short_description = 'bill type' here it's my backend admin. i'd like to show all 'buy' type in one table but different urls. and all 'refund','withdraw','subscription' is as same as 'buy' type so as to let me toggle to different pages. the multiple admin site is the option but is not suitable for this situation. what django tool can i use? plz give me some hint or some suggestion thanks a lot -
AttributeError: Serializer object has no attribute 'initial_data', when trying to post a new request to a nested serializer in DjangoRestFramework
I'm trying to create two model instances from a single post request. Model2 is linked to Model1 using a ForeignKey field. Model1 also has a validate() in its serializer. The issue is when I use nested serializer to save both model instances together, the validate function of Model1 returns an error AttributeError: 'Model1Serializer' object has no attribute 'initial_data'. As per DRF docs If the data keyword argument is not passed then the .initial_data attribute will not exist. Trials: I tried intercepting the flow in __init__() and validate() of CombinedSerializer but it seems, the validate() of Model1Serializer is evaluated first. Doubt: Why is the Model1Serializer not getting supplied with the data keyword argument and how can I correct my code? At what stage is the Model1Serializer validate() function evaluated? Models: from django.db import models class Model1(models.Model): key1 = models.PositiveIntegerField(blank=False, null=False) def __str__(self): return self.key1 class Model2(models.Model): foreign_key = models.ForeignKey('Model1', blank=True, null=True, on_delete=models.CASCADE) key2 = models.CharField(max_length=20) def __str__(self): return self.key2 Serializers: from rest_framework import serializers from .models import Model1, Model2 class Model1Serializer(serializers.ModelSerializer): def validate(self, data): if(self.initial_data['key1']>=10): data['key1'] = self.initial_data['key1'] + 1 return data else: data['key1'] = self.initial_data['key1'] return data class Meta: model = Model1 fields = '__all__' class Model2Serializer(serializers.ModelSerializer): class Meta: model … -
How to pass a valiable as an object instanse in Django function
I have a function def update_field(): ... ... book.country = country_id ... I have the same piece of code in several places and I need to make a separate function for it. For example def update_field(obj_field): ... ... obj_field = country_id ... but when I try to call the function it doesn't work country = book.country update_field(country) -
Trying to include multiple images in CSV
In Django, I made a model where I import a CSV file to the DB and show the contents in index.html. All the columns have either int|char or both, but the final columns have multiple images in each cell, when I used ImageField and in the HTML used the MODEL.url it worked for all only one image, and when I tried to use more than one: <img src= " /static/assets/images/thumb/1537.png /> " in the cell using CharField the < /> transform to &lt; and &gt; and turn the HTML that was on the col to a string. Is there any way to get multiple images from the same cell? or fixing the &lt and &gt: and make it stay as < > -
DRF : How to sort custom field which created by SerializerMethodField
I've created serializing nested be using serializers as document models.py class Category(models.Model): name = models.CharField("Name", "name", max_length=255) iconname = models.CharField("Icon Name", "iconname", max_length=255) budgetamount = models.DecimalField( max_digits=19, decimal_places=2, default=0) iconcolor = models.CharField( "Icon Color", "iconcolor", default='4294951175', max_length=255) def __str__(self): return self.name class DailyExpense(models.Model): payee_item_desc = models.CharField( "Payee Item Description", "payee_item_desc", max_length=255) category = models.ForeignKey( Category, related_name='dailyexpense_category', on_delete=models.CASCADE, blank=True, null=True) amount = models.DecimalField(max_digits=19, decimal_places=2) remarks = models.CharField( "Remarks", "remarks", max_length=255, blank=True, null=True) tran_date = models.DateTimeField() isnotclear = models.BooleanField(default=False) def __str__(self): return self.payee_item_desc serializers.py class DailyExpenseSerializer(serializers.ModelSerializer): class Meta: model = DailyExpense fields = "__all__" class CategoryWithDailyExpenseSerializer(serializers.ModelSerializer): dailyexpense_category = DailyExpenseSerializer( source='filtered_dailyexpense_category', many=True, read_only=True) sum_expense = serializers.SerializerMethodField() class Meta: model = Category fields = ('id', 'name', 'iconname', 'sum_expense', 'budgetamount', 'iconcolor', 'dailyexpense_category') def get_sum_expense(self, obj): fromDate = parse_datetime(self.context['request'].query_params.get( 'fromDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') toDate = parse_datetime(self.context['request'].query_params.get( 'toDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') return obj.dailyexpense_category.aggregate(sum_expense=Sum('amount', filter=Q(tran_date__range=[fromDate, toDate])))['sum_expense'] views.py class CategoryWithDailyExpenseViewSet(viewsets.ModelViewSet): def get_queryset(self): fromDate = parse_datetime(self.request.query_params.get( 'fromDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') toDate = parse_datetime(self.request.query_params.get( 'toDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') queryset = Category.objects.prefetch_related( Prefetch('dailyexpense_category', queryset=DailyExpense.objects.filter( tran_date__range=[fromDate, toDate]).order_by('tran_date'), to_attr='filtered_dailyexpense_category') ).annotate(num_daily=Count('dailyexpense_category', filter=Q(dailyexpense_category__tran_date__range=[fromDate, toDate]))).filter(num_daily__gt=0) return queryset serializer_class = CategoryWithDailyExpenseSerializer filter_class = CategoryFilter And the result that I got as below [ { "id": 52, … -
Creating a users and superusers with a custom `MyCompanyUser(AbstractUser)` related N:1 with `Customer(models.Model)` model
I am a Django rookie. I have created a Customer class. I have created a custom user class NeuroCloud(AbstractUser). Then relate them adding a foreign key field to the custom user class. When I try to create a supreuser with python manage.py createsuperuser an error (copied below) raises. The error seems to be raising because no primary key (associated to Customer) is given/is available. My goal is to be able to create users or superusers giving email, password and customer (no its primary key but its name which is unique). Sorry for not being specific enough, but I am learning Django with no previous web programming experience. The models would be something like this: from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. # TODO: docstrings (ONLY MEANINGFUL INFO!) class Customer(models.Model): """ """ date_joined = models.DateTimeField(auto_now_add=False) class NeuroCloudUser(AbstractUser): """ """ customer = models.ForeignKey(Customer, on_delete=models.CASCADE) When I try to create a superuser, the following error raises: Username: admin Email address: <email hidden for privacity purposes> Password: Password (again): This password is too short. It must contain at least 8 characters. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "/home/yere/anaconda3/envs/neurocloud/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
How to pass object from js code to python code in django [closed]
I have a graph that I created based on user inputs and i collected the data in js code Now i want to use this graph in a searching pythone algorithm How to pass this graph to python page in dgango?? -
how to serialize two model in django rest framework to get nested json data
Hi everyone i have two model one is Name and 2nd is Role, i have join two or more model multiple time, but this time response is different, here i have share my model and expected response,please help me out. models.py class Name(BaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) class Role(BaseModel): role=models.CharField(max_length=255,null=True, blank=True) name=models.ForeignKey(Name, models.CASCADE, null=True, blank=True) serializer.py class RoleSerializer(serializers.ModelSerializer): name=NameSerializer() class Meta: model = Role fields = "__all__" Expected Response { "id": 1, "first_name": "thor", "middle_name": "", "last_name": "" "role": { "id": 1, "name": 1 } } -
Django many to many relationship in same class model
I have a modelclass 'Mapset' with a formclass 'MapSetForm'and I have a many to many field name, because I want to make a relationship where a Mapset can have many Mapsets but the mapset shouldn't be able to have a relationship to itself. I am doing this in a web application where i can set the relationship by selecting the mapset, but the problem is that the mapset where I am selecting the other ones has itself in the list. Question: How can I remove this mapset from the list? class MapSetForm(forms.modelform) class Meta: model = MapSet fields = [ 'name', 'dependencies', ... ] def __init__(self, *args, **kwargs): n = kwargs.pop('dependencies', []) super(MapSetForm,self).__init__(*args, **kwargs) self.fields['name'].queryset = MapSet.objects.filter(name = n) view: class MapsetUpdateView(guardian.mixins.PermissionRequiredMixin, UpdateView): model = MapSet form_class = MapSetForm() permission_required = 'webksv.change_mapset' return_403 = True model: class MapSet(models.Model): """Model class for MapSets. name = models.CharField( 'Name', max_length=50, unique=True, validators=[alphanumeric]) visibility = models.ForeignKey(Visibility, models.DO_NOTHING) verbose_name = models.CharField('Langname', max_length=256) description = models.TextField('Beschreibung', blank=True) dependencies = models.ManyToManyField( 'self', blank=True, symmetrical=False) -
Querying for models based on time range in Django REST Framework
I have a DB with models that each have two timestamps. class Timespan(models.Model): name = models.CharField(null=False) start_time = models.DateTimeField(null=False) end_time = models.DateTimeField(null=False) I want to be able to query for these objects based on a timestamp range. A GET request would also have a start and end time, and any Timespans that overlap would be returned. However I'm not sure how to construct a GET Request to do this, nor the View in Django. Should the GET request just use url parameters? GET www.website.com/timespan?start=1000&end=1050 or pass it in the body? (if it even makes a difference) My view currently looks like this: class TimespanViewSet(OSKAuthMixin, ModelViewSet): queryset = Timespan.objects.filter() serializer_class = TimespanSerializer Which allows me to return obj by ID GET www.website.com/timestamp/42. I expect I'll need a new viewset for this query. I know how to add a ViewSet with a nested urlpath, but shouldn't there be a way to send a request to /timespan the inclusion of a "start" and "end" parameter changes what is returned? -
django share document with user
I have a my django site where admin user will have to share documents with other user type called accountant.for example admin has something called documents in the sidebar when clicked it shows the list of documents related to the admin beside every document we will have a button share when clicked it shows the list of accountants when selected and shared the documents will be listed on the accountant's documents list page.there are two different login interfaces.how can i achieve this i have model called Document and the user type model Accountant.how should the relations should be and what should be the logic in views. class Document(models.Model): name = models.Charfield() file = model.Filefield() class Accountant(models.Model): name = models.Charfield() -
form doesn't appear - UnboundLocalError at / DJANGO FORM
my form doesn't appear at my website and its error now. this is my error message : UnboundLocalError at / local variable 'form' referenced before assignment Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.14 Exception Type: UnboundLocalError Exception Value: local variable 'form' referenced before assignment Exception Location: F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\MusicLockApp\views.py in homepage, line 20 Python Executable: C:\Users\Capoo\python.exe Python Version: 3.10.2 Python Path: ['F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp', 'C:\Users\Capoo\python310.zip', 'C:\Users\Capoo\DLLs', 'C:\Users\Capoo\lib', 'C:\Users\Capoo', 'C:\Users\Capoo\lib\site-packages'] Server time: Thu, 19 May 2022 06:33:52 +0000 here's my views.py : def homepage(request): if request.method == "POST": form = Audio_store(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['record']) return render(request, "homepage.html", {'form': form}) else: return render(request, "homepage.html", {'form': form}) return render(request, "homepage.html") html : <form method="POST" enctype="multipart/form-data"> <button type="submit" class="dsnupload"> <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i> <p style="font-weight: bold; color: white;">Insert file audio (mp3)</p> {% csrf_token %} {{form}} </button> </form> form.py : from django import forms class Audio_store(forms.Form): record=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control'})) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), path("", views.homepage, name="upload") ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i want my form appear instanly, please help me -
Page not found (404) Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order:
So hello guys i have run into trouble while running my project. enter image description here this is my urls.py from unicodedata import name from django.urls import path from django.contrib import admin from django.urls import re_path from . import views app_name = "Project" urlpatterns = [ path('', views.index , name='index'), path('counter', views.counter, name='counter'), path('Register', views.Register, name= 'Register'), path('login', views.login, name='login'), path('logout', views.logout, name = 'logout'), path('post/<str:pk>', views.post, name = 'post'), path('profile', views.profile, name='profile'), re_path(r'^appointment/appointment=(?P<appointment_id>[0-100]+)', views.viewAppointment, name='appointment'), re_path(r'^appointment/appointment=(?P<appointment_id>[0-100]+)/AddDiagnonsis', views.addDiagnosis, name='AddDiagnosis') ] and this my views.py def viewAppointment(request, appointment_id): appointment = Appointment.objects.filter(id=appointment_id) return render(request, 'appointment_form.html', {'Appointment': appointment}) i dont know what do im new here at django -
django field using pictures instead of text
If I choose one of whose input value is radio in HTML and submit, the selected one is delivered to the models, and finally, I want to retrieve the selected image from HTML again. But I can't even get a clue. What should I do? And I also wonder how to connect and use these with forms.py and html. I want to know the exact answer because the image field is set as a temporary measure. models.py ''' class Guest(models.Model): author = models.CharField(null=True,max_length=20) content=models.TextField() created_at =models.DateTimeField(auto_now_add=True) sticker=models.ImageField(label="Decorate the picture next to it!",widget=models.RadioSelect(choices=STICKER_CHOICES)) def __str__(self): return f'{self.author},{self.content}' ''' main html Sticker: <div class="table"> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/boat.png' %}" style="height:80px;width:80px;"></input> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/airplane.png' %}" style="height:80px;width:80px;"></input> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/bird.png' %}" style="height:80px;width:80px;"></input> </div> <div class="table"> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/board.png' %}" style="height:80px;width:80px;"></input> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/fish.png' %}" style="height:80px;width:80px;"></input> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/starfish.png' %}" style="height:80px;width:80px;"></input> </div> <div class="table"> <input type = "radio" name = "major" style="margin-left:15px;"><img src="{% static 'diary/css/images/sticker/turtle.png' %}" style="height:80px;width:80px;"></input> <input … -
How to change datefield to datetime field in django properly?
I have a datefield in my model currently but I want to change it to type datetimefield. I have a huge number of records in the database with type date but now after I change it to datetime will it impact other areas(since it is used in so many times like in filtering, comparing dates, getting difference between two dates etc etc)? Note: I am using django 1.9 class MyModel: date = models.DateField(null=True, blank=True) Now I want to do: date = models.DateTimeField(null=True, blank=True) This will impact more than 50k rows. What would be the best approach for this kind of scenario? -
How to popup the alert - Django template
I have wrote the template for user input the info , each user will have the separate password. I would like to validate the password when they input , if the password is incorrect they will got the popup message said "wrong password .." or sth like that. I tried to import messages library, however it doesn't work correctly, could you please help assist ? below is my code: views.py from .models import Register1 @csrf_exempt def reg(request): if request.method == 'POST': if request.POST.get('password') =="Password": print(request.POST.get('password')) if request.POST.get('phone') and request.POST.get('name') and request.POST.get('email'): post=Register1() post.phone= request.POST.get('phone') post.name= request.POST.get('name') post.email= request.POST.get('email') post.save() return render(request, 'posts/reg.html') else: print(request.POST.get('password')) messages.add_message(request, messages.INFO, 'Wrong Password') return render(request,'posts/reg.html') else: return render(request,'posts/reg.html') templates/posts/reg.html <meta charset="UTF-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <div class="container mt-3"> <body> <div class="col-9"> <!-- <h2>Input your password to continue proceed</h2> password: <input id = "pwd" type="password" name="password"/><br/> <div class="col-3 "> --> <!-- <button class="btn btn-primary" onclick="validate()">proceed</button> </div> --> </div> <div class="col-6 mt-3"> <form action="" method="POST"> {% csrf_token %} <h2>Input your password to continue proceed</h2> password: <input id = "pwd" type="password" name="password"/><br/> <div class="col-3 "> Phone: <input type="text" name="phone"/><br/> <!-- Name: <br/> <textarea cols="35" rows="8" name="name"> </textarea><br/> --> Name: <input type="text" name="name"/><br/> Email: <input type="text" name="email"/><br/> <input … -
Failed to load image at '/images/logo.png': timeout: timed out in html to pdf by weasyprint
<img id="pdf-logo-2" src="{% static 'assets_landing/images/logo.png' %}" alt="#" /> I face issue when render pdf from html. In weasyprint log, it show Failed to load image at '/images/logo.png': timeout: timed out -
How I can update nested relationships
I'm learn DRF, trying write simple monitoring system for computers. With client I havent problem, but with server have one - UPDATE foreign key. Code - https://pastebin.com/HgKXKNh0 How I can known pk for Disk and NetAdapter in for disk_data in disks_data: Disks.objects.update(client=instance, **disk_data) for adapter_data in net_adapter_data: NetAdapter.objects.update(client=instance, **adapter_data) def create(self, validated_data) from https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers, I tried to do the same update, but it didn't work. -
AWS ElasticBeanstalk LoadBalancer Config Not Linking my aplication to my domain
I created an aplication but Its is not linked to my domain exp: "site.com", "www.site.com", when I access it I get: Note: my apllication status is "ok" EI went to EC2 - LoadBalancer, And copied the instance ID, then I went to my Hoster, created a CNAME "api" and put the instance value, when I acessed "api.site.com" It worked, my aplication was linked to my domain(but not as https), but why isn't "site.com" and "www.site.com" linked? and I set the following configs: I created a key pair when I did EB init( I dont know for what it's for) Type a keypair name. (Default is aws-eb): SSH-Django_store Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:\Users\kayna\.ssh\SSH-Django_store. Your public key has been saved in C:\Users\kayna\.ssh\SSH-Django_store.pub. The key fingerprint is: SHA256:Int9QZ2czLsVCXAJTaprHmOMhuCAq4R8fGK2mKuelFU SSH-Django_store The key's randomart image is: and then I created the LoadBalancer in ElasticBeanstalk: WHY is my loadbalancer different from the tutorial i'm watching in youtube? the title is "Modify Classic LoadBalancer" the videos I watch have a different loadbalancer pagar My domain: My domain with "api" as subdomain from when I copied the instance from EC2 and … -
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)")
i was trying to connect to mySQL DB but i got this error although the server is running as shown: and here's my connection data: DB_HOST='127.0.0.1' DB_NAME='trustline' DB_USER='root' DB_PASSWORD='' DB_PORT=3306 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'STRICT_TRANS_TABLES', 'charset': 'utf8mb4' }, } } what should be done? -
Property field not appearing in django serializer
I have a property inside a Django model, I have to show it inside the serializer. I put the field inside the serializer, but it's not coming up in the response. class Example(models.Model): field_1 = models.ForeignKey( Modelabc, on_delete=models.CASCADE, null=True, related_name="abc" ) field_2 = models.ForeignKey( Modelxyz, on_delete=models.CASCADE, null=True, related_name="xyz", ) name = models.CharField(max_length=25, blank=True) @property def fullname(self): if self.name is not None: return "%s%s%s" % (self.field_1.name, self.field_2.name, self.name) return "%s%s" % (self.field_1.name, self.field_2.name) Serializer is like this: class ExampleSerializer(serializers.ModelSerializer): fullname = serializers.ReadonlyField() class Meta: model = OnlineClass fields = [ "id", "fullname",] When I call the get API for this, the fullname is not being displayed in the api response. What is the issue? -
(Django RF) Unable to set the 'to_field' to ForeignKey model
I have four model like the code below: class Sample(models.Model): sample_ID = models.CharField(max_length=10, unique=True) def __str__(self): return str(self.sample_ID) class Image(models.Model): image_ID = models.CharField(max_length=50, primary_key=True, unique=True) image_sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='image_sample') image = models.ImageField(upload_to='images') def __str__(self): return str(self.image_ID) class Label(models.Model): AI_sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='AI_sample') AI_defect = models.BooleanField() def __str__(self): return str(self.AI_sample) class Manual(models.Model): manual_sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='manual_sample') manual_image = models.ForeignKey(Image, on_delete=models.CASCADE, to_field='image_ID') manual_defect = models.BooleanField() def __str__(self): return str(self.manual_sample) Manual is ForeignKey to Sample & Image. and Image is also ForeignKey to Sample. Now I have customized an image_ID field for the to_field in manual_image so that I can reference it using my custome field. However, when I try to do the same thing for manual_sample and sample_ID, the manual_sample will become null value like this: sample: [ { "id": 1, "sample_ID": "a000001", "AI_sample": [], "manual_sample": [] } ] manual_sample: [ { "id": 3, "manual_sample": null, "manual_image": "p01", "manual_defect": true }, { "id": 5, "manual_sample": null, "manual_image": "p02", "manual_defect": false } ] For now, my API endpoint look like this: [ { "id": 1, "sample_ID": "a000001", "AI_sample": [], "manual_sample": [ { "id": 3, "manual_sample": 1, "manual_image": "p01", "manual_defect": true }, { "id": 5, "manual_sample": 1, "manual_image": "p02", "manual_defect": false …