Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get ManyToMany Field values in with selecte_related
I'm new to django. I'm using a ManyToMany field in my Profile model with Membership Model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(blank=True) membership = models.ManyToManyField(MemberShip, null=True) What I want to do is I want to get all the users who has specific membership(from membership model) For example I want the list of all the users who has the Red Membership. I researched and found out that select_related() or prefetch_related can help in some way. but I can't understand how can I use these methods to get what I want. -
Adding markers google maps using sql db in django
How can I add multiple markers to my Google map using data from database? My js code: function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } // Adds a marker to the map and push to the array. function addMarker(position) { marker_f = Markers.objects.all() const marker = new google.maps.Marker({ Markers from models, map, }); markers.push(marker); } My models.py code: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Markers(models.Model): area = models.CharField(max_length=100) latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) Tutorials used for generating this code: https://developers.google.com/maps/documentation/javascript/examples/marker-remove https://developers.google.com/maps/documentation/javascript/examples/marker-simple I don't want to hardcode my coords in js like in the example below, I would like to add them via my admin page in django with models.py variable to show markers on my map in html https://developers.google.com/maps/documentation/javascript/examples/icon-complex -
Plotly - Plot not rendering in Django
I have created 2 functions to generate plots in my projects, essentially the view call these functions to create the plots, however, the problem I have is that one of the plots is not shown, but the code is exactly the same as the other plot (the exception is the column names) views.py @login_required def dashboard(request): c = Profile.objects.get(user=request.user) leads = Leads.objects.filter(agent_id = c) deals = Deal.objects.filter(agent_id=c) #Data for plot qs_leads = Leads.objects.filter( agent_id=c, status='Open') qs_deals = Deal.objects.filter( agent_id=c) df = read_frame(qs_leads) #Creates Plots plot_div_leads = plot_leads_data(qs_leads) plot_div_deals = plot_deals_data(qs_deals) if len(leads) == 0: context = {'leads': len(leads), 'deals': len(deals), } else: if len(deals) == 0: context = {'leads':leads, 'deals': len(deals), 'pot_div_leads':plot_div_leads} else: context = {'leads':leads, 'deals':deals, 'pot_div_leads':plot_div_leads, 'plot_div_deals':plot_div_deals} return render(request, 'account/dashboard.html', context) Dashboard.html {% extends "base.html" %} {% load static %} {% block title %}Dashboard{% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1"> {% block content %} <h1>Dashboard</h1> <p>Welcome to your dashboard.</p> <h1> Add Data </h1> <a href="{% url 'add_company' %}" class="buttons">Add Company</a> <a href="{% url 'add_client' %}" class="buttons">Add Client</a> <a href="{% url 'add_lead' %}" class="buttons">Add Lead</a> <a href="{% url 'add_call' %}" class="buttons">Add Call Report</a> <p></p> <h1>Your Data </h1> <p>Click on the buttons inside the tabbed menu:</p> <div class="tab"> <button class="tablinks" … -
how Convert .ajax() to fetch()
I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation. my code fetch don't work ajax function myidLikeCom(params) { $.ajax({ type: 'POST', url: '{% url "boards:likeComment" %}', data: { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']"; }, error: function (xhr, errmsg, err) { } }); } fetch function myidLikeCom(params) { let data= { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), } fetch('{% url "boards:likeComment" %}', { method: 'POST', body: data, }) } -
form tag not working with django and heroku
When I deployed my website with heroku it works fine but when I go to the contact page it give me error (500) but when I put it to Debug = True its says Exception Type: TemplateDoesNotExist and Exception Value: games\contact_page.html here is my views.py file its seems fine: error = False def contact_page(request): global error try: if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] if '@' and '.com' not in message_email: error = True raise Exception("Enter True email") elif '@' not in message_email or '.com' not in message_email: error = True raise Exception("Enter True email") else: error = False with open(os.path.join("staticfiles/txtfiles/messages.txt"), "a") as file: file.writelines(f'{message_name} :: {message_email} :: {message} :: {time.ctime()}\n\n') messages.success(request, ('Your email is sent! We will reply as soon as possilbe')) return redirect('home') except: messages.success(request, ('Oops there is an error!! Enter the information correctly')) return render(request, 'games\contact_page.html', { 'error': error }) else: return render(request, 'games\contact_page.html', { }) contact_page.html file: <!DOCTYPE html> {% extends 'games/base.html' %} {% block content %} <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-name" class="form-control mb-30" placeholder="Your name"/> </div> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-email" class="form-control … -
Count number of Tests
I wanted to know that is there any way I can have a test for number of tests that got run in my Django manage.py test command? My Project CI runs my test but when I comment out some tests for local testing and forget to undo them before commiting, my CI will not run all my test so more bugs may happen in production -
How to create new model using pk
I am trying to make user join the room ( so creating a new RoomMember) but this is the error that I get : "Cannot assign "room_name": "RoomMember.room" must be a "Room" instance." (thanks in advance) * Views.py: def join_room(request, pk): RoomMember.objects.create(room=pk, user=request.user).save() return redirect('room_detail') Urls.py: path("join/<int:pk>/room/", views.join_room, name="join_room"), Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-dark" href="{% url 'join_room' pk=room.pk %}">Join</a>* -
Products/Items are not being added in the Cart in Django. How do I fix it?
I am new to Django and working on an ecommerce app. I have defined the products and users things. But I am stuck at the cart. I have basically two apps in my project viz. index and cart. I have defined TwoPieceSuits() as a products' model in index.models.py and I have defined Cart() & CartManager() (just to manage cart properly if an anonymous user logs in the web, after adding the products in cart) in cart.models.py. I have defined two_piece_suits, an attribute in cart.models.Cart as a ManyToManyField referenced to index.models.TwoPieceSuit. Now it basically works all the way, until I want to add up the price(s) of TwoPieceSuit() instances and save the result in total of Cart(), it does not add up the prices. Despite of Cart() instance having many (because of ManyToManyField) instances of TwoPieceSuit() containing the values in price attribute, it does not add up the prices when I call them to be added in my cart.models.py. My index.models.py is: import os from django.db import models from django.utils.text import slugify def get_file_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filepath): name, ext = get_file_ext(filepath) filename = instance.fabric + '-' + instance.lining + '-' + … -
Finding outliers with django
So i trying to detect some price outliers in a query, but didn't fully understand. How it cant be done. So how i trying to do this: I got one model class History(models.Model): id = models.CharField(...) price = models.FloatField(...) retailer = models.CharField(...) in view i got query like so price_query = History.objects \ .filter(id__in=product) \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(F('Price')\ .order_by('dt') # so i can access price outliers = np.array(price_query) filtered_price = outliers[(outliers>np.quantile(price_query, 0.1)) & (outliers<np.quantile(price_query, 0.99))] but in this case a can associate any filtered_price with any id in History model, any suggestions how i can do right? Sorry, haven't slept for a long time, nothing comes to my mind -
serving react and django with nginx without having to delete and rebuild docker
I am trying to serve Django and react via Nginx separately. Part of my Nginx folder is: upstream react_frontend { server react:3000; } location /static/ { alias /usr/src/app/react_files/static/; } location / { proxy_pass http://react_frontend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } Part of my docker-compose is react: container_name: frontend build: context: ./frontend dockerfile: Dockerfile args: - API_SERVER=http://127.0.0.1 volumes: - react_static_volume:/usr/src/app/build/static expose: - 3000 env_file: - ./frontend/react_app/.env command: serve -s build -l 3000 depends_on: - web On the frontend the error I get is localhost/:1 GET http://localhost/static/css/main.e7ed58af.chunk.css net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) However when I delete the docker container + volume + images, then those errors go away. Is there a faster way than deleting all the containers and building it again? -
Django: How do I check for duplicates before bulk_create (when defining the object)?
I would like to define an object and check if it is a duplicate before creating it,as shown below. if data['title'] in videos: I'm hoping I can determine it this way. How can I determine duplicates? videos = [] throughs = [] for datas in files: for data in datas: tags = data["tags"].split() tag_pks = list( set([Tag.objects.get_or_create(name=tag)[0].pk for tag in tags]) ) #Around here, we want to make sure that the list called videos already contains data['title']. video = Video( title=data["title"], thumbnail_url=data["thumbnail_url"], preview_url=data["preview_url"], embed_url=data["embed_url"], embed_source=data["embed_source"], duration=data["duration"], published_at=data["published_at"], ) for tag_pk in tag_pks: throughs.append( Video.tags.through(video_id=video.pk, tag_id=tag_pk) ) videos.append(video) Video.objects.bulk_create(videos) Video.tags.through.objects.bulk_create(throughs) -
django redirect to other page and auto login to that page
Is there a way to redirect to other page and automatically log into that page? So it's like I make django webpage with login and create link to facebook. When user clicks to facebook link, it should automatically login to his facebook page. Of course, I will have his facebook username and password on db I used to create the website. Is this possible? Basically, I am trying to create interface page on django with link to several different webpage and make user access to his page by simply logon to this interface page alone. -
Can't access fields on abstracted user model in Django
I have an abstracted user model like so: class MyAccountManager(BaseUserManager): """ Class to adjust the base user manager """ def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.is_active = True user.company = None user.cashpool = None user.save(using=self._db) return user class User(AbstractBaseUser): """ Main User model, inherits from AbstractBaseUser """ # Meta email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) # equals to email date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) # Relations company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) cashpool = models.ForeignKey(Cashpool, on_delete=models.CASCADE, null=True) # Booleans is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # Manager objects = MyAccountManager() # Use Email as login USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def get_full_name(self): return f'{self.username}' Now in a view I can't access the company field for instance: def test(request): company = request.user.company .. # settings.py # Custom User Model AUTH_USER_MODEL = "user.User" … -
Django call related object's function
I have the following models class Customer(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=255) def as_dic(self): return {"id": self.id, "name": self.name } class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() def as_dic(self): return {"id": self.id, "quantity": self.quantity, "customer": self.customer.as_dic() } then orders = Order.objects.select_related('customer').all() orders_list = [obj.as_dict() for obj in orders] the error message says 'Customer' object has no attribute 'as_dic' -
I am trying to use soaplib for python third version and getting some errors
I am migrating code from python2.7 to python3.6 where I am using soaplib and it is compatible with python 3.6 is there any other lib like this? -
How do I fix pagination when there is a GET filter from the URL?
In the main product browse page (www.url.com/works), pagination works well (displays 10 items at a time) and the URL becomes www.url.com/works/?page=2 In the same view, the works can be filtered by category (i.e. www.url.com/works/?collection=Drawing). Since it using the same view, it is still paginating by 10, but if I click other pages, it loses the /?collection=Drawing and just goes back to being www.url.com/works/?page=2. How do I combine them to be something like www.url.com/works/?collection=Drawing&page=2 ? Thank you! views.py class ProductListView(ListView): model = Product template_name = "products/product_all.html" paginate_by = 10 def get_queryset(self, *args, **kwargs): sold = ProductPurchase.objects.filter( refunded=False ).values_list('product_id') qs = super(ProductListView, self).get_queryset(**kwargs) qs = qs.filter(for_sale=True, test_check=False).exclude(id__in=sold).order_by('-timestamp') categoryfilter = self.request.GET.get("collection") if categoryfilter: qs = qs.filter( Q(category__name__icontains=categoryfilter) ) query = self.request.GET.get("q") if query: tags = Tag.objects.filter( slug=query ).values_list('products') qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(material__icontains=query) | Q(id__in=tags) ).order_by("title") return MyFilterSet(data=self.request.GET, queryset=qs).filter() -
how to configure Postgres to work with pytest
I am using django for my backend and pytest to handle my tests. I switched my project db from sqlite3 to postgres, everything works just fine except for the tests, for some reason all of my them are failing. before switching I was able to access my db during my tests with the following line: pytestmark = pytest.mark.django_db but now after using Postgres as my db I get this error on all of my tests UndefinedTable The above exception was the direct cause of the following exception: request = <SubRequest '_django_db_marker' for <Function test_logged_user_saved_recipes_url_reverse>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, reset_sequences = validate_django_db(marker) if reset_sequences: request.getfixturevalue("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: > request.getfixturevalue("db") does anyone knows the right way to access Postgres db while using pytest? or maybe there is a way to switch to sqlite3 db only when testing? thanks in advance -
Use of serializer class in other frameworks
Why isn't there a serializer class just like in DRF Djnago in node, express , laravel or RoR?? Is it just on python we need serialization? In every other framework, are data saved as json in database? I dont think so. Can someone explain this? For eg in DRF we have something like this: class Leadserializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' Here this serializer class serializes all the fields of Lead model while calling a get api. It brings out the complex queryset to json format in api response. Shouldnt the same thing be happening in all other frameworks as well?? -
How to Save a Query Set of Objects in a Single Transaction without using a for loop in Django ORM
Just a quick question, for ex, posts variable has n objects, and i need to save the post id in a post_tag model, how can i achieve without using a for loop, and just with the a single transaction using Django ORM. Here is a small snippet what i want to achieve: posts = Post_Tag.objects.filter(tag_id = subcat).values_list('post_id', flat = True) for post in posts: post_home_feed = Post_Home_Feed.objects.create(post_id = post.post_id, user_id = user_id.id) Any leads much appreciated, Thanks in advance. -
when i try to create a blog post is shows not null constraint failed: blog_blog.id
when i try to create a blog post is shows not null constraint failed: blog_blog.id and i have tried everything possible to fix this and it still not working i dont know if i should add and id field in my models.py let me show my code models.py # some field are commented out because i was trying them to see if it would work class Blog(models.Model): id = models.UUIDField(primary_key=True, editable=False) title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") content = models.TextField(verbose_name="Post Content") # slug = models.SlugField(unique=True) image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", null=True) tags = models.ManyToManyField(Tag, related_name='tags', verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator", null=True) created = models.DateTimeField(auto_now_add=True ,verbose_name="Created", null=True) def get_absolute_url(self): # return reverse('blog:blog-details', args=[self.slug]) return reverse('blog:blog-details', kwargs={'pk': self.pk}) class Meta: verbose_name = "Blog Post" verbose_name_plural = "Blog Posts" def __str__(self): return self.title views.py def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.creator = request.user form.save() messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { "form": form } return render(request, 'blog/AddPost.html', context) urls.py path('', views.blog_list, name="home"), path('post/<int:pk>', views.blog_detail, name="blog-details"), path('post/categories/<slug:category_slug>', … -
Using Django/Postgres to store binary data in a memory efficient manor
Context I have a Django project, and inside of this project, I have a database model with a field of type models.BinaryField(max_length=50000000, default=b'0') Problem When the server is requested to query for this binary data, even though there are never more than 1-2 concurrent requests, I am reaching the ram limits of my server using io.BytesIO, along with stream.seek({index}), and stream.close()(I use the term stream very loosely, as I am simply referring to seeking and closing a stream of bytes here). Question Is it possible that I need to implement the way I am storing this binary data differently? Solutions that I have tried that didn't work Would splitting it up into chunks of smaller sizes be computationally more efficient for the RAM of the server? When I attempted this, I discovered that chunking up the file into smaller chunks and relating them with a many-to-one relationship was extremely taxing as far as overhead on the database. -
How do I get collectstatic to work when running a DjangoApp on Heroku?
I have a Django App that am trying to deploy on Heroku I am sharing my log file and my settings.py and urls.py file as well. This is my log file 2021-11-18T17:47:23.000000+00:00 app[api]: Build started by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.297666+00:00 app[api]: Release v55 created by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.297666+00:00 app[api]: Deploy 6d11bc39 by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.717498+00:00 heroku[web.1]: Restarting 2021-11-18T17:47:49.753132+00:00 heroku[web.1]: State changed from up to starting 2021-11-18T17:47:50.533623+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2021-11-18T17:47:50.719741+00:00 app[web.1]: [2021-11-18 23:17:50 +0530] [9] [INFO] Worker exiting (pid: 9) 2021-11-18T17:47:50.719816+00:00 app[web.1]: [2021-11-18 23:17:50 +0530] [10] [INFO] Worker exiting (pid: 10) 2021-11-18T17:47:50.719923+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [INFO] Handling signal: term 2021-11-18T17:47:50.723833+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-11-18T17:47:50.820321+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [INFO] Shutting down: Master 2021-11-18T17:47:50.953355+00:00 heroku[web.1]: Process exited with status 0 2021-11-18T17:47:54.323110+00:00 heroku[web.1]: Starting process with command gunicorn resume_app.wsgi 2021-11-18T17:47:55.884509+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-11-18T17:47:55.884907+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:5402 (4) 2021-11-18T17:47:55.884969+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Using worker: sync 2021-11-18T17:47:55.887917+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [9] [INFO] Booting worker with pid: 9 2021-11-18T17:47:55.895825+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [10] [INFO] Booting worker with pid: 10 … -
I don't understand how to use the django-dynamic-formset plugin
I am using the Django Dynamic Formset However, I have not found a documentation for noobs who are just starting out, I feel that they already take many things for granted and do not go step by step. I have several doubts: In point 5 of the page, it mentions that I must write jquery.formset.js in my MEDIA_ROOT and I must include the jQuery library if my MEDIA_ROOT, but how will I do that if mine is like this MEDIA_ROOT = os.path.join (BASE_DIR, ' photos') in point 4 of the plugin documentation it says this prefix: '{{formset.prefix}}' which means prefix here -
How to delete model by filtering with pk
I am trying to delete an entire model using pk, but when I click on "delete" I am redirected to the given page but nothing happens model is still there and not being deleted, but when I write the 'room_name' instead of 'pk' it does work, (thanks in advance) *Views.py: def delete_room(request, pk): Room.objects.filter(name=pk).delete() return redirect('home') Urls.py: path("delete/<int:pk>/", views.delete_room, name="delete_room") Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-danger" href="{% url 'delete_room' pk=room.pk %}">Delete Room</a>* -
Wrong decimal round to first 2 digits of amounts in python 3.7 and Django
Let there be 3 Django fields: INPUT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RESULT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RATE = models.DecimalField(max_digits=12, decimal_places=5, default=1) RATE is always Decimal('1.00000'). I want to have RESULT = INPUT * RATE and since the source is either from database, either from APIs, I use: RESULT = Decimal(INPUT) * Decimal(RATE) I do not know why, but in some cases (≈ 2%) I end with the numbers you see in the following table. There is a round to the first 2 digits. Do you know what could cause that? I do not see anything in the code that could do that and I am clueless. Both columns should be equal. RESULT INPUT 610.000 609.000 3700.000 3743.520 1200.000 1159.000 570.000 573.300 61.000 61.470 1300.000 1321.550 44.000 43.730 130.000 125.770 18.000 18.500 100.000 99.590 41.000 40.650 95.000 94.880 19.000 18.710 36.000 35.640 120.000 118.800 12.000 12.290 11.000 11.260 1.000 1.030 160.000 155.970 190.000 186.850 51.000 50.770 130.000 128.150 12.000 12.290 11.000 11.260 25.000 24.940 24.000 23.640