Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when i update/edit data is duplicated instead of being updated in django
data is duplicated instead of being updated in django, please help me to overcome this i also tried update method but issues i have faced is image not displayed, therefore i is used save method which will save and make copy of anthor object which i dont want. it should update the same object. views.py def EuAdmin(request, pk): pi = EmailDb.objects.get(id=pk) if request.method == 'POST': institution = request.POST.get('institution', '') fullname = request.POST.get('fullname', '') email = request.POST.get('email', '') contact = request.POST.get('contact', '') position = request.POST.get('position', '') uploadd = request.FILES.get('upload', '') sdata = EmailDb(institution=institution, fullname=fullname, contact=contact, email=email, position=position, uploaddata=uploadd) sdata.save() return HttpResponseRedirect("/eadmin") return render(request, 'NEC/eupdate.html', {'pi': pi}) models.py class EmailDb(models.Model): institution = models.CharField(max_length=300, blank=True, null=True) fullname = models.CharField(max_length=50, blank=True, null=True) contact = models.IntegerField() email = models.CharField(max_length=300, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) uploaddata = models.FileField(upload_to='appointment_letter') def __str__(self): return self.fullname -
No module named 'project_name' with Django + Celery?
Day 2 of debugging this I have to turn to stackoverflow I'm on the edge. I used cookiecutter-django to generate my project months ago. Project name config/settings/... src/ app_name/ __init__.py manage.py when I create celery.py inside config I get an error because it is named after a package, so I googled and tried using absolute_import but I just went with naming the file celery_app.py like guys from django-cookie-cutter did celery_app.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base") app = Celery("my_awesome_project") #I tried this with 10 different names, doesn't make any difference # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django app configs. app.autodiscover_tasks() init.py inside config/ #from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery_app import app as celery_app __all__ = ('celery_app',) last lines of the traceback File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File … -
How to create relations between 3 models that inherits data from 3 forms in django
i have 3 models in my django project and all of them are bein populated form data that the users submits via 3 forms, i actually need to create relations between them in order to link the user with his own card details and his own otp here are my models from django.db import models # Create your models here. MONTH_CHOICES = [ ('', 'الشهر'), ('01', '01'), ('02', '02'), ('03', '03'), ('04', '04'), ('05', '05'), ('06', '06'), ('07', '07'), ('08', '08'), ('09', '09'), ('10', '10'), ('11', '11'), ('12', '12'), ] YEAR_CHOICES = [ ('', 'السنة'), ('23', '2023'), ('24', '2024'), ('25', '2025'), ('26', '2026'), ('27', '2027'), ('28', '2028'), ('29', '2029'), ('30', '2030'), ] class Payment(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False, unique=True) submission_date = models.DateTimeField(auto_now_add=True, null=True) user = models.ForeignKey('Users', on_delete=models.CASCADE, null=True) card_number = models.CharField(max_length=16, null=True ) month_pick = models.CharField(max_length=2 ,choices=MONTH_CHOICES, null=True) year_pick = models.CharField(max_length=4 ,choices=YEAR_CHOICES, null=True ) cvv = models.CharField(max_length=3, null=True) card_type = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.submission_date.strftime('%Y-%m-%d %H:%M') class Users(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False, unique=True) payments = models.ForeignKey(Payment, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=100, null=True) user_ip = models.GenericIPAddressField(null=True) def __str__(self): return self.full_name class OTP(models.Model): PENDING = 'PENDING' APPROVED = 'APPROVED' DECLINED = 'DECLINED' STATUS_CHOICES = [ (PENDING, 'Pending'), (APPROVED, … -
Django views and urls - can't runserver
I'm learning django and having issues with implementing this code below: from django.urls import path from . import views urlpatterns = [ path('members/', views.members, name='members'), ] The code above is stored in a urls.py file I created in an app folder as directed by the tutorial guide. However when I try to run it on the browser I get this message: The included URLconf '<module 'members.urls' from 'C:\Users\Chinasaokwu\Desktop\storefront\try-django\my_app\members\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. I don't know what to do here. I'm new to django. It's w3schools.com that I am using as a guide I'm still learning how views and urls work since I'm new to django but I understand that views are functions that take and return https requests/response, and that urls are used to implement views. -
Django Admin formfield_for_foreignkey for manytomany
My Model (simpliefied) we have tours: class Tour(models.Model): name = models.CharField(max_length=100) strecke = models.ManyToManyField(Strecke, through="Streckenreihenfolge") A tour has sections: class Strecke(models.Model): name = models.CharField(max_length=100) auftrag = models.ForeignKey("Auftrag", on_delete=models.CASCADE, null=True, blank=True) And the sections are put in order class Streckenreihenfolge(models.Model): strecke = models.ForeignKey(Strecke, on_delete=models.CASCADE) tour = models.ForeignKey("Tour", on_delete=models.CASCADE) reihenfolge = models.IntegerField() In my admin, I want to give some restrictions on which sections (Strecke) to show. I thought about using formfield_for_foreignkey. It gets called, but it doesn't have any impact on the options to select from: @admin.register(Tour) class TourAdmin(admin.ModelAdmin): class StreckenreihenfolgeAdminInline(admin.TabularInline): model = Streckenreihenfolge autocomplete_fields = ["strecke"] ordering = ["reihenfolge"] extra = 0 def formfield_for_foreignkey(self, db_field, request, **kwargs): print(db_field.name) if db_field.name == 'strecke': kwargs['queryset'] = Strecke.objects.filter(auftrag_id__exact=8) return super().formfield_for_foreignkey(db_field, request, **kwargs) inlines = [StreckenreihenfolgeAdminInline, ] Does formfield_for_foreignkey not work for manytomanyfields? -
Django Rest: how to mock FileField and ImageField to_representation()
I have a model with 2 fields: image (ImageField) and media (FileField). They both use a custom GoogleCloudMediaStorage. When writing my tests, I cannot access GCS, so I mocked the writing of the files by doing this: from unittest.mock import patch @patch('my_project.storage_backends.CustomGoogleCloudMediaStorage.save') def test(self, mock_save): mock_save.return_value = 'mocked_file.png' # rest of the test And it's working fine. The problem is now I have to test update and list views. When I do so, I have of course this error: google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. After digging it a bit, I see that the error is triggered by the serializer to_representation(). And more precisely in the FileField: def to_representation(self, value): if not value: return None use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL) if use_url: try: url = value.url # !! THIS LINE CAUSE THE ISSUE except AttributeError: return None request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url So I tried to mock FileField.to_representation() doing this: @patch('django.db.models.FileField.to_representation') def test_update(self, mock_representation): mock_representation.return_value = 'mocked_training_file_url' data = { 'title': 'Updated', } response = self.client.patch(. . .) But I have this error: Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line … -
Convert series datetime data into total hours
I've a dataframe named mainData_Frame with column 'Clearance Time' in the following format. Clearance Time 2 days 22:43:00 1 days 12:32:23 5 days 23:44:13 . . . . I need to convert all timedelta series at 'Clearance Time' column into numeric hours. What I applied is the following codes: import pandas as pd import datetime def convert_to_hours(time_string): time = datetime.datetime.strptime(time_string, '%d days %H:%M:%S') delta = datetime.timedelta(days=time.day, hours=time.hour, minutes=time.minute, seconds=time.second) return delta.total_seconds()/3600 timeData = pd.Series(mainData_Frame['Clearance Time']) num_Hours = timeData.apply(convert_to_hours) print(num_Hours) But got the following errors: TypeError: strptime() argument 1 must be str, not Timedelta I'm the beginner in python and having some project regarding this, please help to sort out. -
Is there a way to add context to Django reverse function?
Is it possible to pass context through the reverse function in Django in some way like reverse('foo', context={'bar':'baz'})? Or is there a better workaround? -
I need to write an if statement for adding an image next to an h1 tag in an unordered list, if the image exists
Attached is the wagtail template I have written so far. {% load wagtailimages_tags %} <section class="container"> <h2 class="text-center">{{ self.title }}</h2> <div class="general-alumnae-deck"> {% for member in self.general_member_cards %} {% if member.photo %} {% endif %} {% endfor %} </div> </section> Ultimately I want the code to look like <h2>Avatar Images</h2> <ul> <li><img src="img_avatar.png" alt="Avatar" class="avatar"> <h3> Bleu </h3></li> <li><img src="img_avatar2.png" alt="Avatar" class="avatar"> <h3> Red </h3></li> </ul> </body> </html> with the image popping up next to the "h3" tag if there exists a photo of course the image will be {{}} double bracketed for dynamic template. -
How do I ensure any object I create is saved in my django project?
I'm working on a simple chat app that creates rooms for users to join. You enter your room name and it checks if the room exists already. If it does, you're redirected to the room. If not, it creates a new room, saves the room and redirects you there. The issue I'm having is in saving the new room that is created. I keep getting a "DoesNotExist" error. "Room matching query does not exist." Here is the code: def check_view(request): room_entity = request.POST['room_name'] username = request.POST['username'] if Room.objects.filter(name=room_entity).exists(): return redirect('/' + str(room_entity) + '/?username=' + str(username)) else: new_room = Room.objects.create(name=room_entity) new_room.save() Room.save(new_room) return redirect('/' + str(room_entity) + '/?username=' + str(username)) def room(request, room_info): username = request.GET.get('username') room_details = Room.objects.get(name=room_info) return render(request, 'room.html', { 'username': username, 'room': room_info, 'room_details': room_details }) -
Django, Celery: use regex to consume all tasks that ends with
inside my task_routes in celery I'm trying to consume all tasks in a specific path that end with _export. app.conf.task_routes = ([ (re.compile(r'project\.app\.tasks\.export$'), {'queue': 'exports', 'routing_key': 'task.export'}), ]) It seems, that I missed something here. Im still not to familiar with regex, so I think I'm missing some character at the end!? Thanks and have a great weekend! -
django-storages[azure]: NotImplementedError: This backend doesn't support absolute paths
I have Django application with celery task that I am trying to run on Azure using the code from below. The main goal is to read python, yaml and template files when running celery task. I am getting the following error: NotImplementedError: This backend doesn't support absolute paths. I am using django-filer and django-storages[azure] to handle my media files and I use Azure Storage to store all my files. My model looks like this: class Mymodel(models.Model): ... id_config_file = FilerFileField(null=True, blank=True, related_name="spider_config_file", on_delete=models.CASCADE) yaml_config_file = FilerFileField(null=True, blank=True, related_name="yaml_config_file", on_delete=models.CASCADE) template_file = FilerFileField(null=True, blank=True, related_name="template_file", on_delete=models.CASCADE) Below is my celery task: @shared_task(name="schedule_test") def schedule_test(id): id = Mymodel.objects.get(id=id) id_config_file = id.id_config_file.file yaml_config_file = id.yaml_config_file.file template_file = id.template_file.file id_config_file_path = os.path.join(MEDIA_URL, f"{id_config_file}") yaml_config_file_path = os.path.join(MEDIA_URL, f"{yaml_config_file}") template_file_path = os.path.join(MEDIA_URL, f"{template_file}") spec = importlib.util.spec_from_file_location("id", id_config_file_path) id_module = importlib.util.module_from_spec(spec) sys.modules["id"] = id_module spec.loader.exec_module(id_module) asyncio.run(id_module.run( yaml_config_path = yaml_config_file_path, input_file_path = template_file_path, task_id = schedule_test.request.id )) return f"[id: {id}]" My settings.py contains Azure Storage config variables: DEFAULT_FILE_STORAGE = 'azure.storage_production.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/media/' Here is what I tried to implement but with no success: id_config_file_path = os.path.join(MEDIA_URL, f"{id_config_file}") id_config_file_path = f"{MEDIA_URL}{id_config_file}" id_config_file_path = f"{MEDIA_URL}{id_config_file.path}" id_config_file_path = f"{MEDIA_URL}{id_config_file.url}" id_config_file_path = f"{MEDIA_URL}{id_config_file.file}" Question How … -
How to access "context" from http request between two django apps
So i'm fairly new to django, html, and javascript. In my first app, I have a button that when I click it, it invokes an $.ajax type "GET" function. In the script of the html template of app1, I have the following: $('#btn_to_app2').click(function () { if(Object.keys(name).length > 0){ $.ajax( { type:"GET", url:"to_app2", data:{ 'name': JSON.stringify(name), 'place': JSON.stringify(place), }, success: function (data) { if(data["noted"] == 1){ window.location.href = "http://" + window.location.host + "/app2/"; } } } ) } The accessed url refers to a view function (defined in the url.py and views.py files of the corresponding app1). def to_app2(request): if request.is_ajax() and request.method == 'GET': name = json.loads(request.GET['name']) request.session['name'] = name place = json.loads(request.GET['place']) request.session['place'] = place return JsonResponse({ 'noted': 1, }) The data obtained is send to the next app using a http request. In the views.py file of app2, I have the following bit of code: def app2(request): context = { 'name': request.session['name'], 'place': request.session['place'] } return render(request, 'app2.html', context) How can I now access the information contained in the "context" variable within the script of the html-file of app2? I have tried the let name = {{ name | safe }}; framework, with quotes and without, but that … -
Django, legacy PostgreSQL database, multiple primary keys
I suppose that question as old as it possibly could be, but I still have a hope that maybe someone has found some magical solution. Everything is simple, I have a database (postgresql) with small table as an example, with already existing field with Primary key: enter image description here My goal is to add an ID field as a second primary key. My Model looks like this: class CdcConn(models.Model): id = models.BigAutoField(primary_key=True) conn_type = models.CharField(max_length=128, blank=True, null=True) conn_name = models.CharField(max_length=128) class Meta: managed = True db_table = 'cdc_conn' After migration the result output is: django.db.utils.ProgrammingError: multiple primary keys for table "cdc_conn" are not allowed Tried many options, unique_together, constraints, some additional modules such as django-viewflow, and so on. The issue is about 15 years old, documentation says that composite pk are not allowed, but still, I can't believe that such powerful tool as Django just can't handle that simple operation. Any thoughts would be highly appreciated. -
deleting a user model that extends abstractuser
I am trying to delete a user object that belongs to a User class that extends AbstractUser. The extending class looks something like this: class User(AbstractUser): name = CharField("Name", blank=True, max_length=255) def __str__(self): return self.username When I try to delete a user like this: user = User.objects.get(pk=self.user_id) user.delete() The user object is not deleted (at least from checking the user table in the database). Other models that have on_delete=models.CASCADE to my custom user class are deleted as expected but the actual user object is NOT deleted. When I try user = User.objects.get(pk=self.user_id) user.delete() user.delete() # adding extra delete() i.e. an extra user.delete(), then the user object is deleted, but also raises an exception (which is not unexpected) User object can't be deleted because its id attribute is set to None. but the user object along with other objects with FK relationship to the User class are deleted (as expected). Sounds like the object was "deleted" the first time I called user.delete()? But I can still see the row in my user's table. Not sure if related but, I see that the type of User to delete is <class 'django.utils.functional.SimpleLazyObject'> not the User model class. So, I'm trying to delete a … -
How to display the raw value of my queryset
I have this function, to show my querysets: funcionarios_aniver = FuncionarioAux.objects.filter(FuncionarioDataNasc__gte=dia_um, FuncionarioDataNasc__lte=ultimo_dia) But it returns the querysets in an array, for example: <QuerySet [<FuncionarioAux: Alberto Santos>, <FuncionarioAux: Josney Arman>]> I would like it to return the raw values, like: Alberto Santos, Josney Arman I already tried using .get() at the end of the function, but I got the following error: funcionarios.models.FuncionarioAux.MultipleObjectsReturned: get() returned more than one FuncionarioAux -- it returned 2! what can i do to resolve? -
UsercreationForm to check if email exists in database django
I've created a usercreationform and try to check if username and email is already exist in database or not. Here It only check for email if it is exist or not but it cannot check for the username. Views.py from django.shortcuts import render,redirect from . forms import signupform from django.contrib import messages from django.contrib.auth import login,authenticate,logout from django.contrib.auth.models import User def signup_data(request): form = signupform(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(username=username).exists(): messages.error(request,'Username is already taken') return redirect('signup') elif User.objects.filter(email=email).exists(): messages.error(request,'Email is already taken') return redirect('signup') else: form.save() messages.success(request,'Account Is Created') return redirect('signup') return render(request,'login_module/signup.html',{'form':form, 'message': messages}) Forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class signupform(UserCreationForm): username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label="Confirm Password",widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username','first_name','last_name','email','password1','password2'] -
Is there a way to use get_F00_display in parallel with values() in Django views.py
What I want to do : Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template. models.py class Leave(CommonFields): LEAVES_TYPES = [ ('10', _('Type 1')), ('20', _('Type 2')), ('30', _('Type 3')), ] owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10") def __str__(self): return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y") views.py def get_queryset(self): return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status') leave_list.html <td>{{leave.type}}</td> BUT : I want to return {{leave.get_type_display}} and at the same time Leave.objects.filter(is_active=True).**values**(...) How to ? Is there a better way to achieve this ? -
How to prevent storage of celery chord counter objects in database
I am experiencing an issue where the django_celery_results_chordcounter table is filling up fast making me run out of server space. It was growing from a few MBs to over 99GB. I have tried resolving this by setting CELERY_RESULT_EXPIRE=60 hoping that the celery backend cleanup task will help me clean up the table every minute but that was not happening. I ran the task and by the time the table had grown to about 7GB, I truncated it on the psql shell. This is definitely not a solution but I had to do this so that the task can be successful without increasing server resources. Here are the celery tasks leading to this problem. Items can be hundreds of thousands to millions. Server specs: 16vCPUs, 64GiB memory @celery_app.task(ignore_result=True) def get_for_one(item_id): # an IO-bound task pass @celery_app.task(ignore_result=True) def get_for_many(parent_id): tasks = [ group( get_for_one.s(item.id) for item in Item.objects.filter( owner__isnull=True, parent_id=parent_id ).iterator() ) ] chord(tasks)(get_for_many_callback.si(parent_id)) celery==5.2.7 Django==4.1.1 django-celery-beat==2.4.0 django-celery-results==2.4.0 -
django project - how to combine two different types of databases (sqlite3 into mssql)
I took over an unfinished project from someone else and built a new user system based on Django authentication syste. It is when everything is done I found out that the system was connected to the default sqlite3 db while everything else was connected to mssql... setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'nlp_db': { 'ENGINE': 'mssql', 'HOST': 'DESKTOP', 'PORT': '1433', 'NAME': 'my_db', 'USER': 'guest', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', }, }, } Anybody know how to combine the sqlite3 into the mssql? I have tried Django : Transfer data from Sqlite to another database and changed the setting.py to the codes below but got an error(seems not compatible) DATABASES = { 'default': { 'ENGINE': 'mssql', 'HOST': 'DESKTOP', 'PORT': '1433', 'NAME': 'my_db', 'USER': 'guest', 'PASSWORD': 'password', }, } Error Msg pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] Cannot insert the value NULL into column 'name', table 'my_db.dbo.django_content_type'; column does not allow nulls. INSERT fails. (515) my_db.dbo.django_content_type is a table already existed before in mssql db but empty. I don't know how to fix this or should I delete my_db.dbo.django_content_type? Anyone has any idea? Thanks in advance! -
Django: Count forloop.first only if a second if condition is met
I have the following (oversimplified example): {% for item in myitems %} {% if item == "orange" %} {% if forloop.first %} {{item}} {% endif %} {% endif %} {% endfor %} Let's say that my list myitems is ['apple','orange','watermelon']. The first loop will be item=apple so it won't print the item because it is not "orange". In the second loop now we have item=orange but it no longer fulfills if forloop.first` so it won't print the item. I want a forloop.first that print only if it fulfills getting inside the if orange condition. How can I achieve this? -
Django queryset to list of ids with integer values
I need to retrieve IDs from multiple queries and add them into a list. products = Product.objects.filter(category="Apple").values_list("product_id", flat=True) reviewed = Reviews.objects.filter(category="Apple").values_list("product_id", flat=True) selected_ids = [10,20,30] Then I tried all_products = selected_ids + products + reviewed This raised error as list cannot be added to queryset. so, I tried, all_product_ids = selected_ids + list(products) + list(reviewed) This works but, all_products has a mix of int and tuple values [10, 20, 30, (2,), (2,), (1,)] I need them to be [10, 20, 30, 2, 2, 1] -
celery 'function' object has no attribute 'delay' how to get return value after delay?
Hi I have a problem in getting async function return value. this is my views.py code def preprocess_log2(request,uuid): data = get_object_or_404(Adata, uuid=uuid) if request.method == "POST": result = log2_transform_task.delay(data.raw_path) test = result.get() data.mat_data = test data.save() return redirect("raptorlite:home") return render(request, 'raptorlite/detail.html',{"data":data}) this is my task code @shared_task def log2_transform_task(raw:str, out_dir = None) -> str: return out_name sorry for not uploading my source code but I checked result it work perfectly and it is my settings.py CELERY_BROKER_URL = 'redis://redis:6379/0' result_extended = True accept_content = ['application/json'] result_serializer = 'json' task_serializer = 'json' timezone = 'Asia/Seoul' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' enter image description here when I run code if not use result.get() it works well but I want to get return value so I followed celery docs however after using get to return value suddenly that error happended.. please help me.. I followed celery docs and I read about similar error case in here but I checked that function name do not duplicate -
Why my "friends_list" remains empty when my Django signal is triggered?
I am using a Django post_save signal to modify the Database content of Budget. In my response I get the friendsList filled with the user IDs, but when I use post_save signals and query and store it in friends_list I see that the list remains empty. My response: { "id": 5, "amount": 100, "budgetForSplitPay": 1, "friendsList": [ 2, 3 ] } My post_save signal code: @receiver(post_save, sender=SplitPayBudget) def post_save_splitpay_amount(sender, instance, created, **kwargs): Budget.objects.filter(user=instance.budgetForSplitPay.user).update(budgetofUser=F('budgetofUser') - instance.amount) friends_list = instance.friendsList.all() for friend in friends_list: Budget.objects.filter(user=friend.user).update(budgetofUser=F('budgetofUser') - instance.amount) My API call body which triggers this signal: { "budgetForSplitPay": "1", "amount": 100, "friendsList": [2, 3] } I want a solutions by which my friends_list should be initialised with [2, 3]. Thank You. I tried using friends_list = instance.friendsList.all() but the instance.friendsList.all() remains empty. -
Django create update form with pre filled data from database
Django create update form with pre filled data from database but custome html form i have attaced the vire, model and the html templet that i used insted of django form view.py i used this view for adding player def add_player (request): if request.method=='POST': Name=request.POST.get('Name') E_mail=request.POST.get('E_mail') Area_code = request.POST.get('Area_code', False) Phone_Number = request.POST.get('Phone_Number', False) Country = request.POST.get('Country', False) City = request.POST.get('City', False) State = request.POST.get('State', False) Zip_Code = request.POST.get('Zip_Code', False) Address = request.POST.get('Address', False) FIG_License_Number = request.POST.get('FIG_License_Number', False) Passport_Number = request.POST.get('Passport_Number', False) add_player= contact.objects.create(Name=Name,E_mail=E_mail,Area_code=Area_code, Phone_Number=Phone_Number, Country=Country, City=City, State=State, Zip_Code=Zip_Code, Address=Address, FIG_License_Number=FIG_License_Number, Passport_Number=Passport_Number) add_player.save() return redirect('/contact') else: pass return render(request, 'from/add_player.html') model.py class contact (models.Model): Name =models.CharField(max_length=200, null=False) E_mail =models.EmailField(max_length=200, null=True) Area_code =models.CharField(max_length=200, null=True) Phone_Number =models.CharField(max_length=200, null=True) Country =models.CharField(max_length=200, null= False) City =models.CharField(max_length=200, null= False) State =models.CharField(max_length=200, null= False) Zip_Code =models.CharField(max_length=200, null= False) Address =models.CharField(max_length=200, null= False) FIG_License_Number =models.CharField(max_length=200, null= False) Passport_Number =models.CharField(max_length=200, null= False) def __str__(self): return self.Name