Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-taggit: add tags
django-taggit==1.2.0 class Post(models.Model): tags = TaggableManager() # django-taggit ... def save(self, *args, **kwargs): super().save(*args, **kwargs) tag_slugs_list = strip_and_split(self.tags_aux) # tmp_tags = ', '.join('"{}"'.format(w) for w in tag_slugs_list) tmp_tags = Tag.objects.filter(slug__in=tag_slugs_list) self.tags.add(list(tmp_tags)) Problem Environment: Request Method: POST Request URL: http://localhost:8000/admin/posts/post/1/change/ Django Version: 3.0.8 Python Version: 3.8.0 Installed Applications: ['admin_aux', 'images.apps.ImagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'posts', 'sidebars', 'general', 'categories', 'marketing', 'home', 'authors', 'taggit', 'cachalot', 'widgets', 'code_samples', 'hyper_links', 'polls', 'applications', 'videos', 'quotations', 'languages', 'people', 'arbitrary_htmls.apps.ArbitraryHtmlsConfig', 'tweets', 'vk_posts', 'facebook_posts', 'instagram_posts', 'email_subscriptions', 'social_share', 'assessments', 'django_bootstrap_breadcrumbs', 'promo'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1641, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, … -
How to create a model with different price tags on different shirt sizes?
I created this simple model for product, but don't know how to set separate price for various product (e.g. shirt) sizes. class Product(models.Model): name = models.CharField(max_length=200, null=True) photo = models.ImageField(upload_to="products/%y/%m/%d/") cover_photo = models.ImageField(upload_to="products/%y/%m/%d/") price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) then show it in template like: thanks -
Clear Django Cache
I am using django 3.0. How do I clear cache in my django project. I have tried the below two methods given out as answers to questions in the this forum but they are not working out: python manage.py clean_pyc python manage.py clear-cache -
Resolve conflict in Django urls
I have the following in urls.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^nuevo/', views.nuevo, name='nuevo'), url(r'^populate/', views.populate, name='populate'), path('<uuid:sorteo_id>/', views.sorteo, name='sorteo'), # 1 path('<uuid:sorteo_id>/sortear', views.sortear, name='sortear'), path('<uuid:id_asignacion>/', views.asignar, name='asignar'), # 2 path('admin/', admin.site.urls), ] As you can see, 1 and 2 are basically the same path. The idea is that some UUIDs will execute one view and some others the other view. However, when I insert a UUID that must be match by 2, it enters 1 first and returns a 404. How can I make it so that the 404 indicates Django to keep exploring the urlpatterns? Or is there any workaround that enables me to use UUID paths for two different views? -
relation “django_session” does not exist when moving from sqlite to postgres
I have no idea what I'm doing wrong here. I am attempting to migrate my db over to postgres but I am running into this error: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se.. I deleted my old db, migrated over, tried doing a fake migration, I see the new tables created in pgadmin so I am not sure why I am getting this error. I also made sure that my pgadmin settings were in sync with my django settings. Furthermore, I can see my db's tables on pgadmin, but I do not see django sessions or my db on pgadmin. I do get a warning when I do manage.py run server You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): dating_app, sessions. Run 'python manage.py migrate' to apply them. And then when I run manage.py migrate, this is the traceback I get Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, … -
DJANGO TERMINAL - What does the text displayed mean, when a request is made
in the terminal whenever a request is made this is displayed: example : [09/Jul/2020 19:45:16] "POST /login/ HTTP/1.1" 302 0 [Datetime] [request.method] [url] [Http_Response] [number] what I dont understand is what this number in the end is. -
Heroku deployment error for python application
I tried to deploy my application with heroku platform, but i get this error in my logs. I am fairly new to this platform. Error logs: 2020-07-09T16:23:22.453419+00:00 heroku[router]: at=info method=GET path="/" host=secret-bayou-34598.herokuapp.com request_id=2ec15d58-aaf7-4c64-984e-98d6eb67d334 fwd="142.119.123.252" dyno=web.1 connect=1ms service=4ms status=404 bytes=388 protocol=https Let me know if you require more details on this. Can someone advise here please? Thank you for the help in advance. -
Import model Django in MondoDB shell whith Djongo
I want import models in django in MondoDB shell. My model class in Django class User(models.Model): name = models.CharField(max_length=20) I use in mongo shell it from app.models import User Error: [js] SyntaxError: missing ; before statement @(shell):1:6 -
Sending QueryDict object from Javascript (without form?)
How can i send information from Javascript to a Django view in a QueryDict object without using forms? For example, this is my dictionary in JS: const postDict = { 'request_name':'change-extra-fields', 'type': 'increase', 'id': droppedElId, } And this is my view (and expected result of print) class ExampleView(View): def post(self, request, pk, *args, **kwargs): if request.POST['request_name'] == 'edit-main-fields': task.update_from_request(**request.POST) elif request.POST['request_name'] == 'change-extra-fields': print(request.POST) <QueryDict: {'request_name': ['change-extra-fields'], 'type': ['increase'], 'id': ['6'], 'csrfmiddlewaretoken': ['0NHXB1Nn4uimjNXARjq9wfVdCLjVFcBBDTiGIBHt4Mjcqu3YPx5vqFLJvHT4ra3b']}> My current solution is to make a form element with every piece of information and submit.. However, i'm not sure if there's a faster / more correct way of doing this Current solution: const sendCustomForm = function (valuesDict) { const ghostForm = document.createElement('form') ghostForm.method = 'POST' ghostForm.action = document.location.pathname valuesDict['csrfmiddlewaretoken'] = csrftoken Object.keys(valuesDict).forEach(key => { const newInput = document.createElement('input') newInput.setAttribute('name', key) newInput.setAttribute('value', valuesDict[key]) ghostForm.appendChild(newInput) }) document.body.appendChild(ghostForm) ghostForm.submit() } sendCustomForm(postDict) This solution works but i'm not sure if that's the most correct. Recently i asked for help on how to setup JSON post-requests with Javascript but i kind of need to have the information on a QueryDict, otherwise the if-condition on my post view will fail. -
Facing Exception Type: OperationalError in the django administration page
I am currently working on my first python/django project and on the django administration page i encountered the following problem: OperationalError at /admin/movies/genre/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/movies/genre/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old -
How to define a function to get an field element of a Marshmallow Schema while still serialising through a nested Schema
So I have a Nested Many Schema (eg Users) inside another Schema (eg Computer). My input object to be deserialised by the Schema is complex and does not allow for assignment, and to modify it to allow for assignment is impractical. The input object (eg ComputerObject) itself does not contain an a value called "Users", but nested in a few other objects is a function that can get the users (eg ComputerObject.OS.Accounts.getUsers()), and I want the output of that function to be used as the value for that field in the schema. Two possible solutions exist that I know of, I could either define the field as field.Method(#call the function here) or I could do a @post_dump function to call the function and add it to the final output JSON as it can provide both the initial object and the output JSON. The issue with both of these is that it then doesn't serialise it through the nested Schema Users, which contains more nested Schemas and so on, it would just set that field to be equal to the return value of getUsers, which I don't want. I have tried to define it in a pre-dump so that it can … -
Combine multiple lists inside dictonary in python
I have a dictionary which has multiple lists. I want to try and combine lists within the dictonary that has similar names. Category: Western Item Count: 2 ['Zurie Cake', 4, 396.0] ['Zurie Cake', 1, 99.0] --------------------- Eg: Combine the Zurie Cake to ['Zurie Cake', 5, 495] Thank you in advance. -
Angular 9 front/corsheaders django 3 back - appending the CORS headers to the request
having the problem to find a way how to configure properly front end app in Angular 9 consuming back REST webservice. On the remote server with the static IP i run my angular dev server with (i know it is only for dev purposes but i want to get rid of this error first) ng serve --host 0.0.0.0 --port 80 so i can access it from the outside. then i have my django app also with the dev server at 127.0.0.1:8000 In the angular service.ts file i am trying to inject the header export class FlightService { httpOptions = { headers: new HttpHeaders({ 'Access-Control-Request-Method':'GET', 'Access-Control-Request-Headers':'origin, x-requested-with, accept' }) }; private endpoint = 'http://127.0.0.1:8000/services'; constructor(private http: HttpClient) { } //GET All Services getAllServices(): Observable<any>{ return this.http.get(this.endpoint, this.httpOptions) } } In the settings.py of my django backend i have put at the top the corsheaders module: 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... and allowed all the host (after trying many things with whitelist which none of worked: CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_METHODS = [ # 'DELETE', 'GET', 'OPTIONS' #'PATCH', #'POST', #'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'x-forwarded-for' ] But I fail all the time. After i added the … -
Generic "Get Current Admin" for Settings in Django
I'm new to Django so maybe this is a naïve or misguided question, but in my settings.py, I'd like to assign a variable to a generic accessor for the current admin's username (or any unique identifier for the admin, e.g. email). I envision it'd look something like: MY_SETTTING = 'django.something.get_admin_username()' I haven't received any help on this site with django-filer specific issues at this point, but my goal specifically is to set the "upload_to" property within filer to the admin's username, so each admin uploads to a directory named after them. -
Not Understanting Django Forms and There use, Is there a way to ignore them and still save files uploaded in the forms?
I'm trying to make a website using django which I'm not familiar with. Not know what django forms do I wrote my html file purely in html and now I'm having difficulty trying to save uploaded files because django won't let me save them manually. I tried to bypass this with no luck, so I think that now I have to rewrite my html file in django html template, so I can save files. I have an html file like this: html <div class="w3-container w3-white"> <select class="w3-select" name="request_function" id="request_function" > <option id="faces_embedding" value="faces_embedding" style="" onclick="pagechange()">faces_embedding</option> <!-- <option id="faces_model" value="faces_model" style="" onclick="pagechange()"> faces_model </option> --> <option id="image_recognizer"value="image_recognizer" style="" onclick="pagechange()">image_recognizer</option> <option id="video_recognizer" value="video_recognizer" style="" onclick="pagechange()">video_recognizer</option> <option id="stream_recognition" value="stream_recognition" style="" onclick="pagechange()">stream_recognizer</option> <option id="help" value="help" style="" onclick="pagechange()">help</option> </select> </div> <div id="AddFaces" style="visibility: visible; display: block;"> <div class="w3-row-padding" style="margin:0 -16px;" > <div class="w3-half"> <input type="radio" name="input_method" id="input_method_0" onclick="datachange()" checked value="input_method_0"> <label>Add A Database</label> </div> <div class="w3-half"> <input type="radio" name="input_method" id=input_method_1" onclick="datachange()" value="input_method_1"> <label>Add A Face</label> </div> </div> <div class="w3-row-padding" style="margin:0px -10px;"> <div id="dataset" class="w3-half w3-margin-bottom" style="visibility: visible; display: block;"> <label>Dataset Path</label> <input class="w3-input w3-border" type="text" placeholder="directory path" name="dataset_path" id="dataset_path" required > </div> <div id="face" style="visibility: hidden; display: none;"> <div class="w3-half w3-margin-bottom"> <label>Images Path</label> <input type="file" … -
force django to send reset password email even if usable password is not set for a user
Django silently fails and does not sends reset password emails if a usable password is not set for a user. How do we override this condition? Django assumes that that LDAP auth needs to be used in case password is not set. But in our case, users can login via social auth, which does not sets the password for users. Reseting the password via email is the the only option if they wish to login using an email and password. How do we do this? One possible method is to set a random password at the time of user registration, but we do not want to do that since it is not very intuitive. References: https://stackoverflow.com/a/53830188/842837 https://stackoverflow.com/a/39122137/842837 -
Django Rest Framework comment on post api
I am developing rest apis using drf and I am trying to show comments on post detail api. I looked nested serializers and couldn't manage to implement to my project. How can I use nested serializers to show comments? and I got this error: NameError: name 'CommentSerializer' is not defined there is my code: -comment model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) content = models.TextField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class Meta: ordering = ('-created_at',) def __str__(self): return f'Comment by {self.author.username} on {self.post}' def children(self): return Comment.objects.filter(parent=self) @property def is_parent(self): if self.parent is not None: return False return True -post model class Post(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location,blank=True, null=True) title = models.TextField(max_length=30, null=True, blank=True) slug = models.SlugField(unique=True, blank=True) created_at = models.DateTimeField(default=timezone.now) star_rate = models.FloatField(default=0.0) def __str__(self): return self.slug def get_absolute_url(self): return reverse('post-detail', kwargs={'slug':self.slug}) -serializers.py class PostDetailSerializer(serializers.ModelSerializer): image = SerializerMethodField() author = SerializerMethodField() comments = CommentSerializer(source='comments.content') class Meta: model = Post fields = ('author', 'image', 'title', 'created_at','star_rate', 'slug', 'comments') def get_image(self, obj): try: image = obj.image.url except: image = None return image def get_author(self, obj): return obj.author.username -
How to reduce the filters on admin page after choosing the first filter?
I have a setup containing 3 models, my goal is to filter the blog entry page by Group and subsequently the Author filter should only list Authors who are in the Group. To reword that "Can I refresh the Authors list once I filter by a Group?" I've been trying to learn about custom filters inheriting from SimpleListFilter but the examples I find all have static If statements basing them on a couple of inputs. This one needs to be dynamic as new groups are added. class BlogEntry(models.Model): author = models.ForeignKey(Author, on_delete=CASCADE) class Author(models.Model): group = models.ForeignKey('Country', on_delete=CASCADE) class Group(models.Model): .... class BlogEntryAdmin(admin.ModelAdmin): list_filter = [ ('author__group', admin.RelatedOnlyFieldListFilter), ('author', admin.RelatedOnlyFieldListFilter), -
In Django, restrict users to particular urls
I have the following urls in my Django application: path('rooms/<room_id>',views.home,name='home'), models: class ChatRoom(models.Model): eid = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=25) views def rooms(request): room = UserProfile.objects.filter(user=request.user).values()[0]['room_id'] rooms = ChatRoom.objects.all().values() user = User.objects.filter(username=request.user) return render(request,'chat/rooms.html',{'rooms':rooms,'room_user':room}) Here <room_id> is variable i.e it depends on the eid of a Room model. A user can be a part of only one room. Therefore, the user can access only one <room_id>, let us say '4'. So, a user can access only rooms/4/. How can I restrict the user from entering into other URLs e.g. /rooms/5/ ?. -
How to change the validation Django applies on model.objects.create?
I made a model which has a DateField. I need to create some instances of this model by that field from the console for design reasons, but whenever I try with model.objects.create(date=MY-DATE-IN-EU-FORMAT) Django is raising a validation error. Example: from main import models models.Rental.objects.create(stop_date='25-12-2020') . . . django.core.exceptions.ValidationError: ['“25-12-2020” value has an invalid date format. It must be in YYYY-MM-DD format.'] I want Django to accept date in a EU localized format (dd/mm/aaaa or dd-mm-aaaa), so as suggested by some answers I found on here and by the official docs i updated my django.settings as this: TIME_ZONE = 'Europe/Rome' DATETIME_FORMAT= '%d-%m-%Y %H:%M' DATE_FORMAT= '%d-%m-%Y' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' # CUSTOM AUTH_USER_MODEL = 'users.CustomUser' # new DATE_INPUT_FORMATS= [ '%d-%m-%Y', '%d/%m/%Y', # '25-10-2006' , '25/10/2006' '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] My model is: class Rental(Model): start_date = models.DateField(help_text=_('inserire la data … -
File upload using Django+React+Redux(RSAA)
I'm new to the web, I encountered the problem of downloading a file from frontend. Downloading the file via the backend API is successful, and when trying from the site, no action. I saw a couple of similar questions here, but could not find a suitable answer my API method def get(self, request, format=None): data = tablib.Dataset(*data, headers=headers) response = HttpResponse(data.xls, content_type='multipart/form-data') response['Content-Disposition'] = "attachment; filename=file.xls" return response thunk: export const Unloading = (name, type_data) => { return { [RSAA]: { endpoint: `${settings.API_URL}/${settings.API_VERSION}/unloading`, method: 'POST', headers: withAuth({'Content-Type': 'application/json'}), body: JSON.stringify({'name': name, 'type_data': type_data}), types: [UNLOADING_REQUEST, UNLOADING_RECEIVE, UNLOADING_FAILURE] }, } } enter code here and in the presentation component, respectively, a button for calling thunk, and it is not clear how to save the file <button className="style" onClick={this.handleSubmitUnloading}>Unload to Exel</button> -
Display specific number of random items in array with For loop
I am working with a template in django trying to dispaly a specific number of random items from an array of related objects for now i display all items in the array what changes can i make {% for pdt in object.pdt_set.all %} <div class="ps-product ps-product--simple"> <div class="ps-product__thumbnail"> <a href="{% url 'pdtdetail' pdt.id %}"><img src="{{ pdt.image.ur }}"alt=""></a> <div class="ps-product__badge">-16%</div> <ul class="ps-product__actions"> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Read More"><i class="icon-bag2"></i></a></li> <li><a href="#" data-placement="top" title="Quick View" data-toggle="modal" data-target="#product-quickview"><i class="icon-eye"></i></a></li> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Add to Whishlist"><i class="icon-heart"></i></a></li> <li><a href="#" data-toggle="tooltip" data-placement="top" title="Compare"><i class="icon-chart-bars"></i></a></li> </ul> </div> <div class="ps-product__container"> <div class="ps-product__content" data-mh="garden"><a class="ps-product__title" href="product-default.html">{{ pdt.name }}</a> <div class="ps-product__rating"> <select class="ps-rating" data-read-only="true"> <option value="1">1</option> <option value="1">2</option> <option value="1">3</option> <option value="1">4</option> <option value="2">5</option> </select><span>01</span> </div> <p class="ps-product__price sale">$ {{ pdt.price }} </p> </div> </div> </div> {% endfor %} -
Python + Django URL & View errors when attempting to POST to_do item
This is my first attempt at utilizing Django and I've run into an issue with the URL & Views files. I created a project called "reading". Within that project, I created two apps, "products" and "speech". Within the "speech" urls.py file, I have the following code: from django.urls import path from speech.views import todoView, addTodo urlpatterns = [ path('todo/', todoView), path('addTodo/', addTodo) ] In the views.py file I have the following code: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .models import TodoItem def todoView(request): all_todo_items = TodoItem.objects.all() return render(request, 'todo.html', {'all_items': all_todo_items}) def addTodo(request): new_item = TodoItem(content = request.POST['content']) new_item.save() return HttpResponseRedirect('/todo/') In the project folder, within the urls.py file, I have: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')), path('speech/', include('speech.urls')) In the project folder, within the "templates" directory, I have a "todo.html" file with: <h1>This is the todo page</h1> <ul> {% for todo_item in all_items %} <li>{{ todo_item.content}}</li> {% endfor %} </ul> <form action="/addTodo/" method="POST">{% csrf_token %} <input type="text" name="content" /> <input type="submit" value="Add" /> </form> When I attempt to add an item to the todo model, I get this error "The current path, addTodo/, didn't match … -
Django ManyToOne relation in serializer get the object who is calling
`Hello My code class MyRelatedModel(models.Model): related_model_instance = models.ForeignKey(MyModel........) class MyModel(models.Model) [....] serializer class MyRelatedModelSerialzier(serializers.ModelSerializer): related_models_instance = MyModelSerializer() class Meta: model = MyRelatedModel fields = ['id', 'name', 'related_model_instance'] class MyModelSerailzier(serializer.ModelSerializer): parent_id = serializer.SerializerMethodfield('get_parent_id') def get_parent_id(): # How to get the id of the object which is being serialized? # In order to make some calculations return 'foo' class Meta: model = MyModel fields = ['id', 'name', 'parent_id',.... Question I have 2 models with relation one to Many In the MyModelSerializer I need to know which is the objects calling, because I need it to calculate some values before returning a response. I thought of overriding to_representation of the MyRelatedSerializer, but it wont work with drf-yasg... -
how to convert this model into non editable model in admin of django?
I create a model but I need a non-editable model. When I visit the model it's just displaying text, not giving any option of update the record in admin panel. model.py class Contact(models.Model): name = models.CharField(max_length=160) email = models.EmailField() subject = models.CharField(max_length=255) message = models.TextField() def __str__(self): return self.subject While searching I get information about readonly but I do not still understand how to use it.