Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djanjo get values from related models
I have 2 models- class POWStage(Content): time_slot = models.OneToOneField( TaskTime, on_delete=models.CASCADE, help_text='Link to time slot describing the stage timescale', verbose_name='Time slot link', null=True, blank=True class TaskTime(Content): schedule_finish = models.DateTimeField( help_text='Scheduled finish date', verbose_name='Scheduled finish', blank=True, null=True, I would like to get the latest end date for a list of POwStages.... e.g. If I have 8 POWStages will have 8 corresponding schedule finish dates. I have tried the following with no success: pow_stage_list = POWStage.objects.get_stage_by_pow(pow_detail) task_time_list = TaskTime.objects.get_task_time_by_id(getattr(pow_stage_list,'time_slot')) and also: time_list = [] time_slot=[] time_finish[] for time_slot in pow_stage_list: time_list.append(time_slot) for entry in time_list: time_entry.append(entry.id) for finish_date in time_entry: time_finish.append(TaskTime.objects.get_task_time_by_id(finish_date)) to try and at least get the values of the finish dates in order to process them further (neither of which are working) Im thinking of getting the POWStages - using a filter - no problems 2)FOr each of the POWStages - loop through them to get the id of TaskTime I can do this ok -ish ( I manage to get the id which is returned as UUID() object. which I cannot then pass to get the TaskTime For each of the TaskTime get the value of schedule finish Iterate through the values to find the latest finish date. Im … -
DataError: value too long for type character varying(1024) TextField
Hello I am having this problem with my Django model. Field is HTMLField from TinyMCE which inherts from Django's TextField so it should be unlimited. Is it possible that db somehow truncated this length? I am inserting string which is about 4k characters long and I am using psql (PostgreSQL) 12.3 as my database. Thanks Model: class Category(Model): page_content_html=HTMLField(_("page content"), blank=True, null=False, default=''), ) HTMLField: class HTMLField(models.TextField): """ A text area model field for HTML content. It uses the TinyMCE 4 widget in forms. Example:: from django.db.models import Model from tinymce import HTMLField class Foo(Model): html_content = HTMLField('HTML content') """ def __init__(self, *args, **kwargs): self.tinymce_profile = kwargs.pop('profile', None) super(HTMLField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = { 'widget': TinyMCE(profile=self.tinymce_profile) } defaults.update(kwargs) # As an ugly hack, we override the admin widget if defaults['widget'] == AdminTextareaWidget: defaults['widget'] = AdminTinyMCE(profile=self.tinymce_profile) return super(HTMLField, self).formfield(**defaults) psql: Sloupec | Typ | Collation | Nullable | Implicitně -------------------+------------------------+-----------+----------+---------------------------------------------------------- id | integer | | not null | nextval('product_category_translation_id_seq'::regclass) language_code | character varying(15) | | not null | name | character varying(256) | | not null | long_name | character varying(512) | | not null | page_content_html | text | | not null | master_id | integer | … -
Can we loop through an array send from context data function to django template?
I am asking this question second time because last time I didn't get proper answer of this question. Well I think its hard to explain that what I am actually trying to do but let me try to explain briefly so you guys can understand better. Here in a picture you can see there is a list of followers and we can also see the list followers and following of each follower. I want run this kind to query. I am trying with the following code views.py def get_context_data(self, *args, **kwargs): context = super(FollowerView,self).get_context_data(*args, **kwargs) user = context['user'] user_com = User.objects.get(username=user) myfollowers = user_com.is_following.all() followers_Array =[] followerings_Array =[] for target_list in myfollowers: user_obj = User.objects.get(username=target_list) followers_obj = user_obj.is_following.all() print(followers_obj,'name o ki line') followerings_Array.append(followerings_Array) print(followers_obj,user_obj) followerings_obj = user_obj.userprofile.follower.all() followerings_Array.append(followerings_obj) print(followerings_obj,user_obj) print(followerings_Array,'arry one one one ') context['myfollowers_data']= followers_Array context['myfollowerings_data']= followerings_Array return context Well I am using two arrays in the code but i don't want to use them,right now i am not getting right output by returning arrays in context. If arrays are unnecessary than tell me the other way and tell me how can i show data the way i show you in the picture, I am sharing followers template here … -
Nginx Redirect 80 port insted of 443
I moved my server digitalocean to google cloud. I am using same config on my django website. I am using gunicorn and nginx. Website works perfect 80 port and I am trying enamble ssl and getting 301 Moved Permanently error. Problem is when I logged 443 port it redirects 80 port again and I have redirect command to redirect https connection. SO I am trying to connect https://example.com it redirect me with 301 code to http://example.com and nginx redirect it again https://example.com so It is a infinity loop. Here my nginx conf: It is workig with just 80 port server { server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; } server{ listen 443 ssl http2; server_name example.com; root /home/www/example/example; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/letsencrypt/live/example.com/fullchain.pem; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s; ssl_buffer_size 4k; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"; add_header X-Frame-Options sameorigin; add_header X-Content-Type-Options nosniff; add_header X-Xss-Protection "1; mode=block"; if ($host = www.example.com ) { return 301 $scheme://example.com$request_uri; } location /static/ { } location /media/ { } location / { … -
No Django Documentation On Subdomains
Django Documentation is silent on subdomains. Is that because they're not advised or all together unnecessary? -
Django + AJAX, need to click buttom twice to works
trying to develop a single page to perform the CRUD I chose to use nav-tabs, I am using AJAX to navigate between them and load the content, the part of creating an object is happening correctly, however, when I click in the edit button i need to click twice for him to execute the changeTAB () function that has the logic of switching to the CREATE / UPDATE tab. I do not imagine how to solve this problem. index.html: {%load static%} <!DOCTYPE html> <html lang="pt-br"> <head> <title>CRUD EXAMPLE</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Ordens de Serviço</h2> <ul class="nav nav-tabs"> <li class="active"><a class="js-list" data-toggle="tab" href="#list" > Ordens de Serviço</a></li> <li><a data-toggle="tab" class="js-create-update" data-url="{% url 'example:create' %}" id="tab-create-update" href="#create-update" > Create/Update</a></li> <li><a data-toggle="tab" href="#detail">Ver</a></li> </ul> <div class="tab-content"> <div id="list" class="tab-pane fade in active"> <h3>Equipamentos</h3> {% include 'example/list.html' %} </div> <div id="create-update" class="tab-pane fade"> <h3>Criar/Editar</h3> {% include 'example/create.html' %} </div> <div id="detail" class="tab-pane fade"> <h3>Detalhes</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> </div> </div> <script src="{% static 'js/example.js' %}"> </script> <script src="{% static 'js/bootstrap.js' %}"> </script> </body> </html> list.html: <table class="table" … -
Python 3.8: re.error: bad escape \s at position 3
I use django RegexValidator in a model field: city = models.CharField(max_length=30, blank=False, null=False, validators=[RegexValidator(r"^((\p{L}|\s)+)$")]) But I keep getting errors: bad escape \s at position 3 bad escape \p at position 3 I can't understand what's wrong. I've been reading online but nothing seems to solve this problem. I use Python 3.8 and Django 3.1.3. -
django-activity-stream with aggregation
I'm using django-activity-stream to create a feed of goals. A simplified version of Goal object is as follows: class Goal(models.Model): user = models.ForeignKey(User, related_name="goals", on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, related_name="goals_cheered") title = models.CharField(_("title"), max_length=80) There are 2 actions in place: the goal should appear in the feed once it's created and once it has been completed. Then users can like the goal, and here's where I'm stuck: adding the 'likes' count on the feed. This was the (failed) attempt that made the most sense to me so far: from django.db.models import Prefetch goal_qs = Goal.objects.annotate(likes=Count("liked_by")) prefetch = [Prefetch("action_object", queryset=goal_qs)] # in a `group` feed: qs = group.target_actions.all().prefetch_related("actor__profile").prefetch_related(*prefetch) This gives me a ValueError: "Custom queryset can't be used for this lookup." Maybe it's because django-activity-stream uses GFKs? How can I get a count of likes? Can I limit the content_type somehow? -
Django template not rendering time correctly
I have datetime object that I need to show in two different timezones. In the backend, I use astimezone() to change the original datetime tzinfo, this is the code: print("event.date_start: %s" % event.date_start) print("event.date_start.hour: %s" % event.date_start.hour) print("event.date_start.tzinfo: %s" % event.date_start.tzinfo) user_timezone = pytz.timezone("America/Guayaquil") print("user_timezone: %s" % user_timezone) event_user_timezone = event.date_start.astimezone(user_timezone) print("event_user_timezone: %s" % event_user_timezone) print("event_user_timezone.hour: %s" % event_user_timezone.hour) This code prints the datetimes correctly, event.date_start is in UTC time, 18hrs - event_user_timezone is in "America/Guayaquil", 13hrs. event.date_start: 2020-11-17 18:00:00+00:00 event.date_start.hour: 18 event.date_start.tzinfo: UTC user_timezone: America/Guayaquil event_user_timezone: 2020-11-17 13:00:00-05:00 event_user_timezone.hour: 13 However, when rendering the html, with this code: <p class="text-muted font-weight-bold" > {{ event.date_start|date:"h:i A" }} ({{ owner_profile.timezone }}) </p> <p class="text-muted font-weight-bold"> {{ event_user_timezone|date:"h:i A" }} {{ logged_user_profile.timezone }} </p> both times are displayed as 6pm. Why? -
How to dynamically select django model fields in views.py
I am using the DRF and I am trying to dynamically select fields from a django model object so that I can compare them to incoming data. I know how to do this manually def put(self, request): businessPage = BusinessPage.objects.get(id=request.data['id']) if businessPage.name != request.data['name']: businessPage.name = request.data['name'] if businessPage.address != request.data['address']: businessPage.address = request.data['address'] businessPage.save() res = { 'status': 'Success' } return Response(res) While this works it feels very messy and repetitive so I started looking for a way to dynamically check if the object field matched the incoming data. def put(self, request): businessPage = BusinessPage.objects.get(id=request.data['id']) for obj in request.data: if businessPage[obj] != request.data[obj]: businessPage[obj] = request.data[obj] businessPage.save() res = { 'status': 'Success' } return Response(res) I haven't been able to figure out the correct syntax to get the correct field from businessPage. Is this possible? Is there a better way to accomplish this task? Any help here would be much appriciated! -
Creating seperate URL endpoints for text files for a SaaS application
I have an architecture question so I don't need a specific answer but some guidance around a general approach. I am running a single Django App which has multiple GraphQL endpoints (multiple schemas on a single database). As an example I have the following endpoints all running from the same database: - example1.com/graphql - example2.com/graphql - example3.com/graphql I have a requirement to expose a text file which will be publicly accessible. e.g. - example1.com/textfile.txt - example2.com/textfile.txt - example3.com/textfile.txt Each text file will have its own data in it related to the customer URL. The problem I have is that at moment all of the URL endpoints write data to the same text file (since it is not stored on the schema). What I need is for them to write this data to distinct and seperate text files. What is the best way to resolve this problem - is it best to write this data straight to something like AWS S3 storage and create folders for each URL. In the case of S3 storage, is it possible to run append and delete operations on the text file directly. Any help is really appreciated. -
Individual use of password field names in Django All-Auth SignUpForm
I am trying to use Django All-Auth forms in a predefined Bootstrap template so I want my fields to match the styling. Therefore I want to use each field individually in the template such as; I have done this successfully for the LoginForm by adding custom attributes to the fields in my forms.py. class YourLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(YourLoginForm, self).__init__(*args, **kwargs) self.fields['login'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'form-control', 'name': 'loginUsername', 'id': 'loginUsername', 'placeholder': 'name@address.com', 'autocomplete': 'off', 'required data-msg': 'Please enter your email'}) self.fields['password'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'form-control', 'name': 'loginPassword', 'id': 'loginPassword', 'placeholder': 'Password', 'required data-msg': 'Please enter your password'}) And then referring to them with the following template tags. {{form.login}} {{form.password}} However, when I try and repeat this for the SignUpForm, I keep getting a key error which returns password1. The code I am using for this is outlined below. class MyCustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['email'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'textinput textInput form-control', 'name': 'email', 'id': 'id_email', 'placeholder': 'name@address.com', 'autocomplete': 'email', 'required data-msg': 'Please enter your email'}) self.fields['password1'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'textinput textInput form-control', 'name': 'password1', 'id': 'id_password1', 'placeholder': 'Password', 'autocomplete': 'new-password', 'required data-msg': 'Please enter your password'}) self.fields['password2'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'textinput … -
Use Django Channels without views
We want to use Django Channels to use Keras with Tensorflow as model. We've tried Flask but it's not usable for production. Then we tried Javas DeepLearning4J but also got to many problems. We want to solve it with Python. The problem is that Django is fullstack and we just need to use the websockets and execute our python code and send the results back. There is literally no example on Google how to do this. We do this because we got an Angular frontend, Spring Boot backend and another Spring Boot Application as connector between all services. We don't need the most functionalities of Django. It's very hard to find out what do. There is no @socket.route or something like this I think. Websocket using Django Channels this question was maybe a bit helpful but 3 years old and probably outdated. What is the way to achieve what we need? -
Django allauth - Signing up a new user while already logged in
I'm trying to customize allauth's default SignUpView and SignUpForm to allow me to create other users while already logged in. The default behavior prevents me from doing this: in other words, I can only sign up for a new account if I'm not authenticated. How do I override this behavior? I presume I'll have to override the SignupView in views.py but I'm not sure what to look for... Forms.py from allauth.account.forms import SignupForm class SubUserForm(SignupForm): USER_TYPES = [ (2,'customer'), (3,'vendor'), (4,'supplier') ] first_name = forms.CharField(max_length=45) last_name = forms.CharField(max_length=45) user_type = forms.CharField(widget=forms.Select(choices=USER_TYPES)) Views.py from allauth.account.views import SignupView class SubUserSignupView(SignupView): template_name = 'accounts/new_user_signup_form.html' form_class = SubUserForm view_name = 'sub_user_signup' sub_user_signup = SubUserSignupView.as_view() urls.py urlpatterns = [ path('sub_user/',views.sub_user_signup,name='sub_user_signup'), ] Context and extra info: My app allows for a 'parent' user to sign up multiple 'children' users using allauth. In my case, an organization can create several customers, merchants, suppliers, etc. When the the parent user creates a new user, a verification email is sent to the child user, who then activates his account and is prompted to enter a password. I use 2 signup forms; the default allauth signup (for parent accounts), and a customized signup form (for children accounts), which also extends … -
How to open a static file in views.py
I have a little issue with opening a csv file in my views.py Have tried the following 2 things: Open the file while it is in the same directory. Open the file from my static folder. None worked, the framework django is new for me. The code i have right know is a easy one :): from django.shortcuts import render from .models import shopify_orders as sb import csv def csv_converter(request): if request.method == 'POST': f = open(orders_export.csv) csv_f = csv.reader(f) f.close else: return render(request, 'serviceapp/csv.html') There are some tutorials explaining how to import csv data in models, but my csv file is a bit complex. Django directory Your help is apreciated ! -
python Django - lists large array: best way to store and retrieve data when wanted
I am working on a django project. After an operation i get a list of list items. the lenght of the array is 35,000 i have a model and table in django for this. But for me to bulk insert so many data looks time consuming. And i have to do this operation every 1hr. And what to speak of bulk updating so many entries next time. But the advantage of using database is i can filter the records the way i want and show the results. I am thinking instead to store the list in a file and retrieve it when wanted How can i do this effeciently with very little time. I also want to later extract some data based on some filters. Can we use numpy to get data like top50 of a particular column data if i import the list from the file as numpy array. -
How to solve Django python3 handler 'benchmark' error
I get this error of handler 'benchmark' and it seems that Django starts to run in "dev/proj/venv3/lib/python3.8" environment and converts to "/usr/local/Cellar/python@3.8/3.8.6/Frameworks.." not sure if there is a correlation. What can cause to that? Error: Exception ignored in thread started by: <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x10a7d9490> Traceback (most recent call last): File "/Users/username/.vscode/extensions/ms-python.python-2020.11.358366026/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py", line 827, in __call__ ret = self.original_func(*self.args, **self.kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/config.py", line 808, in dictConfig dictConfigClass(config).configure() File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'benchmark'``` -
Understanding the "args" of HttpResponseRedirect in views.pyfile in Django
I have these two functions in my views.py file: def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def search(request): if request.POST["q"] in util.list_entries(): return HttpResponseRedirect(reverse("entry", args=(request.POST["q"],))) else: return render(request, "encyclopedia/error.html") How we can understand the args of HttpResponseRedirect. Where this args passed in the entry function? I just need the behind the scene action of this "args". -
Failed to save using SelectMultiple in Django
I've got a problem to save in DB data using "Select Multiple Field" My code looks like: Models.py class Author(models.Model): author_name = models.CharField(max_length=100) author_lastname = models.CharField(max_length=100) class Book(models.Model): statement_title = models.CharField(max_length=1000, null=True, blank=True) author = models.ManyToManyField(Author,blank=True) Forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['__all__'] widgets = { 'title': forms.Textarea(attrs={'type': 'text', 'placeholder': 'Book title'} 'author': forms.SelectMultiple() } If I add a new object everything is saving but without the author, but if I save author in admin page I can display authors in book-detail view. Of course, I tried many solutions to solve this problem but nothing solved my problem. I know I'm made a mistake but I don't have an idea where... Maybe I should add something extra in views.py? I'll be very grateful for any tips and clues. -
Django Rest Framework - Filtering fields on serializer form
I have a form called "Contact" that is rendered from a serializer (APIView). That "Contact" model has two ForeignKeys: "City" and "State". All possible "Cities" are on the database already and it has a ForeignKey to determines the "State". What I need to do is to filter the form to show only the cities from that state that I select earlier and not all the cities on the table. Unfortunately I can't show the code because it's not on my computer, but I would be realy grateful if someone could give me any clue on how I can do that. -
Django showing the domaine name as example.com
my Django project doesn't display the correct domain name when i try to reset the password: its showing: "example.com" You're receiving this email because you requested a password reset for your user account at example.com. Please go to the following page and choose a new password: https://example.com/reset/MQ/ad8qye-29c2364e246e74a700774721674d01c1/ Your username, in case you’ve forgotten: ****** Thanks for using our site! -
When I make migrations to Django, all accounts are deleted
When I enter the commands python manage.py makemigrations and python manage.py migrate all accounts are deleted from the database. Perhaps the database is simply re-created -
Proper validation in Rest Api Django
I have this code in my serializers.py: from rest_framework import serializers from .models import OnlineMeeting def valid_name(dob): if dob.isalpha() is False: raise serializers.ValidationError("Name and surname must contain only letters") return dob class MeetingsListSerializer(serializers.ModelSerializer): class Meta: model = OnlineMeeting fields = '__all__' class OnlineMeetingDetailSerializer(serializers.ModelSerializer): start_time = serializers.TimeField() end_time = serializers.TimeField() owner_first_name = serializers.CharField(validators=[valid_name]) owner_last_name = serializers.CharField(validators=[valid_name]) participant_first_name = serializers.CharField(validators=[valid_name]) participant_last_name = serializers.CharField(validators=[valid_name]) def validate(self, data): if data['start_time'] > data['end_time']: raise serializers.ValidationError("finish must occur after start") return data class Meta: model = OnlineMeeting fields = '__all__' I don't inherit OnlineMeetingDetailSerializer from serializers.Serializer which is used for implenting your own validation, is it bad? Can I also write validation in classes which inherit serializers.ModelSerializer? -
Cant filter by category
I am trying to make a filtering system by category.When ever i try to click one of my category it always shows all the products but i want to show filter wise category list if i click Smart Phone it will only show me smartphone category products. Here is my Models.Py: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @staticmethod def get_categories(): return Category.objects.all() class Brand(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name def get_brands(): return Brand.objects.all() class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') price = models.FloatField() @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_products_by_category(category_id): if category_id: return Product.objects.filter(category=category_id) else: return Product.get_all_products() Here Is my Views.py: from django.shortcuts import render from .models import * # Create your views here. def index(request): products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) Please help i am very confused here and also got stucked :( -
Django, how to modify output of a related model serizlizer?
I have a model which has several ForeignKeys: class Employee(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="staff", null=False, blank=False) user = models.ForeignKey(to=User, blank=False, null=False, on_delete=models.CASCADE) roles = models.ManyToManyField(to=Role, blank=False) How do I use a fields from Company and User in Employee model? I need them for __str__.