Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Postgres ArrayField: Overlap Length
Let say I have a model: class Post(models.Model): nlp_data = ArrayField(models.CharField(100)) As any awesome blog, I'd like to fetch some recomendations, to keep my users reading. The rule I want to implement: Get any posts, where nlp_data has at least two common "words" with a set of given "words". My guess is I could use some Func inheritance, using some CARDINALITY and && operator, but I'm struggling assembling those together. nlp_data is really coming from NLP Algorithms, any M2M tag system is excluded. -
How can I make citext extension work on Django tests?
I'm running tests against a model having a ArrayField(CICharField()) field and they return a string instead of a list. I use pytest-django to run the tests. I know that returning a string instead of a list was a known problem in the past, but it's fixed in my current Django version (2.1.13). When I reproduce the test from the shell, everything works ok. Things seems to be related to the tests environment, specially how test suite creates the database. As far as I understand, citext extension is not installed properly during the tests. If I run the test battery twice, keeping the database (using --reuse-db), the second (and next other) run work perfectly well. That makes me think that the extension is installed "too late". Probably not very useful, but this is the result I'm getting: self = <tests.test_ciarrayfield.CIArrayFieldTestCase testMethod=test_save_load> def test_save_load(self): print(settings.INSTALLED_APPS) instance = ProductFactory(sku="SKU1", product_types=[]) loaded = Product.objects.get() > self.assertEqual(instance.product_types, loaded.product_types) E AssertionError: [] != '{}' src/tests/test_ciarrayfield.py:14: AssertionError And part of my model: class Product(models.Model): product_types = ArrayField( CICharField(max_length=750), default=list, blank=True) The obvious expected result is to get a list on that field after getting the instance from the database, and not a string. As I said, this … -
Django: Intercepting & Accepting/Rejecting Login Attempts
Is there a way to intercept login attempts with Django, perhaps a signal or hook, whereby if a certain User attribute is True or False, would either allow the login attempt to continue, or reject it... I would rather not have to rebuild from scratch, just use the existing Django infrastructure... -
Jinja: find all the variables used in a template [duplicate]
This question already has an answer here: How to get list of all variables in jinja 2 templates 4 answers I'm working with Django and Jinja and I want to obtain a list of all the variables used in a given template. For the moment, I've managed to retrieve all the undeclared variables, ie. those who are used like this {{ username }},j by using jinja2.meta.find_undeclared_variables. But, I also need to obtain the declared variables, ie. those who are used like this {% set age = 32 %}. Unfortunately, I haven't found a way of doing this. How can I obtain the second type of variables from within a Jinja template? -
Building a secure file-manager app with Django
I'm developing a project which is going to be a public website and it needs to get media files (digital images, audios and videos) from users and save them and I don't want users to upload malicious files into my server (I'm currently using an SFTP server for storage). So I'm looking for a solution to check file formats and allow "safe and intact" media files to be uploaded. Is there any python package to check some bytes of the file and say "this is a valid jpg" or "mp3" etc? Can you recommend any other solution for my problem (securing my file-manager app)? -
How to support optional or empty FileField with Django Rest Framework?
I added a new FileField 'photo' to my existing model and migrated the database. When I try to return data using DRF, I get the error message "ValueError: The 'photo' attribute has no file associated with it." Photo column contains empty values. The field should be optional. models.py: def photo_directory_path(instance, filename): return 'photos/{0}/{1}'.format(instance.id, filename) class MyModel(models.Model): ... photo = models.FileField(blank = True, editable = True, upload_to=photo_directory_path) ... class MyModel_l10n(models.Model): ... mymodel = models.ForeignKey(MyModel, on_delete=models.CASCADE, related_name='%(class)s_mymodel') ... serializers.py: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['photo'] class MyModel_l10nSerializer(serializers.ModelSerializer): photo = serializers.ReadOnlyField(source='mymodel.photo') class Meta: model = MyModel_l10n fields = ['photo', ...] views.py: res = MyModel_l10n.objects.filter(...) serializer = MyModel_l10nSerializer(res, many=True) return Response (serializer.data) error message: ValueError: The 'photo' attribute has no file associated with it. -
How to handle read/write operations on FileObject in Test environment (using Pytest)
I am testing a FileField in django with pytest. What I want to do is to check if the returned content within the file is the same as the file that was uploaded. I know that I can just call read() normally on a FieldFile but somehow in my test env it doesn't work like expected. The pytest docs also don't answer my prayers. I do it like this: def test_content_of_returned_file(self, client, user): response = make_auth_request(user, client) #makes authenticated call first_obj = FileCollection.objects.first() #gets the first object in the db print(first_obj.store_file) # for debugging first_obj_file = first_obj.store_file.read() #read content of first object assert response.content == first_obj_file #check if the content of db object and called object is the same Unfortunately this gives me a ValueError: I/O operation on closed file. When I try to open it like this: first_obj_file = open(first_obj.store_file, "r") I get the same error. Maybe the error is also the response.content. I am not sure. When I print it out it give my a test_file_download.TestDownload object. So maybe the read and write operations differ? Any help is very much appreciated! Thanks in advance! -
Django raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am trying to use pyspark to preprocess data for the prediction model. I get an error when I try spark.createDataFrame out of my preprocessing.Is there a way to check how processedRDD look like before making it to dataframe? import findspark findspark.init('/usr/local/spark') import pyspark from pyspark.sql import SQLContext import os import pandas as pd import geohash2 sc = pyspark.SparkContext('local', 'sentinel') spark = pyspark.SQLContext(sc) sql = SQLContext(sc) working_dir = os.getcwd() df = sql.createDataFrame(data) df = df.select(['starttime', 'latstart','lonstart', 'latfinish', 'lonfinish', 'trip_type']) df.show(10, False) processedRDD = df.rdd processedRDD = processedRDD \ .map(lambda row: (row, g, b, minutes_per_bin)) \ .map(data_cleaner) \ .filter(lambda row: row != None) print(processedRDD) featuredDf = spark.createDataFrame(processedRDD, ['year', 'month', 'day', 'time_cat', 'time_num', 'time_cos', \ 'time_sin', 'day_cat', 'day_num', 'day_cos', 'day_sin', 'weekend', \ 'x_start', 'y_start', 'z_start','location_start', 'location_end', 'trip_type']) I am getting this error: [Stage 1:> (0 + 1) / 1]2019-10-24 15:37:56 ERROR Executor:91 - Exception in task 0.0 in stage 1.0 (TID 1) raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:452) at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:588) at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:571) at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:406) at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37) at scala.collection.Iterator$class.foreach(Iterator.scala:891) at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28) at org.apache.spark.api.python.PythonRDD$$anonfun$3.apply(PythonRDD.scala:153) at org.apache.spark.api.python.PythonRDD$$anonfun$3.apply(PythonRDD.scala:153) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101) … -
Django Docker app container don't open on browser after run
I dockerize my django app, this is my Dockerfile: FROM python:3.6-alpine EXPOSE 8000 RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 well, i build my image and i run it: docker run -p 8000:8000 --link postgres:postgres cath11/test_app all sems to be done: but when i open my browser on http://0.0.0.0:8000/ or http://127.0.0.1:8000/ my app won't open Why my django app seems running on my container, i expose port bat i cannot see it in my hosted browser? So many thanks in advance -
Many-to-Many with additional properties
I've built a small ERP system with some products( model: Product) and 1 stock location. The quantity in stock is simply 1 property of the object. I'd like to extend the application to more stock-locations but don't find the right way to do this. For 2 or 3 locations I can add of course simply additional properties to my model but in the case of many locations(let's say i.e. 250) this becomes not clear anymore. I already tried a many-to-many relationship between a model of stocklocations and products. The problem here, however, is that I can add products to stocklocations but cannot retrieve the amount of product in each stocklocation. I hope somebody can help me on the right track to tackle this self-created problem. -
Django for loop is not showing my items on webpage
I have a table on my webpage that I want to iterate product information into and it worked up until I tried adding a paginator. The server runs fine and the rest of the website is functional. Here are my files: shop/products.html {% extends 'base.html' %} {% block content %} <h1>On sale here</h1> <div class="col-sm-3"> <h4>Categories</h4> <ul class="list-group"> <a href="{% url 'products' %}" class="list-group-item"> All Categories </a> {% for c in countcat %} <a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}} <span class="badge">{{c.num_products}}</span> </a> {% endfor %} </ul> </div> <div class="col-sm-9"> <h4>Note that all products are second hand, unless otherwise stated.</h4> <form class="form-inline my-2 my-lg-0" action="{% url 'search_result' %}" method="get"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q"> <button class="glyphicon glyphicon-search h-100" type="submit"></button> </form> <table class="table table-bordered table-hover table-condensed"> <thead> <!-- The header row--> <tr> <th>ID</th> <th>Name</th> <th>Image</th> <th>Category</th> <th>Description</th> <th>Stock</th> <th>Price</th> <th>Buy</th> </tr> </thead> <tbody> <!-- Product row(s) --> {% for product in products %} <tr> <td>{{product.id}}</td> <td>{{product.name}}</td> {% if product.image %} <td><img src="{{product.image.url}}"></td> {% endif %} <td>{{product.category}}</td> <td>{{product.description}}</td> <td>{{product.stock}}</td> <td>&euro;{{product.price}}</td> {% if product.stock > 0 %} <td><a href="{% url 'add_cart' product.id %}" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-shopping-cart"></span></a></td> {% else %} <td><a href="" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-warning-sign red"></span></a></td> … -
I want to insert google ads sense ads into my django app but i don't know how? can you please help me with this?
Actually, I m developed a simple blog app and i want it to have some ads so that i can earn some income, if someone visits my site. But i dont know how to insert those ads in django. Please help me ! -
Dockerfile error during creating a Django project with Docker
I try to start a django/postgresql project with Docker. I have 3 files in the project folder (Dockerfile, docker-compose.yml, requirements.txt) When I run: sudo docker-compose run web django-admin startproject composeexample . I get the following error: Starting backend_db_1 ... done Building web ERROR: Cannot locate specified Dockerfile: Dockerfile Here's my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django>=2.0,<3.0 psycopg2>=2.7,<3.0 -
How to change the initial value of a nested field to zero instead of null value.?
How to change the initial value of a nested field to zero instead of null value.? In my case Prize model is a OneToOneField to model Album Serializer class PrizeSerializer(serializers.ModelSerializer): class Meta: model = Prize fields = ['title', 'amount'] class AlbumSerializer(serializers.ModelSerializer): prize = PrizeSerializer(read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'prize'] Some items have prize data but some do not have prize data. If there is no prize data it will be shown as null, >>> serializer.data { "album_name": "The Grey Album", "artist": "Danger Mouse", "prize": null } how to change this null value to zero.? Expected output >>> serializer.data { "album_name": "The Grey Album", "artist": "Danger Mouse", "prize": "0.0" } -
django server (hosted on ec2 ubuntu) failing for multiple users
I am trying to run django server on aws ec2 instance (ubuntu) using screen command. screen -L python3 manage.py runserver 0.0.0.0:8000 My script works in simple common way that it detects a POST request, processes and responds via HttpResponse. When one user is interacting, and suddenly new user iteracts and new post request is detected, older flow get cut off. How do I handle multiple users ? -
Implementing Django 2.2 database constraint across multiple columns
I have a Django model with start date/time and end date/time where all four components may (independently) be a null value (and there is a semantic difference between a null/unknown value and a known value). I am trying to implement a database constraint [1, 2] to check that if they are non-null that the start date/time is before the end date/time. I have implemented the constraint in two different ways (commented as Option 1, a single constraint, and Option 2, as two constraints) below: from django.db import models class Event( models.Model ): start_date = models.DateField( blank = True, null = True ) start_time = models.TimeField( blank = True, null = True ) end_date = models.DateField( blank = True, null = True ) end_time = models.TimeField( blank = True, null = True ) class Meta: constraints = [ # Option 1 models.CheckConstraint( check = ( models.Q( start_date__isnull = True ) | models.Q( end_date__isnull = True ) | models.Q( start_date__lt = models.F( 'end_date' ) ) | ( ( models.Q( start_time__isnull = True ) | models.Q( end_time__isnull = True ) | models.Q( start_time__lte = models.F( 'end_time' ) ) ) & models.Q( start_date = models.F( 'end_date' ) ) # This line ) ), name … -
Django- Foreign key constraint failed related error
I am new in Django, I'm making an item-category exercise. each item belongs to a category via a foreign key.I'm not able to understand problem in my code during submission of item detail. I'm getting an error "FOREIGN KEY constraint failed". I wrote the code for models.py which is working fine in the admin dashboard of Django, but if same thing I'm trying to implement by HTML form page, I'm getting error. models.py class ColorCat(models.Model): name = models.CharField(max_length=20, default="other") def __str__(self): return self.name class ListItems(models.Model): name = models.CharField(max_length=25, default='item') item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, default=0, null=True,blank=True) views.py def index(request): list = ListItems.objects.all() cat = ColorCat.objects.all() return render(request, 'colorlist.html', {'color': cat, 'item':list }) def colorlist(request): new_list = ListItems new_cate = ColorCat if request.method=="POST": item = str(request.POST["item"]) cat = str(request.POST["category"]) f_key = ColorCat.objects.filter(name="orange").get() new_list(name="item").save() new_list(item_cat=f_key.id).save() item = ListItems.objects.all() color = ColorCat.objects.all() return render(request, 'colorlist.html', {"item": item, "color": color}) def addcat(request): if request.method=="POST": newcat = str(request.POST["name"]) ColorCat(name = newcat).save() item = ListItems.objects.all() color = ColorCat.objects.all() return render(request, 'colorlist.html', {"item":item, "color":color}) colorlist.html {% extends 'base.html'%} {% block content%} <h2>Welcome in color cards</h2> <form action="addcat" method="POST"> {% csrf_token %} <lable>add new cat<input type="text" name="name"></lable><br> <label>submit<input type="submit"></label> </form> <form action="colorlist" method="post"> {% csrf_token %} <label>new item<input type="text" … -
can not import name 'model' from 'app.model'
I have two apps 'user' and 'game' and here is my user/models.py: from django.db import models from django.db.models.fields import related from django.contrib.auth.models import AbstractBaseUser , User, AbstractUser , PermissionsMixin from .managers import CustomUserManager from game.models import Game class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=150, unique=True, blank=True , null=True,) email = models.EmailField( blank=True , null=True , unique=True) password = models.CharField(max_length=100, null=True , blank=True) objects = CustomUserManager() class Meta: db_table = 'user' class Team(models.Model): name = models.CharField(max_length=40, unique=True) players = models.ManyToManyField(User, related_name="players") game = models.ManyToManyField(Game) is_verfied = models.BooleanField(default=False) class Meta: db_table = 'team' and here is my game/models.py: from django.db import models from user.models import User, Team from leaga.settings import AUTH_USER_MODEL class Game(models.Model): name = models.CharField(max_length=50) is_multiplayer = models.BooleanField(default=False) class Event(models.Model): title = models.CharField(max_length=100) start_date = models.DateTimeField() end_date = models.DateTimeField() class Tournament(models.Model): title = models.CharField(max_length=50) is_team = models.BooleanField(default=False) price = models.PositiveIntegerField() info = models.TextField(max_length=1000) user = models.ManyToManyField(AUTH_USER_MODEL, related_name='tounament_user') team = models.ManyToManyField(Team, related_name='team') game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='tournament_game') event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='tournament_event') # some other code and classes here but unnecessary to mention . . . . when i run : python manage.py makemigrations user this is the console log: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", … -
Different templates for UpdateView for the same model in Django
So I've got a template listing different products in user cart - I would like to give user a chance to update each product from this view. But depending on product type I would like to display different 'update_templates'. What should be the best scenario for this situation? Should I use few different UpdateViews for the same model? Like: class ProductType1UpdateView(UpdateView): model = CartItem fields = '__all__' template_name_suffix = '_product1_update_form' class ProductType2UpdateView(UpdateView): model = CartItem fields = '__all__' template_name_suffix = '_product2_update_form' Or should I make it in one view, and add some if statements that will display proper template depending on product type? Like: class ProductUpdateView(UpdateView): model = CartItem fields = '__all__' {here if statement checking product id} template_name_suffix = '_product1_update_form' {elif} template_name_suffix = '_product2_update_form' The first option works, but it doesn't feel right to me. How would I formulate my if statement to make it with the second option. Or is there maye another, better way to do it? -
Add Django endpoint that doesn't require database connection
I have a typical Django project that uses PostgreSQL as it's database backend. I need to set up a specific endpoint (/status/) that works even when the connection to the database is lost. The actual code is very simple (just returns the response directly without touching the DB) but when the DB is down I still get OperationalError when calling this endpoint. This is because I use some pieces of middleware that attempt to contact the database, e.g. session middleware and auth middleware. Is there any way to implement such /status/ endpoint? I could theoretically implement this as a piece of middleware and put it before any other middleware but that seems as kind of hack. -
how to verify emails after link is clicked usind django rest auth
I am using Django rest auth to authenticate users in my app, the users are successfully getting the email to verify their account but on clicking the link, they get an error KeyError at /account-confirm-email/MTU:1iNTcO:lRoljcqAs3HQMlyy9AzUJH6Kq5w/ Please, how can the users be successfully verified when they click the link my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'users', ] ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = 'testE' DEFAULT_FROM_EMAIL = 'test@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/ urls.py from rest_auth.registration.views import VerifyEmailView urlpatterns = [ path('admin/', admin.site.urls), url('api/rest-auth/', include('rest_auth.urls')), url('api/account/', include('users.api.urls')), url('api/rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), ] -
updating the readonly_fields in django based on the change permission
i have python django project where i am using to display all the books and rendering a single book when clicking on each book so django will automatically generate the book details. so while rendering i want to make the price_upgrade boolean field read only if the user doesn't have a group called author so my codes like this class BookAdmin(admin.ModelAdmin): list_per_page = 10 list_display_links = ['name'] readonly_fields = ('id', 'name', 'city', 'price_upgrade') ... ... ... def has_change_permission(self, request, obj=None): if request.user.groups.all().filter(Group ='author').exists(): print('author group is there') else: print('author group is not there') #print('request', request.user.groups.all(), type(request.user.groups.all())) return True how can i add the price_upgrade field to readonly_fields if current user doesn't have the group of author else we should remove the price_upgrade field from readonly_fields because he is part of author group so he can edit it Version python 2.7 django 1.8 Any help appreciated -
Browser complains about access control header missing even thought it is there
I'm using a simple Django middleware to set the access control headers. class CorsMoiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Credentials"] = True response["Access-Control-Allow-Methods"] = "GET" response["Access-Control-Max-Age"] = "3600" response["Access-Control-Allow-Headers"] = "Content-Type, Accept, X-Requested-With, remember-me" return response Using curl i clearly see the correct headers. < HTTP/1.1 200 OK < Date: Thu, 24 Oct 2019 09:40:35 GMT < Server: WSGIServer/0.2 CPython/3.7.4 < Content-Type: application/json < Vary: Accept, Cookie < Allow: GET, POST, HEAD, OPTIONS < Access-Control-Allow-Origin: * < X-Frame-Options: SAMEORIGIN < Content-Length: 176 < Access-Control-Allow-Credentials: True < Access-Control-Allow-Methods: GET < Access-Control-Max-Age: 3600 < Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, remember-me ... But if I try to fetch the url from JavaScript, I see the following error in the console. Access to fetch at 'http://localhost:8000/api/v1/todo' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. -
How could i display that output on my project?
I am creating one project that is work like Sympy gamma. I am done mostly all code but my problem is how to display that output (given in image). I am used sympy build in function but not any function can give me that type of output I want that type of code: -
DRF Relation with two independent columns
I have DB structure like this: common_org: id, code, title special_org: id, code, address Okay. For this I've created models: class CommonOrg(models.Model): code = models.CharField() title = models.CharField() class SpecialOrg(models.Model): code = models.CharField(null=True) address= models.CharField() Now I want to output SpecialOrg as usual, but if I have CommonOrg.code == SpecialOrg.code, then attach CommonOrg to SpecialOrg like this: { "id": 1, "code": "XYZ", "address": "ADDRESS", "common_org": { "id": 2, "code": "XYZ", "title": "TITLE" } } Now I have solution with serializers.RelatedField: class CommonOrgField(serializers.RelatedField): def to_representation(self, value): class _CommonOrgSerializer(serializers.ModelSerializer): class Meta: model = CommonOrg fields = '__all__' representation = None try: common_org = CommonOrg.objects.get(code=value) representation = _CommonOrgSerializer(common_org).data except CommonOrg.DoesNotExist: pass return representation class SpecialOrgSerializer(serializers.ModelSerializer): class Meta: model = SpecialOrg fields = '__all__' common_org = CommonOrgField(read_only=True, source='code') But it looks ugly for me. So the question is: what is the right approach to implement it in DRF? Database is not mine and I cannot to alter it.