Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Documenting Django using UML
Hello Stack Overflow Community I'm trying to document my project and I have doubled on how to translate Django Views into UML Class Diagrams. I have to mention that I'm not using class views, just normal views. Can you please tell me if this is ok? Do I need to let know the reader what I'm trying to achieve or it is clear what the diagram says? Many thanks in advance for your feedback This is the code def index_crypto(request): import requests import json #Api Call url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1' headers = {'Accepts': 'application/json','X-CMC_PRO_API_KEY':'xxxxxxxxxx',} params = {'convert' :'USD'} api_request = requests.get(url, headers= headers,params= params) #Request Object try: data = json.loads(api_request.content) #JSON file containing data. except Exception as e: data = "Error...." print(e) api_assets= [] for i in data["data"]: api_assets.append(i) return render(request,'index_crypto.html',{'api_assets': api_assets}) -
Why am I getting '[Errno 13] Permission denied: '/static'' when uploading file to django admin even when I have permissions?
I recently finished deploying my website using apache2 and django. I was testing everything, icluding the uploading process. But, when I select a file to upload and hit 'Save', it gives me an error: PermissionError at /admin/path/path2/add/ [Errno 13] Permission denied: '/static' This is my apache2 config file (just the static folder part): Alias /static /home/alexholst/excelsite/static <Directory /home/alexholst/excelsite/static> Require all granted </Directory> I have all the right permissions, since I wrote these commands to allow permissions: sudo chown -R :www-data project/static sudo chmod -R 775 project/static sudo chown :www-data project/db.sqlite3 sudo chmod 664 project/db.sqlite3 sudo chown :www-data project/ This works, since when I do ls -l, the permissions are correct. My settings.py file has this as STATIC_ROOT and STATIC_URL: STATIC_URL = '/static/' STATIC_ROOT = '/home/user/project/static' I dont know if this has to do with anything, but my css does load so i dont think it should have to do with the settings.py. Any suggestions are very much appreciated! -
I want to use a python code in django template
I have this code in my django template: {% for i in concedii %} <tr> <td> {{ i.7 }} </td> <td> {{ i.8 }} </td> {% for d in luna %} <td class="text-center"> {% if d.0 > i.5 > d.1%} {{ i.4 }} {% endif %} </td> {% endfor %} <td>-</td> </tr> {% endfor %} And inside this code I would like to implement this code: val1 = 23.04 # this is the d.0 from django template above val2 = 29.04 # this is the d.1 from django template above tobe1 = 24.04 # this is the i.5 from django template above tobe2 = 27.04 # this is the i.6 from django template above if all(val1 < x < val2 for x in (tobe1, tobe2)): print(saptamani) -
Deploying Keras model in django
I am using Django to build APIs for my project. What I was trying to do is load a Keras Conv Net model to process the requests made to the API's endpoint, but Keras seems to have a problem loading the model in Django. The error is as follows: '_thread._local' object has no attribute 'value' and it points to the line where I load my Keras model. Here's the post request handler in my Django apps view file def post(self, request): image_serializer = MalariaDiseaseSerializers(data=request.data) if image_serializer.is_valid(): image_serializer.save() __model = load_model('trained_models/malaria/malaria.h5') image = cv2.imread("media/"+str(request.FILES['image'])) image_array = Image.fromarray(image , 'RGB') resize_img = image_array.resize((50 , 50)) resize_img = np.array(resize_img).reshape(1,50,50,3)/255. prediction = __model.predict(resize_img) index = np.argmax(prediction) self.__response_data['prediction'] = self.__classes[index] self.__response_data['probability'] = prediction[index] return Response(self.__response_data, status=status.HTTP_201_CREATED) return Response(image_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can someone help me out with this? Thank you! -
django docs email is not activated after click on email confirmation link in Django mail backend
I created the Django email backend for active the email during the registration. But in my case When I register the account and confirmation email is sent on my email and after click on the confirmation link then it's not activate the user's account and link is not redirected on login page. setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'your_mail@gmail.com' EMAIL_HOST_PASSWORD = 'XXXXXXXXXX' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = "USERNAME" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = reverse_lazy('account_confirm_complete') ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = reverse_lazy('account_confirm_complete') urls.py urlpatterns = [ url(r'^user_reg/registration/account-email-verification-sent/', email_view.null_view, name='account_email_verification_sent'), url(r'^user_reg/registration/account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), url(r'^user_reg/registration/complete/$', email_view.complete_view, name='account_confirm_complete'), url(r'^user_reg/password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', email_view.null_view, name='password_reset_confirm'), path('admin/', admin.site.urls), path('user_reg/', include('users.urls', namespace="users")), path('user_reg/registration/', include('rest_auth.registration.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And below the email message Greeting from example.com! You're receiving this e-mail because user usertest has given yours as an e-mail address to connect their account via API. To confirm this is correct, go to http://127.0.0.1:8000/user/registration/account-confirm-email/Mjg:1jSeJC:4btJkSnHSxYN7w5CITEPydcG9cA/ Thank you from example.com! example.com Where is the problem and how can I solve this?. Please help me. Thank you! -
django: cannot connect django app to server in production
I am deploying my django app with AWS EC2, Gunicorn with supervisor and Nginx. I have religiously followed tutorials but my incompetence prevent me to spot where I am mistaken. When connecting to my IP address or my domain name I get an error saying that they cannot be reached or it tryes to connect and then says “took too long to connect” I am thinking it has to issues related with hosts because in development the app works like a charm settings.py ALLOWED_HOSTS = ALLOWED_HOSTS = ['xxx.xxx.xxx.xxx', '127.0.0.1', 'mysite.com','www.mysite.com'] (they also are set up in /etc/hosts/.) My nginx configuration: server { listen 80; server_name xxx.xxx.xxx.xxx mysite.com www.mysite.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /static { autoindex on; alias /home/ubuntu/exostocksaas/inventory4/collected_static/; } } and this is my gunicorn configuration: [program:gunicorn] directory=/home/ubuntu/exostocksaas command=/home/ubuntu/Exos/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/exostocksaas/app.sock in$ autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log user=root [group:guni] programs:gunicorn And I have also configurate my EC2 instance to also accept trafic from port 8000. when I run runserver 0.0.0.0:8000 (i know its not recommanded but just to test and launch the IP address on port 8000, I get 404 error. At this point I am feeling a little bit lost and not sure … -
Django - Model not created when user creates an account
recently, I created a new model nammed "Points" but when I create a new account, the account's model is not created. The problem may be in my signals.py : (I don't really know how it works) from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Points @receiver(post_save, sender=User) def create_model(sender, instance, created, **kwargs): if created: Points.objects.create(user=instance) @receiver(post_save, sender=User) def save_model(sender, instance, **kwargs): instance.Points.save() Here's my models.py : from django.db import models from django.contrib.auth.models import User class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) def __str__(self): return f'{self.user.username}'s points' I'm pretty sure the problem is not in admin.py : from django.contrib import admin from .models import Points admin.site.register(Points) I can create the account's model manually but I want it to be automatic. I created this model the same way when I added a profile picture feature which works but I don't understand where the problem is. -
How do I get all entries of a class if it's related set contains an arbitrary item?
class Book(models.Model): ... class Page(models.Model): book = models.ForeignKey(Book) note = models.ForeignKey(Note) class Note(models.Model): name = models.CharField() From the example above, how can I obtain all Books instances that contain an arbitrary Note? my_note = Note.objects.get(name="Arbitrary") pages_with_my_note = Page.objects.filter(note=my_note) books_with_my_note = Book.objects.filter( ??? ) -
how to save ForeignKey object and its parent object at the same time
Angular 8, Django 3. I have two models Recipe and Ingredients. I am using ngModels on the frontend to send data to Django to create a Recipe model. On one page when you click "submit", all the Recipe and Ingredients data is sent to the backend. From what i read about ManyToOne relationships the models.ForeignKey should go on the model that is part of the "many". So there are "many" Ingredients per Recipe, so i have the Foreignkey on Ingredients. My problem is when I send all this data to Django my Ingredients are not being created because there is no ingredients field on the RecipeSerializer. models.py class Recipe(models.Model): name = models.CharField(max_length=30) class Ingredients(models.Model): name = models.CharField(max_length=50) recipe = models.ForeignKey(Recipe, related_name='ingredients', on_delete=models.CASCADE) views.py class AddRecipe(generics.CreateAPIView): serializer_class = RecipeFullSerializer serializers.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredients fields = ['name'] class RecipeFullSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, read_only=True) class Meta: model = Recipe fields = ['name', 'ingredients'] sample data ingredients: Array(1) 0: {name: "23"} length: 1 __proto__: Array(0) name: "23" I am getting an array of Ingredients data on the backend just not sure how to save it all with a Foreignkey to Recipes at the same time. I guess I could create … -
Get local date time and time in Django
How can I get the local date and time in Django? I tried this solution. But it works only for the date now. from django.utils import timezone now = timezone.localtime(timezone.now()) #OK date = timezone.localtime(timezone.date()) #Error time = timezone.localtime(timezone.time()) #Error Preferably in the same format as for datetime now = datetime.datetime.now() #'2020-04-28 17:57:34.120383' date = datetime.datetime.now().date() #'2020-04-28 time = datetime.datetime.now().time() #18:12:08.987472 -
whenever i try to add something in database it show this error
My code is working well because when I run this on Mozilla it is working fine and I can also fill up the database but in chrome, I am not able to add something in the database. is this Django bug or I done some setting wrong or it is the fault of chrome? Exception happened during processing of request from ('127.0.0.1', 14264) Traceback (most recent call last): File "C:\Users\raman\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\raman\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\raman\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\raman\OneDrive\Desktop\Full_stack_practice\django_virtual\venv\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\raman\OneDrive\Desktop\Full_stack_practice\django_virtual\venv\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\raman\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- -
i can't edit in my template by use django form
I have two models child and parent models by which a child model is a foreign key of parent model,i have a template that have child id on it and django-form tag to edit parent records but when i render that template i can't see edit fields on it that will help me to edit my records. Here is child model class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname'] here is my views.py file def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) if request.method=="POST": form=ParentForm(request.POST,instance=child) if form.is_valid(): form.save() return redirect('more_details',pk=pk) else: form=ParentForm(instance=child) context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) and here is my template file <div class="card-body"> <form action="" method="post" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </div> -
HTML image not found (django)
I've been facing this problem, where i get error telling me image not found, and i get cracked picture on the website. I will attach the code including the directory and also the terminal where I get the error. -
How to delete "<QuerySet[]>" from the json response "<QuerySet [data]>"?
I'm sending data in json but the output is like this: { "ids": "<QuerySet [dafa1, lnvq2]>" } and I want it just like this: { "ids": "dafa1, lnvq2" } here's the code I'm using: from upload.models import Images from django.http import JsonResponse def list(request): ids = Images.objects.filter(allowed=True).values_list('id', flat=True) data = { 'ids': str(ids), } return JsonResponse(data) -
Django - User Registration and Profile Settings
So, I managed to create the registration and login for the users. I created two kind of groups, one with restrictions and one with no restrictions. Basically the one with restrictions will managed by me in the admin panel,I will add personally the users in some group instead of another, so no issue here. My issue is that when a new user does the registration in my admin panel it will goes only on my "Users" section and it will not be automatically linked to the Model "user profile" I have created. So I will have to manually add the user into the "Model". How can I make the user automatically be associated with that class in order to make him/her sets up his/her profile picture and so on? accounts/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class FormRegistrazione(UserCreationForm): email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] accounts/models.py from django.db import models from django.contrib.auth.models import User # from django.db.models.signals import post_save # from django.dispatch import receiver class UserProfile(models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) CV = models.FileField(null= True, blank=True) school = models.CharField(max_length=200, null=True) profile_photo = … -
Alter uploaded image before saving with Django admin models
I have a Django model which saves an image. However before I save the model I want to check the width and height and create a md5 hash of the image to check for duplicate uploads. I'm not using any custom forms I'm just trying to upload some images using the admin backend. I'm using Django==3.0.5 and Python 3.8.2 This is my model: from django.db import models from hashlib import md5 from PIL import Image from io import BytesIO class UploadedImage(models.Model): """An image upload Arguments: models {[type]} -- [description] """ name = models.CharField(max_length=255, default='') pub_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='images/') height = models.IntegerField(default=0) width = models.IntegerField(default=0) extension = models.CharField(max_length=20, null=False, default='') hash = models.CharField(max_length=50, null=False, unique=True, db_column='hash', default='') def __str__(self): return self.name @staticmethod def hash_exists(hash): return UploadedImage.objects.exists(hash=hash) def generate_name(self): img_id = UploadedImage.objects.values('id').order_by('-id').first()['id'] + 1 self.name = "%s_%s" % (img_id, self.hash[-4:]) def save(self, *args, **kwargs): # get the actual image??????? # img = self.request.FILES['image'] ???? if img: self.hash = md5(img).hexdigest() try: if hash_exists(self.hash): raise ValueError("image hash already exists, duplicate image!") except ValueError as err: print(err.args) return err img = Image.open(BytesIO(img)) self.width, self.height = img.size self.extension = img.format.lower() self.generate_name() else: print("no image") return "" super(UploadedImage, self).save(*args, **kwargs) However I cannot find anywhere … -
Django 3 returns ModuleNotFound error after renaming the project
I renamed a django project and now I cannot start the WSGI server anymore. It is looking for an old name, but I have changed the name everywhere. Where is the server looking for the old name? The traceback is not helpful. I tried removing all __pycache__ folders. omics_server>python server.py Traceback (most recent call last): File "server.py", line 3, in <module> from omics_server.wsgi import application File "/home/ubuntu/workspace/omics_server/omics_server/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'omics' manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'omics_server.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() omics_server/wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'omics_server.settings') … -
What is the good practice to keep multiple html having the same style and components but different in certain body content
new to web dev here. I am wondering what is the common practice to have multiple pages with the same components (header, sidebar, footer) but only different in the content. I looked around there are suggestion about using php include and other about html import. Say I have a basic.html with <head> fixed stuff </head> <body> <div> sidebar here </div> <!-- Here will be different content other each page --> <footer> fixed stuff </footer> <!-- common scripts here --> </body> Then I will have another 2 pages, say price.html, blog.html. How can price.html recycle basic.html but just with different main contents in the body. I don't know how I can use include here. because the content is in the middle. -
packages aren't install in project's virtual enviroment
i installed django-ckeditor with pip but it goes to the "/home/def-dev/.local/lib/python3.8/site-packages" path when i'm trying to create venv manually. but when i create project with pycharm it goes to the "./venv/lib/python3.8/site-packages" path that this path belong's to internal project's venv . and this make's unknown for pycharm . what should i do to make pycharm find packages from "/home/def-dev/.local/lib/python3.8/site-packages" or when i'm creating venv manually pip save's packages into "./venv/lib/python3.8/site-packages" path. when i create venv manually $ pip3 install django-ckeditor Requirement already satisfied: django-ckeditor in /home/def-dev/.local/lib/python3.8/site- packages (5.9.0) Requirement already satisfied: django-js-asset>=1.2.2 in /home/def- dev/.local/lib/python3.8/site-packages (from django-ckeditor) (1.2.2) when i create venv with pycharm $ pip3 install django-ckeditor Requirement already satisfied: django-ckeditor in ./venv/lib/python3.8/site-packages (5.9.0) Requirement already satisfied: django-js-asset>=1.2.2 in ./venv/lib/python3.8/site-packages (from django-ckeditor) (1.2.2) -
How to create intermediate class in django
I hav this models from django.db import models from embed_video.fields import EmbedVideoField # Create your models here. class Video(models.Model): video_author = models.CharField(default='Bongo Media', max_length=20) video_title = models.CharField(max_length=100) video_file = models.FileField(blank=True) video_image = models.ImageField(default='image.png') video_embed_link = EmbedVideoField(blank=True) video_descriptions = models.TextField(max_length=100, blank=True) video_pubdate = models.DateTimeField(auto_now=True) is_recommended = models.BooleanField(default=False) def __str__(self): return self.video_title class Artist(models.Model): artist_picture = models.ImageField(upload_to='media') artist_name = models.CharField(max_length=100) artist_songs = models.ManyToManyField(Video) def __str__(self): return self.artist_name In database i have a lot of videos and artists. in views.py how can i query so that when i click to the artist name i can see only he is videos, or is there any mistake in my models? Or is the intermediate class needed?, if so, how can i create the intermediate class and how to query data with intermediate class so that i can filter all videos belonging to one artist -
djangocms - cannot import name 'NamespaceAlreadyRegistered'
I have developed a simple project with DjangoCMS(3.7.2) and it works great in the local. I 'm gonna run it on a ubuntu server, which I have another Django project run on it with no issues. Both of my projects are built using python 3.6 & MySQL database. I took these steps to run my new project: Cloned the project on the server via git and updated the settings.py file Created an empty database on the server Installed a virtualenv on server by python3 -m venv venv Activated the venv and upgraded pip Installed requirements successfully using pip install -r requirements.txt Tried to Migrate by python3 manage.py migrate But I got this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked … -
Django models - autocountable field
Welcome! I have a question and i can't find answer. I made model consisting of 3 fields: hours to maintenance, current hours and remaining hours. Is it possible using django admin to have this remaining hours field to be auto countable? ( substracting hours to maintenance and current hours typed by user). This rm field in django admin should be autofilled by substracting hours to maintenance and remaining hours. Regards and thank u for help models.py from django.db import models # Create your models here. class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.IntegerField(help_text = "test", null = True) #current hours ch = models.IntegerField(help_text = "test", null = True) #hours remaining #rm = models.TimeField(auto_now = False) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) -
How to update model field using django signals when updating object in m2m field?
I'm trying to update the order total on updating quantity on OrderItem. For that i'm using django signal m2m change with post_add or post_remove action. Here's my model: class Item(models.Model): name = models.CharField(max_length=20, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) class Order(models.Model): order_item = models.ManyToManyField('OrderItem') total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) m2m changes signal def m2m_changed_order_item_receiver(sender, instance, action, *args, **kwargs): """Receiver for updating total of Order through OrderItem""" if action in ["post_add", "post_remove"]: order_items = instance.order_item.all() total = 0 for order_item in order_items: total += order_item.item.price * order_item.quantity instance.total = total instance.save() m2m_changed.connect(m2m_changed_order_item_receiver, sender=Order.order_item.through) Testcase: def test_updating_order_item_quantity_in_order(self): order_item1, order_item1_data = create_sample_order_item( item=self.item1, quantity=2, data_only=False ) order_item2, order_item2_data = create_sample_order_item( item=self.item2, quantity=2, data_only=False ) order, _ = create_sample_order( order_items=[order_item1_data, order_item2_data], data_only=False ) order_items = order.order_item.all() for order_item in order_items: if order_item == order_item2: order_item2.quantity = 10 order_item2.save() order.save() # update order_item2_total = order_item2.item.price * 10 # works completly fine but i'm searching for alternative method using signal # order.order_item.remove(order_item2) # order.order_item.add(order_item2) order.refresh_from_db() order_item1.refresh_from_db() order_item2.refresh_from_db() # check weather OrderItem total is updated or not self.assertEqual(order_item2.total, order_item2_total) # fails here self.assertEqual(order.total, order_item1.total + order_item2.total) It works completly fine when i first remove … -
How do you save a foreikey in the django of an n: m relationship?
views.py `@login_required def add_arquivo(request, id): if str(request.user) != 'AnonymousUser': if str(request.method) == "POST": form_arq = ArquivoForm(request.POST, request.FILES) if form_arq.is_valid(): form_arq.save() arquivo = Arquivo.objects.create(arq_pro_id = id, arq_usu_id = request.user, arq_desc = form_arq.arq_desc, arq_nome = form_arq.arq_nome, arq_imagem = form_arq.arq_imagem, arq_localizacao_documento = form_arq.arq_localizacao_documento) return redirect('/inicio_projeto/')# rediredionando para lista else: form_arq = ArquivoForm() return render(request, 'arquivos/add_arquivo.html', {'form_arq' : form_arq }) else: return redirect('/')` I don't know how I can save this data arq_pro_id and arq_usu_id together with the others. class Arquivo(models.Model): arq_pro_id = models.ForeignKey(Projetos, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Projetos arq_usu_id = models.ForeignKey(Pessoa, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Usuarios arq_desc = models.TextField('Descrição:') arq_nome = models.CharField('Nome:', max_length=100, null=True) arq_imagem = StdImageField('Imagem:', upload_to='imagem_projeto_arq', null=True) arq_localizacao_documento = models.FileField(upload_to='arquivos_projeto', null=True, max_length=1000) this Arquivos table can have several arquivos linked to a project. class Projetos(models.Model): FINANCIAMENTO_CHOICES = ( ("S", "Sim"), ("N", "Não") ) # pro_titulo = models.CharField('Título do projeto:', max_length=100) pro_imagem = StdImageField('Imagem:', upload_to='imagem_projeto', null=True) # pro_autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) pro_desc = models.TextField('Descrição:') pro_financiamento = models.CharField('Financiamento:', max_length=1, choices=FINANCIAMENTO_CHOICES, blank=False, null=False) pro_financiadora = models.CharField('Instituição financiadora:', max_length=100) pro_datetime = models.DateTimeField('Data de publicação:', blank=True, null=True) pro_inst = models.ForeignKey(Instituicao, on_delete=models.CASCADE, null=True) pro_usuarios = models.ManyToManyField( Pessoa, through='ProjetosDosUsuarios', through_fields=('pdu_projetos', 'pdu_usuarios'), # ) def publicar(self): self.pro_datetime = timezone.now() self.save() … -
Django - Signals are not getting called from User model while creating a new user
I am working on simple hands-on project, and using signals to save the Profile which is part of User model. Seems the signals are not getting called. Though i did not encounter any errors so could not trace what is the issue or what config i am missing. I tried using print statement, and got to know that the signals is not even called. Any pointer how i can check what is causing the issue. Please help... Below is the code i am using. #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'images/default.jpg', upload_to = 'images/profile_pic') def __str__(self): return f'{self.user.username} Profile' #signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print('inside signals') if created: print('inside signals ------------------------> create method is called') Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() # modified the app.py to include the method ready(). from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals