Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django poll - change from only one seleted option (radio) in multiple selection (checkbox) and register all togheter
I made a poll app in django. It work ok but what i want to change is the selection an register vote option. Now i can select and register one option ('participanti') (radio btn select) and i want to be able to let the user to select more than one "participanti" (1 or 1 to maximum 3 ) in the same instance and after submit to register all the option/participanti selected (1 or 2 or all maximum 3 that user selected) . I don't know how to approach this kind of mechanism. Please help me with a solution. Thank you very much. Below mai settings models class Campanie(models.Model): ..... class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) def __str__(self): return self.nume_participant class Meta: verbose_name = 'Participanti' verbose_name_plural = 'Participanti' views.py def votare_campanie(request): campanie = get_object_or_404(Campanie) try: participant_votat = campanie.participanti_set.get(pk=request.POST['participanti']) except (KeyError, Participanti.DoesNotExist): return render(request, 'campanievot/campanie.html', { 'campanie' : campanie, 'error_message' : "Trebuie sa votezi cel putin un coleg", }) else: participant_votat.votes += 1 participant_votat.save() messages.success(request, "Multumim pentru feedback!") return redirect('campanievot:index') template.html <form action=" {% url 'campanievot:votare_campanie'%} " method="post" > {% csrf_token %} {% for p in campanie.participanti_set.all %} {% if p.dep_participant … -
TimeoutError at /index
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond -
('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)
I am trying to connect sql server 2019 (running on another server) with Django project in AWS Lambda environment (Amazon linux) but I am not able to establish connection between django and the sql server database and I get error ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect) Below are the steps I am following to deploy to AWS lambda Spinning docker image with command: docker run -t -i -p 8000:8000 -e AWS_PROFILE=zappa -v "/task" -v C:\Users\Ishan/.aws/:/root/.aws --rm zappa-docker-image dockerfile from lambci/lambda:build-python3.7 #make this default working directory WORKDIR /task #expose tcp port 8000 for debugging EXPOSE 8000 #Prompt to remind you are in zappashell RUN echo 'export PS1="\[\e[36m\]zappashell>\[\e[m\] "' >> /root/.bashrc CMD ["bash"] Once environment is up, I setup msodbcdriver17 using below commands taken from Microsoft's online setup guide: RUN curl http://mirror.centos.org/centos/7/os/x86_64/Packages/unixODBC-2.3.1-14.el7.x86_64.rpm > /tmp/unixODBC-2.3.1-14.el7.x86_64.rpm RUN yum -y install /tmp/unixODBC-2.3.1-14.el7.x86_64.rpm RUN curl http://mirror.centos.org/centos/7/os/x86_64/Packages/unixODBC-devel-2.3.1-14.el7.x86_64.rpm > /tmp/unixODBC-devel-2.3.1-14.el7.x86_64.rpm RUN yum -y install /tmp/unixODBC-devel-2.3.1-14.el7.x86_64.rpm RUN curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo RUN ACCEPT_EULA=Y yum -y install msodbcsql17 Path of msodbcsql17 is /opt/microsoft/ Result of odbcinst -j unixODBC 2.3.1 DRIVERS............: /etc/odbcinst.ini SYSTEM DATA SOURCES: /etc/odbc.ini FILE DATA SOURCES..: /etc/ODBCDataSources USER DATA SOURCES..: /root/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: … -
Example of updating fields without views.py?
Can you please provide an example of vievs.py updating(or crating) fields without using forms.py? -
twilio python cannot send dynamic messages
i am facing issues regarding sending twilio messages from python back-end code. I am able to send static messages to the phone but when i create dynamic messages the messages is send successfully but not able to received in the device. customerName = request.data.get('fullName') phoneNumber = "+91" + request.data.get('phoneNumber') bodyM = f'Hey {customerName} worth' print(bodyM) serializer = UserSerializer(data=data) if serializer.is_valid(): collection_name.save(data) message = client.messages.create(to=phoneNumber , from_="+16104865966", body=bodyM) Adding code for better understanding of the issue i am facing -
Getting Error while reloading the matplotlib plot without refreshing the page
I am trying to reload the matplotlib figure without refreshing the page and using Slider to change the slice number using django, matplotlib, mpld3, and javascript. The slider changes the slice number before generating the new plot matplotlib throws an error. File "D:\Django_Projects\Django_Gliomai\BraTS\show.py", line 25, in plot_1 plt.imshow(original[x,:,:,i], cmap='bone') File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib_api\deprecation.py", line 459, in wrapper return func(*args, **kwargs) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\pyplot.py", line 2660, in imshow sci(__ret) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\pyplot.py", line 3032, in sci return gca()._sci(im) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\axes_base.py", line 2155, in _sci raise ValueError("Argument must be an image, collection, or " ValueError: Argument must be an image, collection, or ContourSet in this Axes -
Django dynamic template filter tag
is it possible to make a dynamic tag inside a if tag my view is this {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.{{DYNAMIC}} %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} {% endfor %} I want filter this by date. Like an input for date and it would show my ' <td> like I have it in my template -
How to delete latest record if it is matched with today date in django
I want to delete the record if it is matched with today's date and new record should replace with old record if it matches I wrote code like below but it's not deleting the record new record also adding Def addEscalatedcount(request): dataDict=Helix.fectEscalted() ifdataDict['error']==False: ESC=Escalated_count.object.all() If ESC: recdate=ESC[0] if str(recdate.last_run.date)[0:10]==str(datetime.date.today())[0:10]: Escalated_count.get(id=recdate.id). delete () ESC=addEscalatedSerializer(data=dataDict['data'],many=True) if ESC.is_valid(): ESC.save() return jsonResponce("data saved",safe=False) -
is it normal to have meta data outside head Django templates
i have three templates home, navbar, base and footer. navbar and footer are included in base and base in extended in every other template (home). this is base.html: {% load static %} <head> <link rel="stylesheet" href="{% static 'base.css' %}"> <link rel="stylesheet" href="{% static 'navbar.css' %}"> <link rel="stylesheet" href="{% static 'footer.css' %}"> </head> {% include 'navbar.html' %} <div id="all"> <div id="bg"> <img id="l1" src="{% static 'img/bg-layer-1.svg' %}"> <img id="l2" src="{% static 'img/bg-layer-2.svg' %}"> </div> {% block content %} {% endblock %} </div> {% include 'footer.html' %} this template represents navbar.html and footer.html: {% load static %} <div class="wrapper"> <ul id="navbar"> <li class="left"> <a href="{% url 'index'%}">Home</a> </li> <li class="right"> <a href="{% url 'account'%}">Account Managment</a> </li> <li class="right"> <a href="{% url 'contests'%}">Contests</a> </li> </ul> </div> <script src="{% static 'navbar.js' %}"></script> this is home.html: {% extends 'base.html' %} {% load static %} <html lang="en"> {% block content %} <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Home Page</title> <link rel="stylesheet" href="{% static 'home.css' %}"> </head> <body> <div class="content"> <table border="0"> <tr> . . . </tr> </table> </div> </body> </html> {% endblock %} technically everything works fine from styling to html elements order in view, but when i inspect … -
I need to upload data from REST API on front-end using vue.js framework but not using vue.js cli
I'm trying to get the data from rest api using vue.js. But it's not working , I've started learning vue.js just now I've tried to implement many logic but still it doesn't gives the appropriate output. Here's my views.py file # Create your views here. class TaskViewSet(ModelViewSet): renderer_classes = [TemplateHTMLRenderer] template_name = 'templates/list.html' def list(self,request): queryset = Task.objects.all() serializer = TaskSerializer(queryset,many=True) context = { 'serializer' : serializer.data } return Response(context) Here's my list.html file <!DOCTYPE html> <html lang="en"> {%load static%} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js" integrity="sha256-Gs0UYwrz/B58FsQggzU+vvCSyG/pewemP4Lssjzv8Ho=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue- resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue- resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU=" crossorigin="anonymous"></script> <title>Document</title> </head> <body> <h3>Tasks Display Here</h3> <div id="app" v-for="task in tasks"> {{task.data}} </div> <script> var app = new Vue({ el : '#app', data:{ tasks : [] } }, methods : { async getData(){ try { // fetch tasks const response = await this.$http.get('http://localhost:8000/api/tasks/'); // set the data returned as tasks this.tasks = response.data; } catch (error) { // log the error console.log(error); } }, }, created(){ this.getData(); } } </script> </body> </html> I have mentioned my API url from where the data is getting retrieved but still the vue.js script is unable to collect the data … -
Cannot see foreign key values in the template
This is my 2nd week learning Django. I'm trying to get comfortable with Django Template Language. I'm trying to make an Inventory app with 4 models. The views for them are class-based. The templates for Ingredient and Menu work as expected. However, I'm struggling with trying to loop through values from the Purchase model which has a foreign key field 'menu_item'. The template is not showing anything from the for loop. I've referred numerous articles here to find most of them use function-based views. I've tried using {% for purchase in purchase_set %}, {% for purchase in purchase_set.all %}. I know the object to iterate over is a query-set. I cannot figure out what to do? MODELS.PY from django.db import models # Create your models here. class Ingredient(models.Model): Pounds = 'lbs' Ounces = 'oz' Grams = 'gms' Eggs = 'eggs' Piece = 'piece' Litre = 'litre' unit_choices = [(Pounds, 'lbs'), (Ounces, 'ounces'), (Grams, 'grams'), (Eggs, 'eggs'), (Piece, 'piece'), (Litre, 'litre')] id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) unit_price = models.FloatField(default=0.0) quantity = models.FloatField(default=0.0) unit = models.CharField(max_length=10, choices=unit_choices) class Meta: ordering = ['id'] def __str__(self): return self.name class MenuItem(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) price = models.FloatField(default=0.0) class Meta: ordering = … -
How to create Basic PWA (progressive web apps) using django
I'm new to PWA with django. Can anyone suggest me a basic PWA app with django(with code). I tried working with the basic web app suggested in the geeks for geeks website (https://www.geeksforgeeks.org/make-pwa-of-a-django-project/) but it didn't work as the instructions were not enough. I'm unable to load the manifest in the devtools >> apps. I tried them as per the instructions in the site by adding the manifest code in settings but it did not create any manifest.json file in the templates. So please suggest me a basic code to make a pwa app with django. Thank you in advance. -
What to do if value is different than all the defined choices for Django field choices?
I am currently working on a Django web application. I have defined a model as follows: class MyModel(models.Model): fav_subject_choices=[ ('physics', 'Physics'), ('chem', 'Chemistry'), ('math', 'Maths'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) student_name = models.CharField(max_length=100) fav_subject = models.CharField(max_length=50, choices=fav_subject_choices, default='physics') Here, I want to provide a dropdown of choices so that Admin can select favorite subject for students. For which I have defined choices and provided the same inside the field. However, the data of students is coming from an API which may have favorite subjects of students different from the choices I have defined, for example, a student can have 'English' as his/her favorite subject. This is fine as I don't want to change the data which is already there, instead I want to add favorite subject only for students whose data for favorite subject is missing. How can it be done? Is there an option where a field can have a value other than the choices defined? PS. This is just a dummy scenario which I have created. But it's exactly the same as the problem I am facing. -
error while loading the data using jinja2 conditional operators
I have 2 models Staff and Hod where user is OneToOnefield of User model. Now in hod.html template I want display list of all staff using jinja2 for loop Loop works perfectly but I want to display the staff which has same branch/department and the year When I use this if statement I don't get any staff which has same department and year models.py class Hod(models.Model): id = models.AutoField(primary_key=True) user=models.OneToOneField(User, on_delete=models.CASCADE) hod_of_year=models.ForeignKey(Year,on_delete=models.DO_NOTHING) hod_of_department=models.ForeignKey(Course,on_delete=models.DO_NOTHING) #..... class Staff(models.Model): id = models.AutoField(primary_key=True) user=models.OneToOneField(User, on_delete=models.CASCADE) teacher_of_year=models.ForeignKey(Year,on_delete=models.DO_NOTHING) teacher_of_department=models.ForeignKey(Course,on_delete=models.DO_NOTHING,null=True) #.... hod.html <tbody> {% for staff in staffs %} {% if user.hod.hod_of_year == staff.teacher_of_year and user.hod.hod_of_department == staff.teacher_of_department %} <tr> <td style="color:white;">{{staff.user.first_name}}</td> <td style="color:white;">{{staff.user.last_name}}</td> <td style="color:white;">{{staff.mobile_no}}</td> <td style="color:white;">{{staff.user.email}}</td> <td style="color:white;">{{staff.identity_no}}</td> <td style="color:white;">{{staff.class_alloted1}}</td> <td style="color:white;">{{staff.class_alloted2}}</td> <td style="color:white;">{{staff.class_coordinator_of}}</td> <td style="color:white;">{{staff.teacher_of_year}}</td> <td style="color:white;">{{staff.mentor_of}}</td> <td style="color:white;">{{staff.teacher_of_subject}}</td> <td style="color:white;">{{staff.teacher_of_department}}</td> <td> <form action="{% url 'deletestaffdatahod' staff.id %}" method="post" class="d-inline"> {% csrf_token %} <button type="submit" value="Delete" class="btn btn-warning">Delete</button> </form> </td> </tr> {% endif %} {% endfor %} </tbody> Similarly I have one more student model and I used the same logic but I get the students of same branch and year student.html <tbody> {%for student in students%} {% if user.hod.hod_of_year == student.year and user.hod.hod_of_department == student.branch %} <tr> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> … -
my API runs properly in local device but once I run it in production with HTTPS I encounter an server error 500
This is the code for my views.py class FetchCustomerUsingQRView(APIView): authentication_classes = [JWTAuthentication] def get(self, request): code = request.data.get('unique_code') try: customer = Customer.objects.get(unique_code=code) print(customer) if customer.already_claimed == True: return Response({ 'message': 'You have already claimed', }, status=status.HTTP_400_BAD_REQUEST) data_serializer = CustomerSerializer(customer) return Response({"data": data_serializer.data}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'message': 'invalid unique code', }, status=status.HTTP_400_BAD_REQUEST) this is working properly in localhost and I also try to run it in my virtual machine localhost and works perfectly but I receiving an error when running in production. my Settings already set to DEBUG = False ALLOWED_HOSTS = ['*'] -
Django: time data '2022-09-02 11:13 am' does not match format '%Y-%m-%d %H%M%S.%f'
I am trying to format DateTime in the views.py file. But I am getting this error while converting data to DateTime. Here is my code. FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").date() FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").strftime('%Y-%m-%d') I have tried both ways to convert data but it is not working for me. I am new to python Django. Grateful for the help in advance. -
Adding columns to pandas not working with Django ORM
I am trying to add columns to existing pandas DataFrame. The added column gets data using Django ORM. My approaches are like the following: 1. df['name'] = User.objects.get(id=df['id']) df['name'] = df.assign(name=lambda x: User.objects.get(x.id)) But for both the approaches, I am getting the following error: TypeError: Field 'code' expected a number but got 0 1 1 18 Name: code, dtype: int64. The field is expecting a number but getting a pandas Series instead. How shall I approach this? -
How to access static variable inside instance method
So i am using a GenericAPIView when my post method is hit function gets called and perform certain action like creating and completing some objects in my class. so i am using a static method here but in exception i am not being able to refer to variable named var used in static method to use in my post method exception class MyApiView(GenericAPIView): @staticmethod def my_custom_method(arg): if condition1 and condition2: var = Class1(arg=arg) var.create() var = Class2(arg=arg) var.complete() if condition4 or condition3: var = Class3(arg=arg) var.create() def post(self, request): try: my_cust_method(arg) except Exception: logger.error(f"{var.__class__}", exc_info=True) Unresolved reference var -
DateTimeField throwing datetime is not serializeable
I have added a new Datetime field in my model. class MyModel: valid_upto = models.DateTimeField(auto_now=True, blank=True, null=True) and my serializer code is class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' When i am updating one instance i am getting TypeError: Object of type datetime is not JSON serializable the value that can come in valid_upto is None or a datetime value which i am getting from timezone.now() -
How to change error messsage I am getting in django for foreign key
Below is my code funding = models.ForeignKey(TblHcrMasterLookupOptions, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_funding',) tpa_for_reference_year = models.ForeignKey(TblHcrVendors, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_tpa') pbm_for_reference_year = models.ForeignKey(TblHcrVendors, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_pbm') I am getting this error message "renewal_month": [ "Incorrect type. Expected pk value, received str." ], "funding": [ "Incorrect type. Expected pk value, received str." ], "pbm_for_reference_year": [ "Incorrect type. Expected pk value, received str." ], I want to change the error message and want my custom error message -
Implement RDKit and Postgres in Django
I started to use rdkit and try to implement in Django with postgres. So I installed rdkit in my django virtualenv with pip install rdkit-pypi and also installed django-rdkit(https://github.com/rdkit/django-rdkit). This command: python3 -c "from rdkit import Chem; print(Chem.MolToMolBlock(Chem.MolFromSmiles('C1CCC1')))" works fine to me. But when I run migrate, it failed. The error is : django.db.utils.OperationalError: could not open extension control file "/usr/share/postgresql/12/extension/rdkit.control": No such file or directory It seems failed to create cartridge rdkit with postgres. Anyone can help me find the problem and solution (better not with Conda, cause I never use it before)? Thank you very much! -
React and Django google login
I am working in backend to create google login service and this login will be seen in react.I have seen many resources but none make me understand cause I am not familiar with react js. I need user to login from frontend and get access and refresh token and save them in db so user could be always logged till the access token expires and then using refresh token he gets again access token and one more service I need to do is using this access token I should get calender events list. -
How to extend the data in Django Plotly Dash?
I have this existing Django plotly app and it's also updating Realtime. It looks like this my project. Every three seconds the graph is updating but, the problem is it's updating the whole traces not adding a new traces. Is it possible to add the next data to graph? like extendTraces function. I just started learning plotly dash bear with me app = DjangoDash("SimpleExample") app.layout = html.Div( html.Div([ dcc.Graph(id='live-update-graph'), dcc.Interval( id='interval-component', interval=1*3000, # in milliseconds n_intervals=0 ) ]) ) @app.callback(Output('live-update-graph', 'figure'), Input('interval-component', 'n_intervals')) def update_graph_live(n): data = { 'time': [], 'PH': [], 'CON': [], 'TOTAL': [], 'VOLATILE': [], } # Collect some data for i in range(9): time = datetime.datetime.now() - datetime.timedelta(seconds=i*20) ph = random.randint(8, 13) con = random.randint(10, 20) total = random.randint(1, 5) volatile = random.randint(5, 10) data['PH'].append(ph) data['CON'].append(con) data['TOTAL'].append(total) data['VOLATILE'].append(volatile) data['time'].append(time) # Create the graph with subplots fig = plotly.tools.make_subplots(rows=2, cols=2, vertical_spacing=0.2) fig['layout']['margin'] = { 'l': 30, 'r': 10, 'b': 30, 't': 10 } fig.add_trace({ 'x': data['time'], 'y': data['PH'], 'name': 'PH', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) fig.append_trace({ 'x': data['time'], 'y': data['CON'], 'name': 'Conductivity', 'mode': 'lines+markers', 'type': 'scatter', }, 2, 1) fig.append_trace({ 'x': data['time'], 'y': data['TOTAL'], 'name': 'Total Suspended Solids', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 2) … -
Using a Boolean to set a condition to make form appear
I have added boolean to my Model as Active where I want to be defaulted as FALSE and if the user change it to TRUE as in active to make a form appear. Here is what I have done so far. I have created a views for the boolean: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p return context def change_activity (request): if request.is_ajax() and request.method=='POST': log = Log.objects.get() log.active = True if request.POST.get('active') == 'true' else False log.save() data = {'status':'success', 'active':log.active} return JsonResponse(data, status=200) else: data = {'status':'error'} return JsonResponse(data, status=400) and I have added the urls: path('changeactivity', change_activity, name="change_activity"), Here is the template for changing the active option: <div> <button {% if not p.active %} {% endif %} id="customSwitches" onclick="start();" type="button"> Start the activity </button> </div> <script type="text/javascript"> $(document).ready(function() { // send request to change the active state on customSwitches toggle $("#customSwitches").on("change", function() { $.ajax({ url: "{% url 'my_gym:change_activity' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", active: this.disabled // true if checked else false }, type: "POST", dataType : "json", }) // $.ajax().done(), … -
Is there a way to customize the value of specific field in a model in django when adding a new data?
I have a model here which I want to specify the value of unique_code everytime I'm adding a new data . model.py class Customer(models.Model): LastName = models.CharField(max_length=45, blank=True) FirstName = models.CharField(max_length=45, blank=True) MiddleName = models.CharField(max_length=45, blank=True) ExtensionName = models.CharField(max_length=45, blank=True) GenderID = models.ForeignKey(Gender, on_delete=models.CASCADE) id_pic = models.ImageField(null=True, blank=True, upload_to=upload_path) otp = models.CharField(max_length=6, blank=True) unique_code = models.CharField(max_length=8, blank=True) verified = models.BooleanField(default=False) already_claimed = models.BooleanField(default=False) email = models.CharField(max_length=45, blank=True) Birthdate = models.CharField(max_length=45, blank=True, null=True) cellphone_number = models.CharField(max_length=45, blank=True, null=True) agreement1 = models.BooleanField(null=True) agreement2 = models.BooleanField(null=True) agreement3 = models.BooleanField(null=True) I try to override the save method to do that and here is my code def save(self, *args, **kwargs): self.unique_code = uuid.uuid4().hex[:8].upper() super().save(*args, **kwargs) but the problem with this approach is that the unique_code change everytime I update the data. and I want the unique_code to not change once the data has been save to database. so is it possible to specify its value here in view.py data = request.data serializer = CustomerSerializer(data=data) how to add unique_code = uuid.uuid4().hex[:8].upper() in this serializer = CustomerSerializer(data=data)