Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy multiple django apps on apache in Windows?
I want to deploy multiple django apps on apache on Windows but only know how to deploy one. Overriding the localhost of the Wamp Server I can deploy the app without problem but I need to deploy more and don't know how. I've sehen virtual hosts and think are good but don't know how to configurate them. Anyone know how can I do this? Thanks in advance. -
django rest framework is removing "+" from datetimes
I have a simple django get view: @api_view(["GET"]) @permission_classes([IsAuthenticated]) def test_endpoint(request): print(request) print(request.GET) The result of this - <rest_framework.request.Request: GET '/api/test_endpoint?start=1969-12-31T19:00:00+05:00&end=2023-01-16T21:22:52-05:00'> <QueryDict: {'start': ['1969-12-31T19:00:00 05:00'], 'end': ['2023-01-16T21:22:52-05:00']}> If you notice start for some reason is cleansing out the + in the datetime. Thus causing an incorrectly formatted datetime object. I have no interest in changing my formatting, but rather fixing why django rest framework is removing the +. You can clearly see in the actual GET request that the + is properly in the string. Any ideas on how to fix this so start value would be '1969-12-31T19:00:00+05:00' instead of '1969-12-31T19:00:00 05:00' without "fixing" it after the fact? (I want the request.GET object to be correct, I don't want to fix the values after retrieving them from request.GET) -
Django: can't delete item in Model inherting django-mptt
in models.py, i've the following code: import uuidfrom django.db import modelsfrom django.db.models import Qfrom mptt.models import MPTTModel, TreeForeignKey from company.models import Account class Plan(MPTTModel): id = models.UUIDField(primary_key=True, unique=True, editable=False, default=uuid.uuid4) coding = models.CharField(max_length=50) title = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') entreprise = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.parent is not None: coding = str(self.coding) parent = str(self.parent) if not coding.startswith(parent): raise ValueError('Le code ne correspond pas au code parent {}'.format(parent)) if len(coding) == len(parent): raise ValueError("Le code ne peut pas être identique au code parent {}".format(parent)) if self.parent.get_level() == 0 and self.entreprise is not None: raise ValueError("Vous ne pouvez pas associer une entreprise à ce niveau") else: if self.entreprise is not None: raise ValueError("Vous ne pouvez pas associer une entreprise à ce niveau") class MPTTMeta: order_insertion_by = ['coding'] and in my views.py, i've this code: @api_view(['DELETE']) def delete_plan(request): try: id = request.data['id'] entreprise = request.data\['entreprise'\] plan = Plan.objects.get(id=id, entreprise=entreprise) context = { 'message': 'Le compte {} - {} a été supprimé de votre plan comptable avec succès'.format(plan.coding, plan.title) } plan.delete() return Response(context, status=status.HTTP_200_OK) except Plan.DoesNotExist as e: context = { 'message': "Ce compte n'existe pas dans votre plan comptable" } return Response(context, … -
Django: Retrieving tweets followed by current user
I currently have the following Models set up User Model class User(AbstractUser): pass Follower Model class Follower(models.Model): # user is following userFollowing user = models.IntegerField() userFollowing = models.IntegerField() Tweet Model class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tweets") content = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) I want to get a QuerySet of Tweets consisting of Tweets from Users that the current user follows. I managed to get the following but I'm not sure if there's a better way to write the Query # Retrieve all users followed by current user usersFollowedByCurrentUser = Follower.objects.all().filter(user=request.user.id) # Retrieve all Tweets tweets = Tweet.objects.all().filter(user_id__in=Subquery(usersFollowedByCurrentUser.values('userFollowing'))) Appreciate any feedback/advice -
Comment Mixin for Django. Why is CommentPost defined like this?
I am a beginner in Django, and I was reading WS Vincent's Django for beginners. In the second to last chapter, he writes the following code. He's creating a view that allows for comments that can handle GET and POST requests without mixing FormMixin and his created ArticleDetailView. I understand all of that, but what I don't understand is why it was constructed like this? Can someone explain what self.object and self.get_object are in this example? Also, why do we save twice in the second method? Thanks!: def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) -
The model has two identical many-to-many relations through the intermediate model
from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64) python manage.py makemigrations app ERRORS: The model has two identical many-to-many relations through the intermediate model -
Django - Adding a 2nd form to a page dynamically
I'm looking for guidance on creating a dynamic form in Django that changes depending on which participants are in a meeting. The background is as follows: The app is used to track meeting scores across several teams, each with 4-8 members. Over the course of a few days a team may have 6 meetings. For each meeting the Team will elect 1 or 2 members to be meeting Participants. Each meeting requires the team to put forward members such that over the course of the training all team members have participated in one or more meetings. For each meeting all other team members are "Observers". The challenge I'm facing is how to dynamically insert a form or form fields for each of the Observers given that the number of observers may be anything from none to 6. The idea is to allow Observers to "rate" the meeting and record this result in the Observer model. The ScoreCreate view correctly sets the 1st participant and populates the "Other Participant" dropdown with all other team members. HTMX in the template passes the 1st and if selected "other participant" to the observers function which is then able to sort out who the observers … -
How to create a "CHOICES" filter field from a model based on unique values from another model?
Good day! I would be very grateful for any help. I have two related tables - Django models. The field "nomer_kotl = models.TextField()" has an association with another model. And as "choices = CHOICES" I would like to have "unique" values from the "Nomerkotelnoy(models.Model)" model. How can I make the "choices = CHOICES" of the model (EmployeeModel(models.Model)) get the values from the field "nomer_kotl = models.TextField()" of the model (Nomerkotelnoy(models.Model)) ? When creating a form for selecting data from a model table for display in an application on a site. - I think how can I make the form have a choice in the form of "select dropdown" - the choice of only one value. class Nomerkotelnoy(models.Model): nomer_id = models.IntegerField(primary_key=True) nomer_kotl = models.TextField() def __str__(self): return self.nomer_kotl CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class EmployeeModel(models.Model): empid = models.IntegerField(primary_key=True) empname = models.CharField(max_length=50) salary = models.IntegerField() joindate = models.DateField() nomer_kotl = models.ForeignKey(Nomerkotelnoy, default=1, on_delete=models.CASCADE, choices = CHOICES) class Meta: db_table = "employee" -
How to reorder the form elements when rendering in template in Django
When rendering a form how do I reorder the form elements in the template? In the above form how do I change the position of the 'Sort by' element. If suppose I want to position it to the top right, how will I do it? forms.py class RoomsForm(forms.Form): numbers = forms.CharField(validators=[int_list_validator()], required=False, max_length=4000, widget=forms.TextInput(attrs={'class': 'unbold-form'})) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) categories = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'unbold-form'}), choices=ROOM_CATEGORIES, ) ROOM_CAPACITIES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacities = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'unbold-form'}), choices=ROOM_CAPACITIES, ) advance = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={'class': 'unbold-form'}) ) SORT = ( ('number', 'Numbers: Ascending'), ('-number', 'Numbers: Descending'), ('capacity', 'Capacities: Ascending'), ('-capacity', 'Capacities: Descending'), ('advance', 'Advance: Ascending'), ('-advance', 'Advance: Descending'), ) sort_by = forms.ChoiceField( required=False, widget=forms.Select(attrs={'class': 'unbold-form'}), choices=SORT, ) HTML Template <h2>Search</h2> <form method="POST" id="bold-form"> {% csrf_token %} {{ form.as_p }} <input type="submit" class= "submit submit-right" value="Search" /> </form> -
Best GUI to run python [closed]
I am building an object detection tool using the Yolo algorithm(Which contains many dependencies). my python script works successfully. My question is, what would be the best GUI to implement with python? I am trying to build a commercial app that anyone on a windows computer can run without having to download python and all its dependencies. Here are some of the ideas that come to mind. Build a C# application form application and combine it with python with either ironpython or compile the python app into an exe and then fetch its output and display it on C# form. I can maybe create a Django web application. If you would have any suggestions from experience, I would be extremely grateful. -
django custom users permissions
i working in big project (first time for me ) for schools chain what is the best setup for Custom model for permission to get different type of permissions i need :- CEO permission >> permissions for all schools and department school manager >> permission for his school only teacher >> permissions for his department only student >> permissions limited permissions for his courses allowed only in his school the privilege tree for me is complected ,, so i cant figure what should i implement to don't waste a lot of time -
How to autoescape form value in UpdateView in Django
I have a form where I use TinyMCE on textareas because I need my users have the option to style the text they enter. It works fine and saves the html codes to the model. I use the safe mode to show the values in the way the users entered it and it works fine but I have an UpdateView where the user can edit what was entered. My problem is that if the user uses the UpdateView to change whet he entered he see the html code in the UpdateView like below and I have no idea how to solve this. <h2>Text</h2> <b><p>More text</p></b> Can I autoescape off the form? I tried these methods but not worked: <div class="container"> <h2>Edit report</h2> <h5 class="my-3">You can edit your report here:</h5> {% autoescape off %} {{ form.as_p|safe }} <!-- tried it separately --> {% end autoescape %} <button type="submit" class="btn btn-warning my-3">Submit changes</button> -
How we can use model objects in ModelSerializer?
I have to create an endpoint to make a customer subscribes to a chef. The subscription model has two FK fields chef and customer. I created this serializer: class SubscriptionSerializer(serializers.ModelSerializer): chef = serializers.SerializerMethodField("get_chef") customer = serializers.SerializerMethodField("get_customer") class Meta: model = Subscription fields = [ "id", "chef", "customer", ] def get_chef(self, *args): return Chef.objects.get(pk=self.context.get("chef")) def get_customer(self, *args): return User.objects.get(pk=self.context.get("customer")) I want to have one endpoint like this: customer/chef/<int:chef_id>/subscribe So in view.py I used ModelViewSet: class CustomerSubscribeChefView(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SubscriptionSerializer def get_serializer_context(self): context = super(CustomerSubscribeChefView, self).get_serializer_context() context.update({"chef": self.kwargs['chef_id']}) context.update({"customer": self.request.user.id}) return context def get_queryset(self): return self.request.user.subscription_set def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( {"msg": "Chef is subscribed!"}, status=status.HTTP_201_CREATED ) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({"msg": "Chef is unsubscribed!"}, status=status.HTTP_200_OK) when I try to send a post request I got this error: django.db.utils.IntegrityError: NOT NULL constraint failed: core subscription. chef _id I've tried to use my custom serializer so I've updated SubscriptionSerializer to be like this: class SubscriptionSerializer(serializers.ModelSerializer): chef = ChefListSerializer customer = CustomerSerializer class Meta: model = Subscription fields = [ "id", "chef", "customer", ] But I don't know how to serializer chef and customer objects. What is the … -
Django return class attribute based on object status in database
I am new to django and trying to learn. Looking to see if there is a better way to produce the result wanted. See my example below: application_list.html - Table Data <td><span class="badge {% if app.application_status_id == 1 %} bg-secondary {% elif app.application_status_id == 2 %} bg-success ">{{ app.application_status }} </span> </td> See here I am setting the class based on the value of the application status id from the database. Instead of having multiple if statements, is it possible to place this code elsewhere to process and return the class attribute back to line? I have tried looking at views.py for the application, but unable to determine how this works. My thoughts were to create a function to return a context value for application_list. application/views.py def application_list(request): """List of all applications""" template = 'application/application_list.html' applications = Application.objects.all() context = { 'applications': applications, } return render(request, template, context) -
Android app written in kotlin with the volley library fails to call my backend, which was written in python with django
so as the post says, i'm making an app, for which i have a server/rest api written with the django framework. When i try to call the api using volley, i fail to get any response, and i don't see it show up on my server's dashboard The server is running on my local machine, and the app is running on an emulator, since i'm using android studio i'd like to send a request and display the response in a textview on the app, for now thats all i need to continue onto the next part What ends up happening instead is that it seems to not even hit my server, the app displays the text i set for if the request fails, adn it doesn't show up on the dashboard of my server -
How to implement a model like "playlist", which is in relation with multiple models like "track"
I have multiple independent video models (let's call them A, B, and C) with different features and I want to design an ordered playlist model to be able to add these videos to the playlist in a desired order. I already studied the [django documentation many_to_many example][1], but, I don't think it is a good idea to implement such a model with multiple many_to_many relationships. [1]: https://docs.djangoproject.com/en/4.1/topics/db/models/#intermediary-manytomany:~:text=something%20like%20this%3A-,from%20django.db%20import%20models%0A%0Aclass%20Person(models.Model,()%0A%20%20%20%20invite_reason%20%3D%20models.CharField(max_length%3D64),-When%20you%20set -
ModuleNotFoundError: No module named 'tutorial'
I am trying to learn how to set up a Django web server using an AWS Ubuntu Machine, I have solved a few of my problems but now I am getting hit with the ModuleNotFoundError: No module named 'tutorial' and I am also getting the 500 internal server error. Here is what I think the necessary code is: error.log GNU nano 6.2 /home/ubuntu/django-project/site/logs/error.log [Mon Jan 16 19:35:18.750368 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Failed to exec Python script file '/home/ubuntu/djang> [Mon Jan 16 19:35:18.750441 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Exception occurred processing WSGI script '/home/ubun> [Mon Jan 16 19:35:18.750979 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] Traceback (most recent call last): [Mon Jan 16 19:35:18.751031 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/src/tutorial/wsgi.py", line 16, in <mod> [Mon Jan 16 19:35:18.751037 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] application = get_wsgi_application() [Mon Jan 16 19:35:18.751043 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751048 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] django.setup(set_prefix=False) [Mon Jan 16 19:35:18.751053 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751058 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) … -
Why is my Django template not displaying on my webpage?
I have two classes in my models, two defs in views and one template in one app. Just one of the functions doesn't work properly. Everything else works fine. I double checked everything but didn't find the issue. Below the code: Models from django.db import models class BildTextMarkt(models.Model): fotomarkt = models.ImageField(upload_to='images/') text = models.TextField(blank=True, max_length= 512) views def bildtextmarkt(request): all_maerkte = BildTextMarkt.objects.all() context = {'my_maerkte':all_maerkte} return render(request, 'maerkte/maerkte.html', context) templates {% for maerkte2 in my_maerkte %} <div class="bild">{{ maerkte2.fotomarkt }}</div> <div>{{ maerkte2.text }} </div> {% endfor %} Thank you for any hints. -
How to automatically set the value of a many to many field in Django
I have a blogPost model which has authors, reviewers and tags. The three fields are part of a ManyToMany relantionship. But I want to set the value of each field in programatically way. Rigth now I can do this: blog.authors.set(qs) This works, but this mean that I have to repeat the same line of code for each field. I was thinking something like this def set_values(blog,field,new_values): setattr(blog, field, new_values) that didn't work and it raises and exception telling me to use the set method. But is there a way to implement something like this? -
Why does my Django application using websocket not work when deployed?
So I created an online chat site using Django and Javascript and I'm having trouble making it work when I deploy it on a live server. It works perfectly fine locally though. Whenever I try to send a message on the chat on the deployed server I get a "Firefox can’t establish a connection to the server at ws://url". I think this is a websocket issue. My asgi.py file is as follows : import os import rooms.routing from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( rooms.routing.websocket_urlpatterns ) ) }) And my consumers.py file : import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from .models import Room, Message class Consumer(AsyncWebsocketConsumer): async def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): data=json.loads(text_data) msg=data['message'] username=data['username'] room=data['room'] if msg.isspace()==False and msg != "" : #On ne veut pas stocker ou envoyer les messages vides ou ne contenant que des espaces await self.storeMsg(msg,username,room) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatmsg', 'message': msg, 'username':username, 'room':room, } ) async def … -
The website does not remove elements, despite the prescribed code
I have a code that can add, change or delete data. Adding and changing works well, but deleting doesn't work. There is simply no response to pressing the button. What is the reason? views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from .forms import PostForm, EditForm from django.urls import reverse_lazy class DeletePostView(UpdateView): model = Post template_name = 'delete_post.html' fields = '__all__' sucсess_url=reverse_lazy('home') urls.py from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView urlpatterns = [ #path('', views.home, name="home"), path('', HomeView.as_view(), name="home"), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), ] delete_post.html {% extends 'base.html' %} {% block content %} <head> <title>DELETE</title> </head> <h3>Delete: {{post.title}}</h3> <div class="form-group"> <form method="POST"> {% csrf_token %} <button class="btn btn-secondary">Delete</button> </form> {% endblock %} -
Django login form not authenticating. using customUser model and customuserform
My login form will not authenticate. when i login using superuser it authenticates but when i login with user model it does not login. models.py class CustomUser(AbstractUser): # user = models.OneToOneField( # to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default="") username = models.CharField(max_length=150, blank=True) email = models.EmailField(_('email address'), unique=True, default=None) first_name = models.CharField(max_length=150) ic_no = models.IntegerField(null=True, blank=True) gender = models.CharField( max_length=150, choices=Gender_Choice) year = models.CharField( max_length=150, choices=Student_Standard) school_name = models.CharField(max_length=150) referral_id = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # source = models.CharField(_('source'), max_length=50, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.first_name views.py def login_view(request): error = None if request.method == 'POST': form = CustomLoginForm(request.POST) if form.is_valid(): user = authenticate( request, username=form.cleaned_data['email'], password=form.cleaned_data['password']) if user: login(request, user) return redirect('main:home') # if not user.is_active: # messages.warning(request, ( # f"It's look like you haven't still verify your email - {user.email}")) # return redirect('accounts:login') # else: # login(request, user) # return redirect('main:home') else: error = 'Invalid Credentials' return redirect('accounts:registration') else: form = CustomLoginForm() return render(request, 'account/login.html', {'form': form, 'error': error}) forms.py class CustomLoginForm(forms.Form): email = forms.CharField(max_length=256, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def clean_username_or_email(self): username_or_email = self.cleaned_data['username_or_email'] if "@" in username_or_email: validate_email(username_or_email) … -
Python Django nginx uWsgi getting failed on specific callback endpoints
I'm running Django web app on a docker container where I use Nginx with uwsgi. Overall the web works just fine it fails only on specific callback endpoints during the social app (Google, Facebook) registration. Below is the command I use to run the uswgi uwsgi --socket :8080 --master --strict --enable-threads --vacuum --single-interpreter --need-app --die-on-term --module config.wsgi Below is the endpoint where it fails (Django allauth lib) accounts/google/login/callback/?state=.......... Below is the error message: !! uWSGI process 27 got Segmentation Fault !!! ... ... DAMN ! worker 1 (pid: 27) died :( trying respawn ... Respawned uWSGI worker 1 (new pid: 28) Just FYI.. this works without any issues in the local docker container but it fails when I use the GCP container. Also, this used to work fine on GCP as well so probably something happened after recent dependency updates. Environment: Python: 3.9.16 Django: 3.2.3 allauth: 0.44.0 (Django authentication library) Nginx: nginx/1.23.3 uWSGI: 2.0.20 -
How to make validator for login in Django?
I want to write validators for the email and username forms, so that when trying to create a new account, it is not allowed to create where username has the value of a name with special characters or languages other than English [a-z, A-Z, 0-9, dot, or underscore] I read the documentation and even tried the example given there, but the validation doesn't work, and I could still create an account where the email was something like "1+2=3@gmail.com" and the username was written in a different language with special characters. I also googled all the possible questions and looked through all the answers, but nothing helped. Most of all, I don't know how validation works in Django, so please give at least a good example with an explanation of what it is for and I will be infinitely grateful. -
How to set field values dynamically based on other fields in django
I have two models in Django. class Product(models.Model): description = models.CharField('Description', max_length=200) price = models.FloatField() class Sell(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() def save(self, *args, **kwargs): self.price = self.product.price super(Sell, self).save(*args, **kwargs) I want to copy dynamically Product.price value to Sell.price and set it as a default value. User can change Sell.price value later. I have implemented save() method for this purpose, but it is not showing any value. How to do it?