Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to replace special text with other special text - Python
How do I change my special string to a different value if value appears? My variables special_url = http://127.0.0.1:8000/ text = '...' special_symbol = {{URL}} Well i have text like this: It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- {{URL}} Or-less normal distribution of letters, as opposed to using 'Content here, content here', I need change above text to this when the value {{URL}} is in text It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- http://127.0.0.1:8000/ Or-less normal distribution of letters, as opposed to using 'Content here, content here', I try this, bot now work: massage = re.sub('{{URL}}', obj.special_url, text) -
"This field is required." Django rest framework
I've looked every answer in stack I cant find an answer. I 've created an API with django rest framework with some measurements . Im trying to post a TreeSensor measurement through postman or django API .Weather measurements works just fine but on my TreeSensor i get the following error even though they are identical besides the fields. { "soil_moisture_depth_1": [ "This field is required." ], "soil_moisture_depth_2": [ "This field is required." ] } Serializers : class TreeSensorMeasurementSerializer(serializers.ModelSerializer): class Meta: model = TreeSensorMeasurement fields = ["sensor", "datetime", "soil_moisture_depth_1","soil_moisture_depth_2","soil_moisture_depth_1_filtered","soil_moisture_depth_2_filtered", "soil_temperature"] class WeatherStationMeasurementSerializer(serializers.ModelSerializer): class Meta: model = WeatherStationMeasurement fields = ["sensor", "datetime", "wind_speed", "current_rain", "wind_direction", "solar_radiation", "air_temperature", "air_humidity", "air_pressure", "luminosity", "battery", "dew_point"] API : ########### TreeSensorMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'soi_moisture_depth_1' : request.data.get('soil_moisture_depth_1'), 'soi_moisture_depth_2' : request.data.get('soil_moisture_depth_2'), 'soi_moisture_depth_1_filtered' : request.data.get('soil_moisture_depth_1_filtered'), 'soi_moisture_depth_2_filtered' : request.data.get('soil_moisture_depth_2_filtered'), 'soil_temperature' : request.data.get('soil_temperature'), } serializer = TreeSensorMeasurementSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ########### WeatherStationMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'wind_speed' : request.data.get('wind_speed'), 'current_rain' : request.data.get('current_rain'), 'wind_direction' : request.data.get('wind_direction'), 'solar_radiation' : request.data.get('solar_radiation'), 'air_temperature' : request.data.get('air_temperature'), 'air_humidity' : request.data.get('air_humidity'), 'air_pressure' : request.data.get('air_pressure'), 'luminosity' : request.data.get('luminosity'), … -
How to get Image From Media Folder in Django
I uplaoded An image from fontend to media folder in django. How can I get that image inside my view.py file. so that I can process that image. image is saved in /media/images folder INPUT_IMAGE = '../media/images/inp7.jpg' but when I try to get image using this url its showing file not found. How can I fix it. -
Problem with webpack of vue3 cli v5 in order to combine it with django 4
For quite some time I'm trying to combine Django with Vue. What I'm trying to do is a simple template that uses the newer versions of these distributions. Quick environment from conda for Django and Vue3 cli project using all the juicy stuff like typescript, css processing, u testing, router, vuex and class-style ect. Everything I find in the internet is using older versions, I don't want that. I need help setting the webpack or some resources that could be helpful. -
How to get elements from callback url for generating an access token for OAuth1 using Django from behind a firewall?
I have a scenario where I'm building an app that is hosted on an ubuntu server. Currently I have all inbound traffic to the server blocked with only outbound being allowed. The only way to access the React/Django app on the server is either thru VPN or having an IP whitelisted. When doing the OAuth1 process (to connect with a data provider), I'm struggling to figure out how to keep my app closed from the public internet but still complete the OAuth 1 process for the end user. Given that this app's purpose is to aggregate user data (from user's who've granted permission), it's not practical for me to whitelist the IP address of every single end user. Currently, I'm considering making a form outside of my app for users to register with and then just having my app hourly check that form for new users so that it can then start the OAuth1 process and send the end user the authorization URL needed to grant permission to the data provider. At this point though, I have it where once the user signs up with their data provider, the callback URL redirects the user back to the Django app so … -
Nginx server not using project config
I am trying to create a configuration for the Nginx web server for my Django project. I would like to store the configuration of the web server in my project files. As I am using MacOS, the /sites-enabled directory was not present in the /usr/local/etc/nginx directory, so I've created it. In the /usr/local/etc/nginx/sites-enabled directory I have made a symbolic link to the project which seems to work. In the nginx.config file in the /usr/local/etc/nginx directory I have updated the file to make it see the sites-enabled directory: http { include /usr/local/etc/nginx/sites-enabled/*; The nginx -t command lists the following if I input incorrect data in my project nginx.conf file: nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful and correctly recognizes changes to it if I make some intentional errors: nginx: [emerg] invalid parameter "server_name" in /usr/local/etc/nginx/sites-enabled/linkem-all:6 nginx: configuration file /usr/local/etc/nginx/nginx.conf test failed The problem is that despite my changing the port to listen to in the nginx.conf file located in my project: server { # port nginx will be listening to listen 8000; # server ip address server_name 127.0.0.1.; # logs stored within the project access_log path/to/nginx-acces.log; error_log /path/to/nginx-error.log; # pass traffic from nginx … -
Django Server Error: port is already in use, docker
When working with Docker and Django setup Initially sometime we will getting this error port 5432 already in use or TCP/IP not able to make connection. How to resolve this issue please find below. -
In my Django project I have two similar url
I have a question with my sites urls. When someone want to go mysite.com I redirect them to mysite.com/register. url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), Also I have another url that allows to write somethings after the part of register. For example when someone goes to this website mysite.com/register/kh-54-m2-fc it allows to go that: url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), But when I use these urls together my guaform view doesn't work. And it goes to customer_form2.html. When someone goes this site: mysite.com/register/ anything I want them go to customer_form.html. How can I seperate these urls? urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), ] views.py from django.shortcuts import render,HttpResponse from olvapp.models import Customer from olvapp.forms import CustomerForm,CustomerForm2 from django.conf import settings from django.http import HttpResponseRedirect from django.urls import reverse from olvapp import forms def guaform(request,pk): theurl = request.get_full_path() orderid = theurl[10:] form = CustomerForm(initial={'order_id':orderid}) if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form.html',{'form':form}) def guaform2(request): form = CustomerForm2() if request.method == "POST": form = CustomerForm2(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form2.html',{'form':form}) -
Django DecimalRangeField form validation will only accept whole numbers
All of my DecimalRangeField fields work as expected when changing values in admin but my form won't accept non-whole numbers: Interestingly, if I set the lower default value as a non-whole number, the validation tries to force any whole number added to the lowest default. For example, if I define a field like this in models.py: my_field= DecimalRangeField( blank=True, default=(0.05, 5), validators=[RangeMinValueValidator(0.05), RangeMaxValueValidator(5)], ) I get the following warning: Maybe I am missing something in the field definition or there is something I don't understand about how Django converts the input into a decimal but I've not been able to find anything online about this. Any help would be greatly appreciated :) -
pytest + django giving me a database error when fixture scope is 'module'
I have the following inside conftest.py @pytest.mark.django_db @pytest.fixture(scope='module') def thing(): print('sleeping') # represents a very expensive function that i want to only ever once once per module Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Inside tests.py @pytest.mark.django_db def test_thing(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db def test_thing2(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db @pytest.mark.usefixtures('thing') def test_thing3(): assert models.Thing.objects.count() > 1 All three tests throw the same error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I've tried using scope='session' / scope='class' / scope='package' / scope='module' -- the only one that works is `scope='function' which defeats the purpose of what I'm trying to accomplish. I want to be able to create all these items ONCE per module, not once per test. Note: I ran into this issue with a large code base and created a new django project with a single app to test and see if the problem was the existing test code, and it failed on a standalone test also. Not that it matters, but the models.py class Thing(models.Model): thing = models.CharField(max_length=100) -
Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$']
It is basically an e-Commerce website. Everything working perfectly but When I log out then occurs the below error. What will be the relevant solution? NoReverseMatch at / Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 16 May 2022 15:31:17 +0000 template: <a href="{% url 'profile_info_update' user.pk %}" class="edit_btn btn"> edit </a> urls.py: path('profile_info_update/<int:pk>', views.profile_info_update.as_view(), name="profile_info_update") views: class profile_info_update(UpdateView): model = User from_class = change_profile_info fields = 'first_name','last_name','email' template_name = '33_change_profile_info.html' success_url =("/") forms.py: class change_profile_info(forms.ModelForm): first_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) last_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) email = forms.EmailField(widget=forms.FileInput(attrs={'class':"form-control"})) class Meta: model = User fields = ('first_name','last_name','email',) -
Django update_or_create()
I'm trying to use Django update_or_create() but I could not pass the pk (obj_key) to defaults. The idea is filter by user_id and wallet_id and update if exist or create if not. class ModelSelectedWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.name = models.ForeignKey(ModelWallet, default=1, on_delete=models.CASCADE) created = models.DateField(verbose_name='Created', auto_now_add=True) modified = models.DateField(verbose_name='Modified', auto_now=True) created_by = models.ForeignKey('auth.User', related_name='selected_wallet_created_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) modified_by = models.ForeignKey('auth.User', related_name='selected_wallet_modified_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) def select_wallet(request): if request.method == "POST": wallet_id = request.POST['wallet_id'] user = get_current_user() user_id = user.id db = ModelSelectedWallet obj_key = db.objects.filter(user_id__exact=user_id, wallet_id__exact=wallet_id).values('id')[0]['id'] defaults = {'id': obj_key} try: obj = db.objects.get(user_id=user_id, wallet_id=wallet_id) for key, value in defaults.items(): setattr(obj, key, value) obj.save() except db.DoesNotExist: new_values = { 'created': datetime.datetime.now().strftime ("%Y-%m-%d"), 'created_by_id': user_id, 'modified_by_id': user_id, 'wallet_id': wallet_id, 'user_id': user_id } new_values.update(defaults) obj = db(**new_values) obj.save() -
Django view. Upload/modify one CSV/Download modified csv
i'm trying to create and API for some validation: I want to have a option to upload one CSV. I want to pass that CSV through some validations, to modify the original CSV (to add 2 new columns) I want to have a posibility to download the modified CSV (with my 2 new columns) I implemented the first part, i created the validation, but after i download, i've got the same output (file wasn't modified) Could anyone help me with this part pls? This is my code for my view: def upload(request): context = {} if request.method == 'POST': promo2 = request.FILES['document'] if request.method == 'GET': promo2 = promo2[~promo2['COMP_ARTICLE_PROMO_TYPE'].isna()] for index, row in promo2.iterrows(): promo2 = pd.read_csv(promo2, sep=';') if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if 0.95 < round(row['COMP_ART_PRICE'] * 0.80, 2) / row['COMP_ARTICLE_PROMO_PRICE_PER_UNIT'] < 1.05: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'WRONG' if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if row['COMP_ARTICLE_PROMO_PERCENT'] == 20: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'WRONG' #fs = FileSystemStorage() #name = fs.save(promo2.name, promo2) #context['url'] = fs.url(name) #promo2.to_excel(response, engine='xlsxwriter', index=False) fs = FileSystemStorage() name = fs.save(promo2.name, promo2) context['url'] = fs.url(name) return render(request, 'upload.html', context) Here is my front … -
Django-rest-framework - fetching data from another server's DB
I made with Django REST Framework an API that i use for my project which is a Flutter app. *BUT, i want to add some data from another Server's database, can i do it in Django REST Framework, and then include those in my API ? -
How to differentiate access to data at the database server level?
In DB i have three roles: guest, client and admin. In my django project, there are three connections under these roles DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'guest', 'PASSWORD': 'guest', 'HOST': 'localhost', 'PORT': 5432, }, 'admin': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': 5432, }, 'customer': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'customer', 'PASSWORD': 'customer', 'HOST': 'localhost', 'PORT': 5432, } } How and where can I change the connection to the database depending on whether the user is authenticated or not? -
DJANGO FORM - how to change save location file uploaded
i don't use models form but only form. How to change location file when i uploaded? i want the file just go to /mp3 folder. And now i got error : UnboundLocalError at / local variable 'form' referenced before assignment and this my code : def homepage(request): if request.method == "POST": form = Audio_store(request.POST, request.FILES) # form = AudioForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['record']) return HttpResponseRedirect('mp3/') return render(request, "homepage.html", {'form': form}) forms.py : from django import forms class Audio_store(forms.Form): record=forms.FileField() and my error msg : my folder: -
How to get the data associated with a checkbox in Django views
I have a database that I'm trying to access via a template in Django. I'd like to be able to select some checkboxes and have it return the items associated with those checkboxes in my views.py so I can perform some logic on that data. template.py <input type="checkbox" checked autocomplete="off" name="tag" value={{ recipe.id }} />{{ recipe }} views.py def create_list(request): check_values = request.POST.getlist('tag') context = {'check_values': check_values) return render(request, 'grocery_lists/create_list.html', context) The create_list.html page simply displays {{ check_values }}. This was my attempt at a troubleshooting step so I could see what was stored in the variable check_values, However, check_values ends up being an empty list. I'm having trouble finding a solution that fits my use case. Thank you in advance. -
Django DRF - Updating many-to-one model in serializer
My models structure is pretty straightforward: a many to one relationship where a set of Conditions references one Item by the foreign key. And here we have the corresponding serializers.py: class ConditionSerializer(serializers.ModelSerializer): class Meta: model = Condition fields = ('condition_id','name', 'left', 'operator', 'right') class ItemSerializer(serializers.ModelSerializer): conditions = ConditionSerializer(many=True, read_only=True) def create(self, validated_data): conditions_data = validated_data.pop("conditions") item = Item.objects.create(**validated_data) for condition_data in conditions_data: Condition.objects.create(item=item, **condition_data) return item def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) conditions_data = validated_data.get('conditions', instance.conditions) for c in conditions_data.all(): print(c.name) # it correctly prints out the value instance.conditions.set(conditions_data.all()) # Doesn't update the instance instance.save() return instance class Meta: model = Item fields = ('item_id', 'name', 'conditions') The problem is in the update function: instance.name is correctly updated; instance.conditions.set(conditions_data.all()) is not. No error is displayed, since the response is 200OK. I also put the for loop printing of field of the Condition object (name) and it successfully is displayed, showing that the data is correctly read. I've tried to address the issue removing the read_only=True from the ConditionSerializer, but the situation got worse since I receive the error: AttributeError: 'list' object has no attribute 'all' Maybe the issue is related to the foreign key management. Is there a … -
The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead
How can i fix it? ERROR MESSAGE The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead. My Views.py def add_comment(request, pk): post = ProductList.objects.get(pk=pk) if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.product = post comment.save() return redirect('index', pk=post.pk) else: form = CommentFrom() return render(request, 'shopping_mall/add_comment.html', {'form':form}) My urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment/', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] -
Django's `date_hierarchy` not showing the correct date in filters
I have date_hierarchy on a date field in my ModelAdmin. The day filters at the top don't match the actual dates in the list. For example, when I click "May 16", it doesn't show any results (the dates only go up to May 15). Is this the expected behavior? My guess is there's something going on with UTC time vs timezone, but I'm not sure why. -
Django Application verify user can only see items relevant to them
My issue is that I can list all the clients in the database and these occur on all account managers detail pages. What I want to achieve is to list only those clients that appear for a specific account manager but to date everything I have tried does not work. This is the Client Model: class Client(models.Model): client_name = models.CharField(max_length=255) account_manager = models.ForeignKey( AccountManager, on_delete=models.CASCADE, related_name="clients", ) My views.py currently looks like this: class AccountManagerDetailView(LoginRequiredMixin, DetailView): model = AccountManager template_name = "accountmanagers/dashboard.html" context_object_name = "ams" def get_object(self, *args, **kwargs): return self.request.user def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context["clients"] = Client.objects.all() return context And my urls.py urlpatterns = [ path("detail", views.AccountManagerDetailView.as_view(), name="detail"), ] -
access form from another funcion
Question is.. I have static page profil.py: def profil(request, pk): context = {} person = User.objects.get(id=pk) try: person.profesor except Profesor.DoesNotExist: context['ucenik'] = Ucenik.objects.get(id=person.ucenik.id) else: context['profesor'] = Profesor.objects.get(id=person.profesor.id) return render(request, "profil.html", context) and this: def profesor(request): profesor = request.user.profesor forma = ProfesorFormaSlika(instance=profesor) context = {'forma':forma} return render(request, 'pocetna_profesor.html', context) question is, how can i access {{ forma }} in HTML page from def profesor in def profil? -
What does reset password token protect against?
This is more of a concept question than a specific code one. I am building a web app in Django which almost entirely handles the password reset process. And it had me thinking what does the token do, I'm aware that it checks whether the same email that requested the reset is the one changing the password. But why is this needed If someone tried to send a reset email to someone elses email they would need that emails password to actually change it. Is the token just another layer of protection? Is it necessary? I also do not understand the way django handles it: path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), How does passing the token in here, which is the page you access when the reset email is sent to YOU, make it secure. The latter question isnt as important. -
How to fill 'initial value' in Django forms with current user data?
I went ahead and created a Form to update the user database entry. class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ("username", "first_name", "last_name", "email") But when I render the form all input fields are empty. How do I populate them with the user's data like current username and email? I use Bootstrap 5 to style it, but that should matter: <div class="mb-3"> <label for="{{ form.first_name.id_for_label }}" class="form-label">{{ form.first_name.label }}</label> {{ form.first_name|addcss:"form-control"}} </div> Problem is, I render the input field with the Django template engine and don't specifiy it myself. My idea was to chain template filters: <div class="mb-3"> <label for="{{ form.username.id_for_label }}" class="form-label">{{ form.username.label }}</label> {{ form.username|addcss:"form-control"|addplaceholder:user.username}} </div> But that didn't work because the first filter converts it to a widget: @register.filter(name="addcss") def addcss(field, css): return field.as_widget(attrs={"class": css}) Maybe you can recommend me a way on how to modify that filter or tell me a complety different approach. -
How can i change a field based on another m2m field?
So, what i'm tryna do here is set the status of an object based on the length of m2m field. Here's how it looks from django.db import models class Dependency(models.Model): dependency = models.SlugField('Шаблон') class Seo(models.Model): statuses = ( (1, 'Дефолтный'), (2, 'Дополнительный') ) dependencies = models.ManyToManyField( Dependency, verbose_name='Зависимости', blank=True, help_text='Оставьте пустым, если это дефолтный шаблон' ) h1 = models.CharField('Заголовок(h1)', max_length=200) title = models.CharField('Заголовок(title)', max_length=200) description = models.CharField('Описание', max_length=200) keywords = models.TextField('Ключевые слова') status = models.IntegerField('Статус', choices=statuses, blank=True, editable=False) def save(self, *args, **kwargs): if len(self.dependencies) == 0: self.status = 1 else: self.status = 2 # self.status = 1 # # print(len(self.dependencies)) super().save(*args, **kwargs) class Page(models.Model): pass But it throws me an error that goes like ValueError: "<Seo: Seo object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. And what it want to achieve is whenever the dependency field is empty then status should be 1 and otherwise it should be 2. But i couldn't find a way to do it.