Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add string var inside php code in python
I saw a php code to decrypt an encrypted AES-256-CBC string in PHP. But I'm using python, so I looked for a way to add a PHP script inside python. This is how I did it as I saw from this link: def decrypt(encrypted_data, password): code = """<?php function decryptionM($data, $key) { $secretkey = str_pad($key, 32, '*'); echo('secretkey: '); echo($secretkey); echo("\n"); $iv_with_ciphertext = base64_decode(str_replace('plusencr', '+', $data)); echo('iv_with_ciphertext: '); echo($iv_with_ciphertext); echo("\n"); $iv_length = openssl_cipher_iv_length('AES-256-CBC'); echo('iv_length: '); echo($iv_length); echo("\n"); $iv = substr($iv_with_ciphertext, 0, $iv_length); echo('iv: '); echo($iv); echo("\n"); $ciphertext = substr($iv_with_ciphertext, $iv_length); echo('ciphertext: '); echo($ciphertext); echo("\n"); $text = openssl_decrypt($ciphertext, 'aes-256-cbc', $secretkey, OPENSSL_RAW_DATA, $iv); echo('text: '); echo($text); echo("\n"); $asArr = explode(',', $text); echo('asArr: '); echo($asArr); echo("\n"); foreach ($asArr as $val) { $tmp = explode('=', $val); echo('tmp: '); echo($tmp[0]); echo("\n"); $finalArray[trim($tmp[0])] = str_replace('+', '', $tmp[1 ]); } echo('finalArray: '); echo($finalArray); echo("\n"); return $finalArray; } echo decryptionM(""" + encrypted_data + """, """ + password + """); ?> """ res = php(code.encode()) return res But the line echo decryptionM(""" + encrypted_data + """, """ + password + """); is outputting an error: [2022-03-24 02:06:50,202: WARNING/MainProcess] b"PHP Parse error: syntax error, unexpected '=', expecting ')' in Standard input code on line 55\n\nParse error: syntax error, unexpected '=', … -
Django Rest Framework - TypeError: reverse() got an unexpected keyword argument 'request'
I have a number of tests written for a django application, and all tests must pass in order for automated deployment to take place. Unexpectedly, a number of tests began failing, none of which had been touched with the latest commit. The error comes from a serializer that uses django rest frameworks 'reverse' function. # serializers.py from rest_framework.reverse import reverse from rest_framework.serializers import ModelSerializer, SerializerMethodField from my_app.models import ConfigVersion class ConfigVersionMetadataSerializer(ModelSerializer): class Meta: model = ConfigVersion fields = ('id', 'config', 'config_name', 'hyperlink', 'version') hyperlink = SerializerMethodField() def get_hyperlink(self, obj): return reverse( 'versions-list', kwargs={ 'configurations_pk': obj.config.id, 'version_pk': obj.id }, request=self.context['request'] ) All tests that call this serializer now fail with error TypeError: reverse() got an unexpected keyword argument 'request' Django rest frameworks documentation states that 'request' is an included and recommended argument https://www.django-rest-framework.org/api-guide/reverse/. After reviewing the documentation, I have searched for dependency version changes in the build logs to see if there were code changes, but the only dependency update is presumably unrelated (pytz). I'm pretty confused by the source of this issue, since tests were working properly a couple days ago and there don't appear to be any changes to the tests, serializers, views, or required libraries. -
Only able to run tests from dir containing manage.py while using docker shell
I have been trying to run a Django test suite in a running docker container, but using docker exec or even entering the docker shell and running the tests from outside their dir results in the test runner failing to find anything. docker exec -it \<container_name\> <project>/manage.py test doesn't find any tests. However, if I docker exec -it \<container_name\> /bin/bash and then navigate to <project> and run python manage.py test this runs the tests. If I try to do the same (enter shell) but from outside the <project> dir (e.g. python <project>/manage.py test) the test runner finds 0 tests again. I am very confused by these results to say the least, as it seems like these commands should all evoke the same behavior -
How to handle multi-level permissions in Django REST Framework?
I'm attempting to create a DRF API that can handle multi-level permissions. I have Users, Clients, and Brands. Clients can contain one or many Brands. The way I'm trying to get User Permissions to work is a User can have access to one or many Clients. If given access to that Client they will also be given limited access to one or many Brands within that Client. I can't wrap my head around how to manage the permissions on this. Does this need to object instance level permissions? or is there another way to organize it? I'm trying to avoid 3rd party packages, but I have seen several people mention django-guardian. I understand this is a very general question. So I appreciate any type of response on this. Thank you. -
How to enable CORS in Python Dash
I've seen that you can enable CORS for Flask (How to enable CORS in flask), but I have a Dash app and I want to enable something like headers = { 'Access-Control-Allow-Origin':'*' } Does anyone know how to do it? -
Muti-array result in models django
I have a second instance of database called slave_db this database have tables like this, the profile and the details of lands I created a model.py for these from django.db import models class Fields(models.Model): field_id = models.IntegerField() field_name = models.CharField(max_length=50) class Meta: managed = False db_table = 'tbl_fields' class Profile(models.Model): profile_id = models.IntegerField() name = models.CharField(max_length=20) fields = models.OneToOneField(Fields) class Meta: managed = False db_table = 'tbl_profile' I also have my serialize.py from rest_framework import serializer from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['profile_id','control_no','name','fields'] then in my views.py from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.generics import get_object_or_404 from .models import Profile from .serializers import Profile Serializer @api_view(['GET']) def ProfileDetails(request): control_no = request.GET.get("control_no") details = Profiles.objects.using("slave_db").select_related("fields").filter(control_no = control_no) detailSerializer = ProfileSerializer(details, many=True) print(detailSerializer) now the result is [ { "profile_id": 1, "control_no": "8-001", "name": "Foo", "fields": "8-001" }, { "profile_id": 1, "control_no": "8-002", "name": "Bar", "fields": "8-002" }, ] how can i get the data properly and have a result like this?. [ { "profile_id": 1, "control_no": "8-001", "name": "Foo", "fields": [ { "field_id": 1 "field_name": "Charlie Land" }, { "field_id": 2 "field_name": "Alpha Land" } ] … -
Field 'id' expected a number but got 'None'
I have a little problem. I try to add some values on my table from Mongodb, using django and the admin page. I wrote in models.py (the code is basic, because I am learning and this was the first step from a tutorial that I saw): from datetime import date from django.db import models class activity_stage(models.Model): date = models.TextField() start = models.TextField() stop = models.TextField() distance = models.TextField() calories = models.TextField() steps = models.TextField() In admin.py from django.contrib import admin from .models import activity_stage admin.site.register(activity_stage) But on my admin page, it doesn't attribute to me the index number (list of objects from admin page). I tried to delete the objects, but I receive this error: Field 'id' expected a number but got 'None'. My table from my database it's look like this: Mongodb_collection. I named the class from the models with the same name as the collection from mongo. At the end, I want to import on my page an excel file and I found something that probably can help me. But I don't know how to solve my error. I think that i solve the problem I can after add the objects from admin page in my db. -
Django async model update not being enacted
The SQL update does not seem to be being enacted upon, and no errors are being thrown either. Below is a simplified version of my code. For context, the "choice" field in the model is a Boolean Field with a default of False, and a user may (ideally) change this by sending a JSON package with the "CHOICE" event and "Yes" message. consumers.py import json from channels.generic.websocket import AsyncJsonWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] #Websockets connection code async def disconnect(self): #Websockets disconnect code async def receive(self, text_data): response = json.loads(text_data) event = response.get("event", None) message = response.get("message", None) if event == "CHOICE": room_set = await sync_to_async(Room.objects.filter)(room_code=self.room_code) room = await sync_to_async(room_set.first)() if (not room.choice) and message["choice"] == 'Yes': sync_to_async(room_set.update)(choice=True) #line seems to not be working elif room.choice and message["choice"] == 'No': sync_to_async(room_set.update)(choice=False) #code to send message to group over Websockets #code regarding other events async def send_message(self, res): #Websockets send message code I've tried to only include the relevant code here, but if more is needed please let me know. Thanks in advance! -
How to deal with lots of duplicated data in DB?
I'm currently building a database for a photography project and I'm having troube to decide this: There are about 3 million photographs and I'd like this to keep working even with 15 million. They are stored on disk and with paths in the DB. All of those need a caption, but captions are highly duplicated. On Average about 10 photos have exactly the same caption (same creator, same title, same date). Is it better to create one model? class Photo(models.Model): file = models.FileField() headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() Or should I make 2 models even if it means having to create copies manually when one photo out of a group gets a different caption afterwards? class Photo(models.Model): file = models.FileField() metadata = models.ForeignKey('Metadata') def set_metadata(self, metadata): self.metadata = Metadata.models.get_or_create(metadata) class Metadata(models.Model): headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() The most common task will be to search for pictures based on their metadata. Is creating an extra model and reducing the db table by factor 10 worth it? Or does it just introduce unnessesary complications with no benefits in performance? Thank you for your help! -
How to change datatables language on click of a button in django?
I already have the language change of my page when clicking a button, the problem is that how do I do it with dataTables? It's rare to change the entire language page and dataTables doesn't sync with the language change button. Does anyone have an idea how to do that? index.html <form action="{% url 'set_language' %}" method="POST" class="form-inline"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <div> <select name="language" id="" class="form-control"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} {{language.code}} </option> {% endfor %} </select> </div> <input type="submit" value="{% trans 'Go' %}" class="btn btn-danger"> </form> js <script> $(document).ready( function () { $('#datatable').DataTable({ ); } ); </script> -
Django - How to create and migrate two tables for development and production on same database? (prefix in front when running as dev)
I am trying to have two tables in one database like below based on development and production environment. development dev_my_comments production my_comments I tried using environment variable while declaring table like below class Data_Comments(models.Model): class Status(models.IntegerChoices): GENERAL = 0 YELLOW = 1 RED = 2 ord_no = models.ForeignKey(Data_Import, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=500, null=True) strike_comment_type = models.IntegerField(choices=Status.choices, default=0) strike_date = models.DateTimeField(auto_now=True, blank=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='comments_user') class Meta: db_table = 'my_comments' if settings.ENV_TYPE == 'PRO' else 'dev_my_comments' app_label = "my_app" by using this option, make migrations just renames existing tables instead of creating new... (wanted to have both the tables and want to migrate changes on both tables) is there something I am missing to make it work? -
django forms.DateInput not responding to dd/mm/yyyy format
currently I'm having issues with getting input validation working as expected with Django DateInput As per my understanding, the default format for DateInput is "%Y-%m-%d" if left untouched, however explicitly setting the format to "%d/%m/%Y" still causes validation errors. Here are some examples Input: 25/03/1981 Expected: Valid date (We expect this value to not trigger a validation error) Actual: Enter a valid date. Input: 1/07/1981 Expected: Date parsed as 1st July Actual: Date parsed as 7th January (i.e date and month are parsed in place of each other) forms.py class PatientForm(ModelForm): class Meta: # Make form look nice from here model = Patient fields = ('PAS_number', 'first_name', 'middle_name', 'surname', 'DOB', 'priority_code', 'patient_information', 'patient_status') widgets = { 'PAS_number': forms.NumberInput( attrs={'class': 'form-control'}), 'first_name': forms.TextInput( attrs={'class': 'form-control'}), 'middle_name': forms.TextInput( attrs={'class': 'form-control'}), 'surname': forms.TextInput( attrs={'class': 'form-control'}), 'DOB': forms.DateInput( format=('%d/%m/%Y'), attrs={'class': 'form-control'}), 'priority_code': forms.Select( attrs={'class': 'form-control'}), 'patient_information': forms.Textarea( attrs={'class': 'form-control'}), 'patient_status': forms.Select( attrs={'class': 'form-control'}), } -
Which better operating system (windows or linux) to use for python app on azure app service
I'am confused which opertaing system to use for my django app to deploy it on azure cloud I can't find enough information to take the best decision -
Django RestFramework nested serializer field many=false
how can I create a nested serializer field without using (many=True)? The following code works fine: from music.models import Track, Album from rest_framework import serializers class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album However the I cannot change the json payload as it comes from a 3rd part app, and the field "tracks" in the example should be "track" and POST just one object. This json works fine: { "album_name": "Black Album", "artist": "Metallica", "tracks": [ { "order": 1, "title": "Enter Sandman", "duration": 245 }, { "order": 2, "title": "Sad but True", "duration": 264 }, { "order": 3, "title": "The Unforgiven", "duration": 159 } ] } but I need to get this json working, one object, without the square brackets []: { "album_name": "Black Album", "artist": "Metallica", "tracks": { "order": 1, "title": "Enter Sandman", "duration": 245 } } I've tried to remove the (many=True) but I receive either the following errors: Got AttributeError when attempting to get a value for field `order` on serializer … -
Redirect a user from www.abcd.in to www.abcd.com with nginx and django app automatically
I have a unique query: There is a website is hosted on Digitalocean Droplet with a certain IP. There is a abcd.com domain and a abcd.in domain. Currently the nginx vhost is containing the abcd.com domain ServerName with the IP of the droplet. Also both abcd.com and abcd.in have the same IP addresses configured by the previous server admin. I want a way such that when I open up abcd.in domain, it should redirect to abcd.com automatically. What is the change required to be done in the Nginx server block for the same ? Or can I change directly on digitalocean itself in it's Domain Configuration. The base stack is Django App with Python Stack. -
How can I link styles.scss file with django templates?
I just facing a silly problem. I can't link styles.scss file with django template from the static folder. This method not working here {% static '/css/style.scss' %}. Now, what will have to do for linking .scss file? -
Saving Django data from forms to sqlite database
What I have here is basically recipes which have to be saved in a database with many to one relationship between hops, fermentables etc. and main recipe which includes the name type and so on. What we have is the user fills in the forms and then with this information we are calling this in the view.py file: def saveRecipe(request): try: data=json.loads(request.read()) recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Now this leads us to the models.py file: class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe @classmethod … -
django unit test admin StackedInline with post function using reverse function
I'm working on unit test and want to test the admin dashboard where I have a user information with inline models. I don't want how to fill data to those models. this is test for the admin: def test_user_admin__create(superuser, client): client.force_login(superuser) phone_number = factory.Faker._get_faker().phone_number() password = factory.Faker._get_faker().password() response = client.post( reverse("admin:users_user_add"), { "phone_number": phone_number, "password1": password, "password2": password, "is_superuser": True, "is_staff": True, }, follow=True, ) the models: class User(AbstractUser, PermissionsMixin): phone_number = PhoneNumberField(unique=True) email = models.EmailField("Email address", unique=True, null=True, blank=True) password = models.CharField(_("password"), max_length=128) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) class Address(models.Model): label = models.CharField(max_length=200) user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="addresses") is_default = models.BooleanField(default=False) street = models.CharField(_("Street"), max_length=200) and the registration is done like that: class UserAddressInline(admin.StackedInline): model = Address extra = 0 class UserAdmin(admin.ModelAdmin): add_form = CustomUserCreationForm form = UserChangeForm inlines = [ UserAddressInline, ] admin.site.register(User, UserAdmin) admin.site.register(Address, AddressAdmin) I want to test the admin dashboard and fill data to the model User and the Addresses using the function test_user_admin__create -
how do i solve tuble object has no attribute after i run my django prject
I have created django project and starting the development. there were no issue as i test it but after i visit the developement server I get the error of tuple object has no attribute even though there is no tuble variable whatsoever -
How to store list of JSON data in a Django model?
What is the best way to store a list of JSON dictionaries in a Django model field? I am creating a transaction application for shops and I am trying to store the items of each order in a field without relying on relational models. Each item in this list will have a name, quantity and unit_price. For example: [ { "name": "Product #1", "quantity": 1, "unit_price": 25.0 }, { "name": "Product #2", "quantity": 1, "unit_price": 50.0 } ] I am using a PostgreSQL database, but I've heard it's bad practice to use database-specific fields, such as ArrayField. What would be the best way to go about this and that would also keep the DRF serialization as simple as possible? -
Get list of Array requested by ajax in a django view
let's take this ajax request in a django template: list_of_array = [{name1,value1},{name2,value2},{name3,value3}] $.ajax({ type: 'GET', url: myview_url, data: { my_list: list_of_array, }, dataType: 'json', success: function (response) { do something } }, error: function (error_data) { console.log("error") console.log(error_data) } }) Then, in the view under myview_url, I try to do something with 'my_list' in data. Like so: def myView(request): list = request.GET.getlist('my_list[]') do something... ... response_data = { "list": list, } return JsonResponse(response_data) but list return an empty list. If my_list doesn't contain associative array, like if it is: my_list = [1,2,3] I can get its content in my view. So, how to get the content of list that contains Array in my django view ? Thank you -
Getting CSRF token missing when submitting form data in django
I am getting CSRF token missing error everytime while submitting the form mentioned below. What might be the problem? Below is the code for my views.py file : *all imports are here # Create your views here. def takeExam(request, pk): mock = MockTest.objects.get(id=pk) context = { 'mock':mock, } return render(request, "exam/take-exam.html", context) @login_required(login_url='login') def startExam(request,pk): mock=MockTest.objects.get(id=pk) questions=Question.objects.all().filter(test=mock) if request.method=='POST': pass response= render(request,'exam/start_exam.html',{'mock':mock,'questions':questions}) response.set_cookie('mock_id',mock.id) return response @login_required(login_url='login') def calculateMarks(request): if request.COOKIES.get('mock_id') is not None: mock_id = request.COOKIES.get('mock_id') mock=MockTest.objects.get(id=mock_id) total_marks=0 questions=Question.objects.all().filter(course=mock) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks std = student.CustomUser.objects.get(user_id=request.user.id) result = Result() result.marks=total_marks result.exam=mock result.student=std result.save() return HttpResponseRedirect('view-result') @login_required(login_url='login') def resultViews(request): mocks=MockTest.objects.all() return render(request,'exam/view_result.html',{'mocks':mocks}) @login_required(login_url='studentlogin') def checkMark(request,pk): mock=MockTest.objects.get(id=pk) std = student.CustomUser.objects.get(user_id=request.user.id) results= Result.objects.all().filter(exam=mock).filter(student=std) return render(request,'exam/check_marks.html',{'results':results}) @login_required(login_url='studentlogin') def studentMark(request): mocks=MockTest.objects.all() return render(request,'exam/student_marks.html',{'courses':mocks}) My html file: {% extends 'main.html' %} {% block content %} {%load static%} <div class="jumbotron my-2 py-4" onmousedown="return false" onselectstart="return False" > <h1 style="text-align: center">{{mock.name}}</h1> <form class="form my-2" autocomplete="off" onsubmit="saveAns()" action="{% url 'calculate-marks' %}" method="POST" > {% csrf_token %} {% for q in questions%} {% if q.question %} <div class="text-danger my-3 font-weight-bold"> {{ forloop.counter }}. {% endif %} {% if q.imgQuestion %} <img src="{{q.imgQuestion.url}}" alt="imgQuestion" /> {% … -
If you see valid patterns in the file then the issue is probably caused by a circular import in django
I am getting this error "If you see valid patterns in the file then the issue is probably caused by a circular import in". I saw other stack flow questions and I know the error is coming from views.py but I cannot seem to figure out where the error is views.py/myapp from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey,Welcome</h1>') urls.py/myapp from django.urls import path from myapp import views urlpattern = [ path('',views.index, name='index') ] urls.py/myproject from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')) ] -
SQLAlchemy - Passing a DDL generated Primary Key to Child Model through Relationship
I currently have a parent/child relationship defined between the Invoice/Item table. When running the following code: with Session(engine) as session: invoice = Invoice(INV_STORE=99, items=[Item(LINE_ITEM=1, BARCODE=1234567), Item(LINE_ITEM=2, BARCODE=1234567)]) session.add(invoice) session.commit() I get the following error: [SQL Server]Cannot insert the value NULL into column '...' [SQL: INSERT INTO [ITEM] ([INV_STORE], [LINE_ITEM], [BARCODE]) VALUES (?, ?, ?)] [parameters: (99, 1, 1234567)] My invoice object creates perfectly, it seems the DDL generated column values are not automatically populating the child object, only the store value I passed to the Invoice object (note the lack of INV_NUM in the insert statement). Is there something simple I am missing? Unfortunately, the legacy database we are using requires the table relationship to be configured as such, and there is no auto-increment in place for the Invoice.INV_NUM field. Here's my model configuration: class Invoice(Base): __tablename__ = 'INVOICE' INV_STORE = Column(Integer, name='INV_STORE', primary_key=True, default=1) INV_NUM = Column(Integer, name='INV_NUM', default=text(f"(SELECT MAX(INV_NUM) + 1 FROM INVOICE WHERE INV_STORE = {INV_STORE})"), primary_key=True)) ... items = relationship('Item', backref='Invoice', primaryjoin='Invoice.INV_STORE == Item.INV_STORE and Invoice.INV_NUM == Item.INV_NUM') And the Child, Item: class Item(Base): __tablename__ = 'ITEM' INV_STORE = Column(SmallInteger, ForeignKey('INVOICE.INV_STORE'), primary_key=True) INV_NUM = Column(Integer, ForeignKey('INVOICE.INV_NUM'), primary_key=True) LINE_ITEM = Column(Integer, name='LINE_ITEM', primary_key=True) ... -
Django Rest Framework - Serializer doesn't work
I am trying to create a blog API that would consist of user posts and comment instances. I am using Django & Django Rest Framework to build the API that would return data in JSON format. Below is an example of the JSON data being returned: "id": 2, "user": 1, "user_photo": "http://127.0.0.1:8000/media/users/Forest_Me.jpg", "is_owner": true, "description": "Hey there, this is my post and I like it", "images": [ { "id": 3, "post": 2, "image": "http://127.0.0.1:8000/media/posts/foo.jpg", "comment": "This is image #1" }, { "id": 4, "post": 2, "image": "http://127.0.0.1:8000/media/posts/bar.jpg", "comment": "This is image #2" } ], "created": "2022-03-23T16:58:44.800255+03:00", "likes": [ 1 ], "comment_count": 1, "comments": [ { "id": 3, "post": 2, "text": "This is a comment on my post", "user": 1, "likes": [], "created": "2022-03-23T17:00:27.074362+03:00", "images": [ 3, <----- should be URL to the image, not just id 4 <----- should be URL to the image, not just id ] } ] } My problem is that while the Post images are returned in the JSON correctly, my PostComment images are returned just as an array of id, without the URLs. I indicated with arrows in the code where I'm trying to get an array of objects (id & URLs). I suspect …