Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to send response from an api to an active websocket connection
I am trying to push a api response to an active websocket, I have these functions in the consumer def send_message_from_api(message, chat): channel_layer = get_channel_layer() print('chann', channel_layer) chat_room = f"chat_{chat}" async_to_sync(channel_layer.group_send)( chat_room, { 'type': 'external.message', 'text': json.dumps(message), } ) def external_message(self, event): print('test', message) message = event['message'] self.send(text_data=message) and in the view function I call, Consumer.send_message_from_api(serializer.data, chat.id) I am new to websockets and django channels, the function def external_message is not getting called while I run the code. Can someone please help with this? Thanks -
Problem with making python DJANGO app working on hosting
My logs after error looks like that, but i dont have any idea what can i do.... My application is working perfectly on localserver, the site of hosting says that its problem with application??? I tried putting there only hello world, but it send same error. Traceback (most recent call last): File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 379, in <module> app_module = load_app() File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 80, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/usr/local/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/home/perqu/domains/perqu.usermd.net/public_python/passenger_wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' Traceback (most recent call last): File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 379, in <module> app_module = load_app() File "/usr/local/lib/ruby/gems/2.5/gems/passenger-6.0.7/src/helper-scripts/wsgi-loader.py", line 80, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/usr/local/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/home/perqu/domains/perqu.usermd.net/public_python/passenger_wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' -
Is it possible to access to a pickle file saved in a directory in Django views?
Let me explain, here is my problem: In order not to get bothered with a database, I saved two machine learning models in .pickle in a folder in my Django project. Then in the corresponding views.py I want to open and use this model. The fact is that all this works well when I run the server locally but once deployed on heroku, impossible to access these models and the site does not work. Do you have an idea, is it possible to use this method once deployed or do I have to save them in a database project files organization : main_folder > models_folder > saved_models_folder > my_model.pickle (here the model that I want to open) app_folder > views.py ( here is the file in wich I try to open the .pickle model) Actually I have this code, but it can't work because I'm not in the models folder when I try to open it. def open_model(file_name): base_dir = 'models_folder\\saved_models_folder' file_path = os.path.join(base_dir, file_name) if os.path.exists(file_path): print("Loading Trained Model") model = pickle.load(open(file_path, "rb")) else: print('No model with this name, check this and retry') model = None return model If someone has a little idea I am greatly interested Thanks. -
How to manage approved pending field with two models in Django?
I have a Django model called Authorized that has the sales_item foreignKey How can authorized person approve or decline the sales with adding some comments on sale object if salesmen add new sale in database? i am not able to understand that where i can add the approved or decline attributes models.py class Authorize(models.Model): managers = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sales_item = models.ForeignKey(Sale, on_delete=models.CASCADE, null=True, blank=True) comments = models.TextField(max_length=1000, blank=True) created_at = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Sale(models.Model): saler = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) customers = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) products = models.ManyToManyField(Product) content = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) -
Query a model via another model in Django
I have a model named Demand in my app class DemandFlows(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) class Demand(models.Model): demand_flows = models.ManyToManyField(DemandFlows) delivery_month = models.DateTimeField(blank=True, null=True) From this model I get the month and year and the kits used in that month like the following: d_o = Demand.objects.all() for i in d_o: print("month", i.delivery_month) m = i.delivery_month print("m", m.month) print("y", m.year) for k in i.demand_flows.all(): print("k", k.kit.pk) Now I have another model Allotment, How can I query this model such that I get the kit and the sum of alloted_quantity of the particular month I got by Demand model? Allotment: class AllotmentFlow(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) flows = models.ManyToManyField(AllotmentFlow) For e.g. I got the following from demand: m 12 y 2020 k 3 k 4 k 5 k 7 k 8 k 9 k 10 So how can I know the alloted_quantity of kit 3,4,5,7,8,9,10 in December, 2020? -
Get Month from django datetime model field
I am getting the following datetime from the model object: m = 2021-02-14 15:57:16.222000+00:00 How can I get the month from this ? m is : m = i.delivery_month When I try datetime.strptime(m[:10], "%Y-%m-%d").strftime("%d-%m-%Y") I am getting the following error: TypeError: 'datetime.datetime' object is not subscriptable -
Django: order by multi-level reverse look up
I have following 3 models class Product(models.Model): name = models.CharField( blank=False, max_length=256 ) class TaskGroup(models.Model): name = models.CharField( blank=False, max_length=256 ) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=False, blank=True ) class Task(models.Model): name = models.CharField( blank=False, max_length=256 ) task_group = models.ForeignKey( TaskGroup, on_delete=models.CASCADE, null=False, blank=True ) I want to get all the Products ordered by the created_at date of Task. How can I do this? Is it possible to do this using single query? -
Python string representation of object causes error while saving the object is database
I am working on a Django project. I am setting string representation of an object as the value of one of an object's property. this object is saving values in the database in Gujarati(an Indian language). I have set CHARACTER SET as utf8mb4 and COLLATION as utf8mb4_0900_ai_ci for entire table.(also used utf8mb4_general_ci and utf8mb4_unicode_ci) class MyModel(models.Model): some_value_in_gujarati = models.CharField(max_length=30) some_other_english_value = models.CharField(max_length=30) ... def __str__(self): return "%s" % (self.some_value_in_gujarati) while saving object for this model, I am getting error as follows Incorrect string value: '\\xE0\\xAA\\x95\\xE0\\xAA\\xBE...' for column 'object_repr' at row 1 However, when I don't include 'some_value_in_gujarati' in _str_ definition, I am able to save the object successfully. I also added _repr_ in the Model definition as follows but it is not working def __repr__(self): return "%s" % (self.some_value_in_gujarati) Kindly let me know if anybody has gone through the same issue. -
In Django, how can properly implement a custom mail back end?
My goal is simply to print out the subject line and recipients whenever an email is sent from Django, EDIT: and then send the email to its destination. So I have implemented a custom backend like this: from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, **kwargs): super().__init__(**kwargs) def send_messages(self, email_messages): for message in email_messages: recipients = '; '.join(message.to) print(f'{recipients} {message.subject}') return super().send_messages(email_messages) However when I try to send an email with this back end the log says: Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: Internal Server Error: /secure/rest/djauth/users/ Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: Traceback (most recent call last): Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File "/opt/theapp/venv3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: response = get_response(request) Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File "/opt/theapp/venv3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: response = wrapped_callback(request, *callback_args, **callback_kwargs) Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File "/opt/theapp/venv3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: return view_func(*args, **kwargs) Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File "/opt/theapp/venv3.8/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: return self.dispatch(request, *args, **kwargs) Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File "/opt/theapp/venv3.8/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: response = self.handle_exception(exc) Mar 15 08:44:19 ip-172-26-4-21 uwsgi[190188]: File … -
copy data from one folder to another on AWS S3 with python
I am looking for all the methods for copying the data from one folder to another on AWS S3 bucket. -
Django Dash live Update
File "C:\Users\Administrator\Desktop\cms项目\intelcms\plotly_django_tutorial\home\urls.py", line 5, in from home.dash_apps.finished_apps import secondexample File "C:\Users\Administrator\Desktop\cms项目\intelcms\plotly_django_tutorial\home\dash_apps\finished_apps\secondexample.py", line 48, in def update_metrics(n): File "C:\Users\Administrator\Desktop\cms项目\intelcms\venv\lib\site-packages\django_plotly_dash\dash_wrapper.py", line 345, in wrap_func func.expanded = DjangoDash.get_expanded_arguments(func, inputs, state) File "C:\Users\Administrator\Desktop\cms项目\intelcms\venv\lib\site-packages\django_plotly_dash\dash_wrapper.py", line 305, in get_expanded_arguments n_dash_parameters = len(inputs or []) + len(state or []) TypeError: object of type 'Input' has no len() Unable to find stateless DjangoApp called SecondExample I want to create a django live update app. hier is the bug report, when i use DjangoDash to create an app the first bug showed up, it saies that the input has no len(),i dont quite understand how this problem shows up. when i use dash.Dash to create an Django App the second bug showed up,but in the solo test the app is created, it is just not integrated in Django app. Blow is the full code. The difference is in line 22 and 23. Hope you can help me solve this Problem. Thanks a lot. 1. 2. import dash_core_components as dcc 3. import time 4. import datetime 5. import dash 6. import dash_html_components as html 7. from dash.dependencies import Input, Output 8. import plotly 9. import plotly.graph_objs as go 10. import plotly.express as px 11. from django_plotly_dash import DjangoDash 12. from … -
Get the value of the inline Radio button of bootstrap and pass it to Views.py in Django
I am trying to get the value of the Inline Radio button from my template and then pass it to the views.py. The Radio button is consists of the Choices field from my Models.py. I tried to use the request.POST.get('name of radio button') to pass the value to my views.py. I did not get any error message, but every time the action is triggered, no value is showing on the views. Models.py CATEGORY_CHOICES = ( ('Beverage', 'Beverage'), ('Pasta','Pasta'), ('Cake','Cake'), ('Bakery','Bakery'), ('Sandwiches','Sandwiches'), ) SIZES_CHOICES = ( ('Short', 'Short'), ('Tall', 'Tall'), ('Grande', 'Grande'), ('Venti', 'Venti') ) CAKE_CHOICES = ( ('SLICE','SLICE'), ('WHOLE','WHOLE'), ) def get_upload_path(instance, filename): return 'Items/{0}/{1}'.format(instance.name, filename) def create_new_ref_number(): return str(random.randint(1000000000, 9999999999)) class Item(models.Model): name = models.CharField(max_length=50) categories = models.CharField(choices=CATEGORY_CHOICES, max_length=50) sizes = models.CharField(choices=SIZES_CHOICES, max_length=50, null=True, blank=True, default="Short") cake_size = models.CharField(choices=CAKE_CHOICES, max_length=50, null=True, blank=True, default="SLICE") img = models.ImageField(upload_to=get_upload_path, null=True, blank=True) description = models.TextField() beverage_s_price = models.FloatField(null=True, blank=True) beverage_t_price = models.FloatField(null=True, blank=True) beverage_g_price = models.FloatField(null=True, blank=True) beverage_v_price = models.FloatField(null=True, blank=True) cake_slice_price = models.FloatField(null=True, blank=True) cake_whole_price = models.FloatField(null=True, blank=True) price = models.FloatField(default=0, null=True, blank=True) available = models.BooleanField(default=True) slug= models.SlugField(null=True, blank=True) def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("featured-food", kwargs={"slug": self.slug}) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ … -
Why does "'django_postgrespool2' isn't an available database backend" error occur in Django with multiple database engines?
What I'm Trying to Achieve I want to have two different database engines to select from when connecting to a PostgreSQL database. The reason is that we want to slowly move over to using the django_postgrespool2 from postgresql_psycopg2. So I want some db code to use the postgresql_psycopg2 engine and some code use the django_postgrespool2when connecting to the db. Error When starting Django and running the project I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "c:\users\knowe\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\django_postgrespool2\base.py", line 23, in <module> from sqlalchemy import event File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\sqlalchemy\__init__.py", line 10, in <module> from .schema import BLANK_SCHEMA # noqa File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\sqlalchemy\schema.py", line 12, in <module> from .sql.base import SchemaVisitor # noqa File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\sqlalchemy\sql\__init__.py", line 106, in <module> __go(locals()) File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\sqlalchemy\sql\__init__.py", line 103, in __go from . import naming # noqa File "C:\Users\Knowe\Documents\django\mbrain-gui\lib\site-packages\sqlalchemy\sql\naming.py", line 27, … -
Django ORM make Union Query with column not in common as null
Hi i want to make a query in Djang ORM like this Select Col1, Col2, Col3, Col4, Col5 from Table1 Union Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2 as you see Col4, Col5 are not in common but they will return null instead in Table2. How can i make the query in Django? -
I want to display department only if it contains hospital
Template displaying {% for datas in form %} <div class="card"> <div class="card-body"> <h5 class="card-title">Name : {{datas.fullname}}</h5> <p class="card-text">Location : {{datas.location}}</p> <p class="card-text">Category : {{datas.category}}</p> Checking if datas.category contains hospital or not {% if datas.category == 'HOSPITAL' or datas.category == 'Hospital' or datas.category == 'hospital' %} {% for depart in dept %} <p class="card-text">Department Name : {{ depart.dept_name }}</p> {% endfor %} {% else %} {% for sers in ser %} <p class="card-text">Service Name : {{sers.service_name}}</p> {% endfor %} {% endif %} <a href="{% url 'provideredit' datas.id %}" class="btn btn-warning">Edit</a> <a href="{% url 'providerview' datas.id %}" class="btn btn-info">View</a> <a href="{% url 'providerdelete' datas.id %}" class="btn btn-danger">Delete</a> </div> </div> {% endfor %} I want to display department if the category contains hospital else display services. Can anyone help me? -
How to post modal form and return to same template in django?
I have a Django form that has a field to select a client. If the user wants to add a new client there is a bootstrap modal with form How to save the new client form to database and then close modal and show the newly added client in the main template form? urls.py # Create quotation URL path('create/', views.createquotation, name='createquotation'), views.py @login_required def createquotation(request): if request.method == "GET": return render(request, 'quotations/create.html') create.html <form method="POST"> {% csrf_token %} <!-- Client Details with Reference Number and dated --> <div class="form-group"> <label for="selectedclient">Select Client</label> <input type="text" name="selectedclient" class="form-control" id="selectedclient"> </div> <div class="text-right"> <b style="font-size: smaller;">OR &nbsp;&nbsp;&nbsp;</b> <button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal" data- target="#exampleModal"> Add New Client </button> </div> <!-- Bootstrap Modal form is below this--> -
Python Django ignore atomic
My question is as follows. Let's say that I have a big logic that is happening (it can fail on multiple places), and it's wrapped with transaction.atomic on the high level. I would love if one part of the logic, could ignore that. I have one piece of code that just moves state of the table (let's say order to make it simple) At the start of operation I move order from waiting to in progress and I have 2 more stats (success and error). If exception happens, I would love to move it to the error state, and if not, to move it to success state. But, because it's all wrapped inside transcation.atomic, after exception, it goes back to waiting rather then error. Any idea how I can ignore atomic operation for one method wrapped inside it? -
Is there a way to search whole table for a specific keyword using Django ORM?
I need to search whole table (django model) for a keyword given by user. It's going to be further used as a boolean search feature. My idea was to dynamically add Q objects but I have failed to implement that. Are there any other useful ORM methods I should use? Or am I stuck with SQL injection? Thanks so much in advance for any help! -
How to differentiate new users and existing users on OAuth using Django?
I want my users to be differentiated between : Returning users, and New users while using OAuth such that when I use django-allauth package for OAuth using Google, Github, and LinkedIn, it doesn't create a new user from the login page which is meant only for existing users but rather redirect them to the sign up page. So far I've found that new users just end up making new accounts from the login page as well and I don't want that in the case I'm making it an invite-only app or something similar. -
Why is my python class variable (ex. Post) unable to be used within the class to declare a variable. - django
I keep getting an error while trying to runserver(python manage.py runserver) The error is a nameError and says that Post is not defined. this is from models.py ''' from`` django.db import models class Post(models.Model): posts = Post.objects.all() title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique = True) body = models.TextField(blank=True, db_index = True) date_pub = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title ''' this is from settings.py ''' from django.shortcuts import render from blog.models import Post # # Create your views here. def home(request): return render(request, 'blog/index.html') def index(request): posts = Post.objects.all() return render(request, 'blog/index.html', context={'posts': posts}) File "C:\Users\MaxLe\Desktop\My_Django_Stuff\blogengine\blog\models.py", line 9, in Post posts = Post.objects.all() NameError: name 'Post' is not defined NameError: name 'Post' is not defined '''`enter code here` All help is appreciated as I'm just trying to get off my feet. Thanks. -
How to correctly update a nested Object in django rest framework?
i have a nested model that i want to CRUD. i made the Create method as bellow and now i'm getting a new error in my career i have tow models: class Planning(models.Model): name = models.CharField(max_length=50) salle_sport = models.ForeignKey(SalleSport, verbose_name="Salle de sport", related_name='plannings', on_delete=models.CASCADE, null=True, blank=True) class SalleSport(models.Model): name = models.CharField( max_length=50) adresse = models.CharField( max_length=50) phone = models.CharField(max_length=50) def __str__(self): return self.name i made one serializer For the GET and an other for POST & PUT for the POST method i used the PrimaryKeyRelatedField to get the SalleSport name as a PK to used it as reference. Here is my serializer code of the models : from salle_sport.models import SalleSport from .models import Planning class NameSalleSportSerialiser(serializers.ModelSerializer): class Meta: model = SalleSport fields= ('name',) class PlanningListSerialiser(serializers.ModelSerializer): salle_sport = NameSalleSportSerialiser() class Meta: model = Planning fields= ('id', 'name', 'salle_sport') class PlanningSerialiser(serializers.ModelSerializer): salle_sport = serializers.PrimaryKeyRelatedField(queryset= SalleSport.objects.all(),source='salle_sport.name') class Meta: model = Planning fields= ('id', 'name', 'salle_sport') def create(self, validated_data): plan = Planning.objects.create(salle_sport=validated_data['salle_sport']['name'], name=validated_data['name']) return plan def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() nested_serializer = self.fields['salle_sport'] salle_data = validated_data.pop('salle_sport') nested_instance = instance.salle_sport nested_instance.name = salle_data['name'] nested_instance.save() ### raise TypeError( ### TypeError: Tried to update field salle_sport.SalleSport.name with a model instance, <SalleSport: newValue>. … -
accessing variable to another apps django
I have two apps in django ├── search │ └── views.py │ └── preprocessing └── views.py in search/views.py, i have dataframe with the code like this: df = pd.DataFrame() def scrape(request): global df items = comments + replies df = pd.DataFrame(items, columns=['Comments']) return render(request, 'search/scrape.html', context) And, i want to use the dataframe from search/views.py in second apps preprocessing/views.py from search.views import df def index(request): print(df) context = { } return render(request, 'preprocessing/preprocessing.html') but the problem is dataframe that i pass to preprocessing/views.py is empty so, how can i pass the datframe also with the value inside from search/views.py thx for ur help -
How to create a loop for a approval system?
I created a approval system for my project. I have several users. These users are analyst, lead, manager, etc. I have a credit limit table (DoaTable) in my system. I want to when a lead type user updates a field in this table it shouldn't be accepted until a manager approves it. So, the old value should be valid until the manager approves the new values, and when the manager approves it the new value should be accepted. I created a new model. When a lead wants to update this table, data will save a second model (table) called as DoaTableBeforeApproval. In this way, when a manager approved the table which a lead update, DoaTable should be equal to new table (DoaTableBeforeApproval). How can I create a loop for this equality? models.py LIMITS = ( ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ..'), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ... ) class DoaTable(models.Model): rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) class DoaTableBeforeApproval(models.Model): rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) … -
How to pass the object itself which is creating in model method save()
I would like to pass the object which itself is creating in the model method save. How can I do it? class Legal(ApplicationAbstractFields): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='legal') legal_product_cat = models.ForeignKey(TechniqueCategory, blank=True, null=True, on_delete=models.CASCADE) legal_product_cat_type = models.ForeignKey(TechniqueCategoryType, blank=True, null=True, on_delete=models.CASCADE) legal_product_name = models.CharField(blank=True, null=True, max_length=254) legal_name = models.CharField(blank=True, null=True, max_length=254) def save(self, force_insert=False, force_update=False, using=None, update_fields=None, *args, **kwargs): if self.is_sent == True: Notification.objects.create( # HERE HOW TO PASS THE OBJECT Legal itself??? legal=self.objects, is_viewed=False, user=self.user, event='Your application was received') super().save(*args, **kwargs) -
In drf can i use image like this <img src={`http://127.0.0.1:8000${mapped.product.img}`} alt="one" />?
{list.map((list_item) => { return ( {list_item.quantity} {list_item.product.name} {list_item.product.type} {list_item.product.quantity} <img src={http://127.0.0.1:8000${list_item.product.img}} alt="one" /> ); })}