Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'dict' object has no attribute 'pk' when using Django bulk_create() function
I have a table counters with 2 fields: date and value. I have a big list of objects which need to be inserted into table counters. But using serializer.save() for every row in list, there will a lot of inserts and if i have a lot of data, it will take some time until it the data has finished inserting. To solve this i looked into Django's documentation and i found that there is a function name bulk_create which can help me to insert into table a list of Objects in just 1 query. Now, here's my code: models.py: class CounterFileData(models.Model): date = models.DateTimeField() value = models.FloatField() serializers.py: class CounterFileDataSerializer(serializers.ModelSerializer): class Meta: model = CounterFileData fields = ['date', 'value'] and the code where i use bulk_create: objs = (CounterFileData(date=row.date, value=row.value) for row in parsed_data) batch = list(parsed_data) CounterFileData.objects.bulk_create(batch) row has the following schema. For example: { "date": "2018-12-31T22:00:00" "value": 9.23129792740622e-05 } When i try to do that CounterFileData.objects.bulk_create(batch) i get the following error: AttributeError: 'dict' object has no attribute 'pk' Can somebody tell me why it returns no attribute 'pk' ? I'm struggling with this thing some good hours and i still can't find a fix. Thanks in advance. -
writing a backend for authenticating users with account number after registration
I am creating a bank system that should authenticate users automatically after registration using email and password. Then, users should be assigned unique account numbers immediately they register. These account numbers are then to used for authentication during login. The problem arises when I try to login users with the assigned account numbers. It flags an error Account does not exist I have tried looking into my backends.py file to figure out errors. I realize that it seems my backend cannot fetch the user from the database. However, I cannot point out the exact error in the application. Kindly assist. models.py: class User(AbstractUser): username = models.CharField( _('username'), max_length=30, unique=True, null=True, blank=True, help_text=_( 'Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.' ), validators=[ RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username. ' 'This value may contain only letters, numbers ' 'and @/./+/-/_ characters.'), 'invalid'), ], error_messages={ 'unique': _("A user with that username already exists."), }) email = models.EmailField(unique=True, blank=True, null=True) contact_no = models.IntegerField(unique=False, null=True, blank=True) account_no = models.PositiveIntegerField( unique=True, validators=[ MinValueValidator(1000000000), MaxValueValidator(9999999999) ] ) balance = models.DecimalField( default=0, max_digits=12, decimal_places=2 ) GENDER_CHOICE = ( ("M", "Male"), ("F", "Female"), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICE) birth_date = models.DateField(null=True, blank=True) city = models.CharField(max_length=256, … -
Django DateField and Postgres
I'm using SQLite for development, but when deploying to production (using Postgres), I had the following error on a CreateView: Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = date LINE 1: ...xxxx" WHERE "xxxxx"."date" = '2019-07... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. This is the field: date = models.DateField('Date', max_length=150, default='', blank=True, unique=True) Also, I use this in settings.py: DATE_INPUT_FORMATS = ('%Y-%m-%d') Do you have any ideas ? -
How can I prevent the escaping of HTML data in a DRF renderer?
I have a serialized my data in to Pandas DataFrame with the rest-pandas package. I can use the method to_html of this Dataframe to create a nicely formatted table in HTML. However, when I render its HTML is escaped and thus showing the HTML describing the formatted table instead of the table. I would like to prevent the renderer from escaping the HTML. There must be an option to set or method to override but I cannot find it. Has anyone have a suggestion? -
Android Virtual Machine management with Python for mobile applicaton security scanner
I want to develop an Android Mobile Application Vulnerability Scanner (Dynamic) to run android applciation to an android virtual machine and check out the vulnerabilities and report. In detail i should say that after the android application installation on virtual machine, a python script should run and check the application behaviour. I want to develop this scanner with python and django and I have problem on this subjects: Which Android Virtual Machine I should use. How can I connect python and android and my Django scripts to work which each other. How can I manage Android Virual Machine with Python. Thank you -
How can I get the length of a model when I create an instance of it in Django
I'm creating a model class named Project, and I wanted to use the length of the Project models. I mean when I create an instance of Project, if there are 10 instances, I wanna set the default value of order field is the length of the Project model. How can I get the current length of the model? this is my models.py code for Project model in models.py class Project(models.Model): title=models.CharField(max_length=50) order=models.IntegerField(default=0) isPublic=models.BooleanField(default=True) content=models.TextField() detailUrl=models.CharField(max_length=200) # where to upload image = models.ImageField(upload_to = createFileName, help_text="The recommended size of the images are 1x1") time=models.DateTimeField(default=timezone.now) view=models.IntegerField(default=0) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.order=models.IntegerField(default=0) # this works fine but this isn't what I want self.order=models.IntegerField(default=len(Project.objects.all())) # this is what I want but it gives me no response without emitting errors. -
How to aggregate on a foreign key and a specific field at the same time?
My table named Value has a one to many relationship with the table Country and the table Output_outcome_impact. I have a query that is working fine and gets what I want but then I need to do an average of the value field, but this average needs to be done for each unique id_output_outcome_impact and not the whole query. class Country(models.Model): country_name = models.CharField(max_length=255, primary_key=True) CONTINENTCHOICE = ( ('Africa', 'Africa'), ('America', 'America'), ('Asia', 'Asia'), ('Europe', 'Europe'), ('Oceania', 'Oceania') ) region = models.CharField(max_length=255) continent = models.CharField(max_length=255, choices=CONTINENTCHOICE) GDP_per_capita = models.IntegerField(null=True) unemployment_rate = models.FloatField(null=True) female_unemployment_rate = models.FloatField(null=True) litteracy_rate = models.FloatField(null=True) def __str__(self): return self.country_name class OutputOutcomeImpact(models.Model): output_outcome_impact_name = models.CharField(max_length=255, primary_key=True) TYPECHOICE = ( ('Output', 'Output'), ('Outcome', 'Outcome'), ('Impact', 'Impact'), ) type = models.CharField(max_length=255, choices=TYPECHOICE) description = models.TextField() TARGETGROUP = ( ('Standard', 'Standard'), ('Investors', 'Investors'), ('Local authorities and NGOs', 'Local authorities and NGOs'), ) target_group = models.CharField(max_length=255,choices=TARGETGROUP) question = models.TextField(null=True, blank=True) parent_name = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) indicator = models.ForeignKey(Indicator, on_delete=models.PROTECT) def __str__(self): return self.output_outcome_impact_name class Activity(models.Model): activity_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() product_service = models.TextField() output_outcome = models.TextField() outcome_impact = models.TextField() output_outcome_impacts = models.ManyToManyField('OutputOutcomeImpact') countries = models.ManyToManyField('Country') sectors = models.ManyToManyField('Sector') def __str__(self): return self.activity_name class Value(models.Model): value_name = models.CharField(max_length=255, primary_key=True) country … -
Issues with FileField not using upload_to location?
I believe I have some sort of bug with a FileField in Django. It is defined as follows: employees_csv_upload = models.FileField( _('Employees CSV Upload'), upload_to='csv/organisations/employees/', validators=[organisation_employees_csv_upload_validator], help_text='Allowed file formats: {}'.format('.csv'), null=True, blank=True ) I have an upload_to location specified. I then aim to upload the file named "employees.csv" from the Django admin area. Expected: When referencing self.employees_csv_upload.url in the model's save() call, it should be: '/uploads/csv/organisations/employees/employees.csv' Actual: However, when I go to reference self.employees_csv_upload.url on save() it is as follows: '/uploads/employees.csv' Surely this is a bug? What have I done wrong? What I have tried: On the same model, I have the following: logo = models.FileField(_('Logo'), upload_to='img/organisations/logos/', null=True, blank=True) When uploading a logo, all works fine: self.logo.url = '/uploads/img/organisations/logos/logo.png' -
Change Foreign key DropDown to Checkbox Django Admin
I have two models,linked through Foreign key. What I exactly want is I have created Table hobbies which has some hobbies and user can select hobbies listed in hobbies table inform of checkbox.When editing model 'UserModel', on admin site in field where I have applied FK it shows dropdown to 'Hobbies' Model.On admin site I want hobbies to be displayed in form of checkbox instead of opening a new popup window and selecting hobbies. models.py class hobbies(models.Model): hobbies_choices = ( ('CRR', 'Cricket'), ('POL', 'Politics'), ('FBL', 'FootBall'), ('TV', 'Television'), ('MOV', 'Movies') ) table_id=models.AutoField(primary_key=True) hobbies = MultiSelectField( choices=hobbies_choices, verbose_name='Hobbies', default=None ) def __str__(self): return str(self.hobbies) class UserModel(models.Model): username=models.ForeignKey( User, related_name='UserModel', on_delete=models.CASCADE, ) name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) hobbies=models.ForeignKey(hobbies,on_delete=None,related_name='of_user')\ On Admin Site When I Edit 'UserModel' ,I want to display 'hobbies' field from hobbies table in form of checkbox,But traditionally it display a plus sign and opens a new popup window.Could someone help me with it.Thanks -
Is there a way to use mixins in Django templates like in Sass?
Say I have a template with a lot of repeated code. Very simply: <tr> <td>ITEM 1</td> <td>ITEM 2</td> </tr> Is there a way in Django to create a shortcut or a mixin that allows me to define a structure and pass a variable to it? E.g. {% mixin 'mymixin' %} <td>$value</td> {% end mixin %} And then use this in the html such as: <tr> {% use_mixin 'mymixin' 'ITEM 1' %} {% use_mixin 'mymixin' 'ITEM 2' %} </tr> I want to do this all in the template rather than mess about with my views so I can knock some wireframes up quickly. -
How to send token (JTW Token) headers from React Client to Django Channels2
It appears to be complex then I imagined. I am using React as client to connect websocket on Django Channels server. I have used JWT Auth for REST Api validation (using DRF). I have have not seen way to send Token using ws connection. I come across few suggestion to send as protocal - this did not work for me. There are other suggestion to send token as query string - I think it is not safe. I am looking better ways. -
integration of Django and mysql
first i have some questions :- A) can mysql and sqlite3 run on same server concurrently ? B) currently i m authenticating users using sqlite3 database. Was researching about integration of MYSQL and Django and found this. --> so After performing the steps in the link will my django app be using MYSQL db ? -->are these steps sufficient to move my database from sqlite3 to mysql ? --> if steps are performed as they are in the link, am i be using mysql db (but not sqlite3) through Django admin ? thnx for the help.! -
save() not updating the table in database
I have to update 2 tables in database every time user visit a page. this is working: order_order = OrderTable.no_objects.get(order_number=order_id) order_order.status = 'updated status' order_order.save() This is not working: (related with first table through foreign key) order_item = ItemsTable.objects.filter(order_id__order_number=order_id) for i in range(order_item.count()): order_item[i].qty = i + 5 order_item[i].qty_nextMonth = i + 30 order_item[i].save() Can anyone tell what's wrong in 2nd part of code. It's not updating the database. -
How to Show Navigation menu from Database in Django?
My category are not showing on header menu, Please let me the process for this. If i use code on home.html file then all category are showing on homepage but when i click on any category page it's not showing. Here are the models.py file... class WebCategory(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Category name') slug = models.SlugField(verbose_name='Slug') title = models.CharField(max_length=165, null=True) metadesc = models.TextField(max_length=165, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebCategory' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(WebCategory, self).save(*args, **kwargs) def __str__(self): return self.name class WebSubCategory(models.Model): category = models.ForeignKey('WebCategory', related_name='websubcategory', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select category') name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=100, null=True) metadesc = models.TextField(max_length=165, null=True) description = RichTextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebSubCategory' def __str__(self): return self.name class SubChildCategory(models.Model): subcat=models.ForeignKey('WebSubCategory', related_name='subchild', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select Subcategory') name=models.CharField(max_length=50) slug=models.SlugField(unique=True, null=True) title=models.CharField(max_length=100, null=True) metadesc=models.TextField(max_length=165, null=True) description=RichTextField(blank=True, null=True) created_at=models.DateTimeField(auto_now_add=True, null=True) updated_at=models.DateTimeField(auto_now=True) class Meta: verbose_name_plural="SubChildCategory" def __str__(self): return self.name And here are my views.py file def header(request): category_list = WebCategory.objects.order_by('-created_at')[:5] context_dict={'webcat':category_list,} return render(request, 'layouts/header.html', context_dict) Here are y urls.py file.. from django.urls import path, re_path from . import views from django.conf.urls.static import static from django.conf … -
Prints Invalid data on the screen
I have retrieved some data from model queries in django-python. I made a dictionary with all three results i queried. Now I want to convert it to json and pass it to FusionCharts object. I did so, but it prints out "invalid data" in place of the chart. How can I solve it? all_count = Offenses.objects.all().count() open_status = Offenses.objects.filter(status__iexact='OPEN').count() closed_status = Offenses.objects.filter(status__iexact='CLOSED').count() hidden_status = Offenses.objects.filter(status__iexact='HIDDEN').count() high1 = Offenses.objects.filter(magnitude=7).count() high2 = Offenses.objects.filter(magnitude=6).count() high3 = Offenses.objects.filter(magnitude=8).count() high4 = Offenses.objects.filter(magnitude=9).count() medium1 = Offenses.objects.filter(magnitude=5).count() medium2 = Offenses.objects.filter(magnitude=4).count() medium3 = Offenses.objects.filter(magnitude=3).count() low1 = Offenses.objects.filter(magnitude=1).count() low2 = Offenses.objects.filter(magnitude=2).count() total_high = high1+high2+high3+high4 total_medium = medium1+medium2+medium3 total_low = low1+low2 status_data = { 'open_status': open_status, 'closed_status': closed_status, 'hidden_status': hidden_status, } status_data_json = json.dumps(status_data) status = FusionCharts('doughnut2d', 'ex3', '600', '400', 'chart-2', 'status_data_json', """{ "chart": { "caption": "Offense Status", "showpercentvalues": "1", "aligncaptionwithcanvas": "0", "captionpadding": "0", "decimals": "1", "plottooltext": "<b>$percentValue</b> of offenses are <b>$label</b>", "centerlabel": "# Users: $value", "theme": "fusion" }, "data": [ { "label": "Opened offense", "value": "$open_status" }, { "label": "Closed offense", "value": "5300" } ] }""") -
Heroku failed to serve django admin static files - other static files work
I'm having trouble serving django admin static files from Heroku. Receiving 404 error for /static/admin/css/base.css - I have the same dir structure and the file base.css is inside it. Non admin static files work great This is how I serve static files: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}) Does anyone know how to solve this issue? -
Modelling a 'web' in a Django database
I have a use case where I have a 'web' with the following relationships; what's the best way to model this in Django? There is a logical top layer (could be modelled as a single 'very top' node if required) There are logical leaves at the bottom Nodes can have relationships to nodes in the layer above and/or below but never to siblings So like that chinese game with a coin dropping through pins, there are multiple routes from top to bottom but a traversal will always work, albeit in some manner determined elsewherre (actually user input in my case). I have tried using ManyToMany relationships but can't see how to spot the top and bottom of the relationships; do I need to switch to many OneToMany relationships for independent child and parent relationships? -
Why don't I obtain tag instance attached to my question instance?
I'm beginner in django and new to DRF. So, the problem is within my create() method in my nested serializer. The thing is that it creates new tags instances but don't attach them to question instance which I`d like to send on server in my POST request. Here is my model: class Question(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=500, default="Write your question") # HTMLField() look TinyMCE tags = models.ManyToManyField("Tag") pub_date = models.DateField(auto_now=False, auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) answers = models.ManyToManyField("Answer") comment_cnt = models.IntegerField(default=0) like_cnt = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('questions', args=[self.title]) class Meta: ordering = ['pub_date'] class Answer(models.Model): content = models.CharField(max_length=500, default="Write the answer") # HTMLField() look TinyMCE pub_date = models.DateField(auto_now=False, auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) like_cnt = models.IntegerField(default=0) def __str__(self): return self.author.username class Tag(models.Model): name = models.CharField(max_length=50) discription = models.CharField(max_length=500, default="This is description") use_cnt = models.IntegerField(default=0) def __str__(self): return self.name Here is serializer: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' read_only_fields = ['use_cnt'] class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True ) answers = AnswerSerializer(many=True, read_only=True) class Meta: model = Question fields = '__all__' def create(self, validated_data): tags_data = validated_data.pop('tags') question = Question.objects.create(**validated_data) for tag_data … -
Filter a querryset in Django based on a changing value
I build a Blogpost App with Django and want comments under the blogpost. I can allready post new comments, and see comments, but i see every comment under every blogpost. In the database every comment is linked to the correct blogpost. class blogpost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) title = models.TextField() slug = models.SlugField(unique=True) content = models.TextField(null=True, blank=True) class blogcommment(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) post = models.ForeignKey(blogpost, default=1, null=True, on_delete=models.SET_NULL) title = models.TextField() content = models.TextField(null=True, blank=True) def blogpost_detail_view (request, slug): # Blogeintrag anzeigen obj = blogpost.objects.get(slug=slug) form = blogcommentform(request.POST or None) qs = blogcommment.objects.filter(***What should stay here and why?***) if form.is_valid(): comment = blogcommment.objects.create(**form.cleaned_data) form = blogcommentform template_name = 'blogpost_detail.html' context = {"object": obj,'form': form,'object_list': qs} return render(request, template_name, context) -
Django get_queryset filtering with multiple select
I doing a form of filtering by the foreignkey field with two search conditions: OR and AND and multiple choices. forms.py class EmployeeSkillFilter(forms.ModelForm): skills = forms.ModelMultipleChoiceField(queryset=Technology.objects.all(), ) class Meta: model = Employee fields = ['skills'] templates.py <form method="get" enctype="multipart/form-data"> {% csrf_token %} <input type="checkbox" name="and" value="AND"> Choice and<br> <input type="checkbox" name="or" value="OR"> Choice OR<br> {{ skill_filter }} <button type="submit" class="btn btn-info" type="button">Go!</button> </form> views.py class AccountList(AuthorizedMixin, ListView): model = Employee template_name = 'employee_list.html' def get_queryset(self, *args, **kwargs): condition_and = self.request.GET.get('and', None) condition_or = self.request.GET.get('and', None) skill = self.request.GET.get('skills', None) if condition_and and skill: object_list = self.model.objects.filter(skills__name_id=skill) ?????? if condition_or and tech: object_list = self.model.objects.filter( Q(skills__name_id=skill) | Q(skills__name_id=skill) ) ????? else: object_list = self.model.objects.all() My urls looks like localhost://....or=OR&skills=5&skills=4&skills=3 The problem is that when I select multiple objects in a form, I don't know how to pass them all to the condition skills__name_id=skill -
How can i set a Django render block value in the "with template tag"?
I am displaying dynamic title based on different views in the Django application, i want to set the same title on the 3 meta tags in my base.html file, which gets extended in all other templates. This works correctly, when i set a string on title variable: {% with title='TEST'%} <title>{% block page-title %}{% block title %}{% endblock %} | {{ agency.name }}{% endblock %}</title> <meta property="og:title" content="{{title}}" /> <meta name="twitter:title" content="{{title}}" /> {% endwith %} I want to set this dynamic title like: {% with title="{% block page-title %}{% block title %}{% endblock %} | {{agency.name }}{% endblock %}"%} <title>{{title}}</title> <meta property="og:title" content="{{title}}" /> <meta name="twitter:title" content="{{title}}" /> {% endwith %} But when i do like this, then i don't get the value in title variable: How can i set it to a variable in with template tag and then re-use that variable in other tags? or is there any other way of doing it ? -
How to connect from my PC to multi-tenant django project on remote PC
I have a PC at work and we started to use for our testing purposes before deploying our code to production server. The problem is that our django project is built with django-tenant-schemas. So, I deployed project on local (remote) PC, with docker with postgres and nginx containers. It works on that PC, but when I want to connect to the project from my PC or my colleague's one, it throws 404 error, stating no such tenant. I've tried nginx configuration, changed several times my /etc/hosts/ file, tried to change firewall on remote desktop (i just opened port, on which dockerized nignx works). My nginx config. backend:8000 and auth:8000 are names of docker containers in my docker-compose.yml and their ports. server { server_name test.backend; location /v1/ { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } server { server_name test.auth; location /v1/auth/ { proxy_pass http://auth:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } It should work this way. On remote PC project opened on http://test.localhost/v1/ URL and it works. The IP of remote PC is stored in my /etc/hosts file with … -
How to use session id in an ecommerce application for helping anonymous users use functionalities that logged in users can use?
I am making an E-commerce application, the final problem I have to solve is giving anonymous users access to use the cart, wishlist, billing and doing pretty much everything a logged in user can do. I know I have to use sessions But to be honest I don't get the document clearly, so please if anybody can help me solve the problem by writing the answer down below and showing me if there's a way to store session id's in models and then a user exits the browser the model objects get deleted. But if the user logins then all this information gets saved to his account id. If this way of handling the situation exists. Kindly show me how with examples, that would help you earn more points and better a chance to get respect from my side. Thank you, -
Message framework: Add message when saving Page class in Wagtail
So I would like to check if a certain field has changed and if so, display a info-message to the user that they should review other datapoints. I feel that the Django messages framework should be ideal for this, but I cant find where to hook in to the wagtail Page class to get this to work. Right now I have the check on the save method for the page like below, but I do not have access to the request object here, so I cant use massage.add_message (since this uses the request object as a parameter). What am I missing? def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.pk is not None: original = EventDetail.objects.get(pk=self.pk) if ( original.start_date != self.start_date and self.messages.all().count() > 0 ): messages.add_message( request, messages.INFO, _( "You have just changed starting time on an event that contains messages, please review the times for the message sends." ), ) -
Problem with saving a property of an object after validation
In my CreateView class I created an instance of my Wholesale_Client model. Inside form_valid() function I am fetching from my form some information which I will use in create_woocommerce_client_individually() function in order to post this record in my woocommerce website. Every user in woocommerce website has a post id which I have it as attribute in my Wholesale_Client model. My aim is after storing the wholesale client instance in my db and in woocommerce website(successfully), to fetch the current stored wholesale client record in order to update the post id of this user(from null to post id). How can I update information after fetching the record? Here is my code: Function for creating a woocommerce client in the website def create_woocommerce_client_individually(wcapi,name,surname,email): data = { "first_name": name, "last_name": surname, "email": email, } wcapi.post("customers", data).json() Function for giving the customer id from woocommerce website , using the api, to my record. def give_cid_to_client_individually(wcapi,email): r=wcapi.get("customers?email="+str(email)).json() post_id=r[0]['id'] fetched_client=Wholesale_Client.objects.get(email=email) fetched_client.cid=int(post_id) fetched_client.save() Here (is the problem) despite the fact that the record is fetched successfully the post_id is not saved to the cid attribute of my model. My CBV class WholesaleClientCreateView(LoginRequiredMixin, CreateView): model = Wholesale_Client form_class = WholesaleClientForm success_url = reverse_lazy('wholesale_clients_list') template_name='wholesale_clients/wholesale_client_create_form.html' def form_valid(self, form): print("Inside …