Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to subtract available_quantity to user_give_quantity
A manager stock 500 products in his stock. But when he give 400 product a SR then it will be subtract and available quantity is 100. But when manager give same product 50pics to another SR then it will be subtract from 100 to 50 and manager can see his stock has 50 products. But i cannot solve this problem. My code is : class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) distribute_price = models.IntegerField() mrp_price = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) user_give_quantity = models.IntegerField(null=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.product.item_name def available_quantity(self): return self.product.quantity - self.user_give_quantity if all([self.product, self.product.quantity, self.user, self.user_give_quantity]) else 0 def stock_quantity(self): return self.available_quantity() - self.user.user_give_quantity if all([self.user, self.user.user_give_quantity]) else 0 def amount(self): return self.mrp_price * self.user_give_quantity -
I'm getting 'module' object is not callable in Django Rest Framework
I'm trying to learn django rest framework for an api. I'm following the documentation and checked all the imports but I'm getting the typeerror: 'module' object is not callable Views.py from rest_framework import viewsets from .serializer import CategorySerializer from .models import CategoryModel class FirstView(viewsets.ModelViewSet): queryset = CategoryModel.objects.all().order_by('name') serializer_class = CategorySerializer serializers.py from rest_framework import serializers from .models import CategoryModel class CategorySerializer(serializers.ModelSerializer): class Meta: model = CategoryModel field = ['name', 'description'] urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'', views.FirstView) urlpatterns = [ path('', include(router.urls)) ] -
Aligning toast messages in javascript
I'm working on a Toast message setup where, if multiple messages are active, they're not visible except for the one in the front (so maybe a margin of 15px between them would help) and display them on the bottom-corner of the screen (fixed), which doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with JavaScript? //dont't know how to get this working let margin = 10; function myFunction() { var type = document.getElementById("toast-" + type); type = "success", "info", "warning", "error"; setTimeout(function(){ margin += toast.clientHeight + 5; }, 3000); } .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-blue{ bottom: 0; position: absolute; background-color: #0000ff; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-orange{ bottom: 0; position: absolute; background-color: #ffbf00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-red{ bottom: 0; left: 0; position: absolute; background-color: #ff0000; border-radius: 4px; box-shadow: 4px 4px 16px 0 … -
Django Blog Post ordering? how to arrange by column
Django blog order is in a row, how to put the order in a column? -
How do can I creating and use a custom fields in Django
I am new to django and building a kinda of a package (Shipments) based app in Django and I have these models, class ShippingLocation(models.Model): latitude = models.IntegerField() longitude = models.IntegerField() class Shipping (models.Model): email = models.EmailField() location = models.ForeignKey(ShippingLocation , default=None, on_delete=models.CASCADE ) class Package(models.Model): name = models.CharField(max_length=30) supplier = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) to = models.ForeignKey(Shipping, default=None, on_delete=models.CASCADE ) this work okay for now but I wonder if can be able to remove the ShippingLocation model and use a custom field instead of at the location field in the Shipping model? If yes how do I create custom fields and how do I implement them? -
Django probelm with actions
Hi I am new to django and I have written a code to go from one html code to another when a button is clicked.but nothing happens when I click the button. can someone help? Below I have added my whole code and any hint is appreciated. here is urls.py from django.conf.urls import url from generator import views urlpatterns = [ url(r'', views.home), url(r'^password/', views.password, name='password'), ] here is views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, 'generator/home.html') def password(request): return render(request, 'generator/password.html') here is home.html <h1>Password Generator</h1> <form action="{% url 'password' %}"> <select name="length"> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <input type="submit" value="Generate Password"> </form> password.html is PASSWORD lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll -
Django-Channels - How to block more than one connection from same client (browser)
I am making a chat app in Django-Channels. When an authenticated (means non-AnonymousUser)user opens the same URL in two different tabs,two websocket connections are made for the same user. How to block the second connection made? Is there a way in Channels to know if a user is already connected to the server or not? -
Can I make django templates work the same way they would on react js components?
Currenlty i am working on a project where i want to reuse a piece of html - Which i understand i can do with {% include tags %} However, in the same html or component, I am also loading different data for different users, where {{ user }} is the user i am passing from the main template. For instance: competition_user_chart.html (Did not put the whole code for simplicity) window.onload = function() { let user = "{{ user|remove_everything_after_hashtag }}" console.log("damage-chart-" + user) initChart("damage-chart-" + user); initChart("kda-chart-" + user); initChart("placement-chart-" + user); createChart(chartId = "#damage-chart-" + user, label = "Damage per minute", color = "#3e25cd", title = "Damage over last games", xAxisLabel = "Matches", yAxisLabel = "Damage"); createChart(chartId = "#kda-chart-" + user, label = "KDA", color = "#f542ef", title = "Damage over last games", xAxisLabel = "Matches", yAxisLabel = "KD"); createChart(chartId = "#placement-chart-" + user, label = "Placement", color = "#f542ef", title = "Placements over last games", xAxisLabel = "Matches", yAxisLabel = "Placements"); }; In the main template i have the following (competition_scores.html): {% if team.player_1 != None %} <li>{{ team.player_1 }}</li> {% include 'competitions/competition_user_chart.html' with team_name=team user=team.player_1 %} {% endif %} {% if team.player_2 != None %} <li>{{ team.player_2 }}</li> … -
'NoneType' object has no attribute 'attname'
djongo model view'NoneType' object has no attribute 'attname' python: 3.8.0, Django: 3.0.5, Djongo: 1.3.3 class MetaData(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) meta_description = models.TextField(max_length=155, default=None, blank=True) class Meta: abstract = True class Article_Categories(models.Model): slug = models.SlugField(max_length=255, unique=True, blank=True) meta_data= models.EmbeddedField( model_container=MetaData ) objects = models.DjongoManager() def __str__(self): return self.slug class Meta: db_table= 'article_categories' -
Django wrap SQL as Command
i have a question, is it possible to wrap a SQL command on Django Command ? because i have this SQL, that need to be executed during deploy update car join car_manager manager_before on car.manager_id = manager_before.id and manager_before.shortname is null join car_manager manager_after on manager_after.name = manager_before.name and manager_after.shortname is not null set car.manager_id = manager_after.id -
How to get the values from a Wagtail CMS Stream field panel using Django Models?
I'm building a webpage using wagtail CMS, Django, Postgresql and at the bottom of the page, I'm building a section where I would display the videos using pagination. I'm trying to retrieve the data from Django Models using all_posts = MultiBlogPage.objects.values("all_blogs_content_pages") and I'm getting the output as <PageQuerySet [{'all_blogs_content_pages': [<wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ee2d21d0>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ed8fa2e8>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35f617e6a0>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ed90aac8>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ed90af60>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ed90a978>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ed90ae48>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ee2b9320>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ee2b9630>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ee339f28>, <wagtail.core.blocks.stream_block.StreamValue.StreamChild object at 0x7f35ee339470>]}]> Could someone please look at my code below and let me know how to get the exact values from Django Models ? def get_context(self, request, *args, **kwargs): context = super(MultiBlogPage, self).get_context(request, *args, **kwargs) context['multiblog_page'] = self // The name of the stream field panel is "all_blogs_content_pages" all_posts = MultiBlogPage.objects.values("all_blogs_content_pages") print("all_posts...",all_posts) paginator = Paginator(all_posts, 3) print("paginator", paginator) page = request.GET.get("page") try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context["posts"] = posts return context -
Django - Model Draft, Published, Revisions
I have a model that I use for creating project budgets. They approve one budget, but later on as they execute hours the budget might need to be revised and a user has to create a draft budget based on the one approved and make changes and submit to the manager for approval. I'm using Django and I'm not sure what I need to use for this. I've looked at django-reversion-API, django easy-mode and wagtail. But I'm very confused. I don't know what I need. Reversion, CMS, something related to state????? Any help would be appreciated. -
Push rejected, failed to compile Node.js app while deploying in heroku
i am deploying my django+react app on heroku but its raising this error every time Push rejected, failed to compile Node.js app i have tried every thing remove cache delete package-lock.json update the node version according to .env file and other packages , app working fine in local but not deploying on server.i have this error so far at every time please help me to resolve i have also follow the heroku documentation to resolve this issue but not worked for me. -
How to combined C++ code implement in Django?
My project is based on Face Recognition, Hence C++ code implements in my project. -
Make that django simple JWT have the same permissions as Django Admin
I'm developing an api in Django with DjangoRestFramework, and now I started to work with Tokens, (I'm using JWT with the djangorestframework_simplejwt library). What I want is to have the same permissions that I have in my django Admin in the token, for intance, I created a group for an specific app in my Django admin but when I use httpie with an user that wasn't supose to have permissions I can get all the data. Do you know a way to connect that permissions? This is the code that I wrote. from rest_framework.permissions import IsAuthenticated class ArticulosLista(APIView): permission_classes = (IsAuthenticated, ) # All other methods -
How to have one model property be a dropdown between attributes of another model?
Relatively new to Django. I think what I am trying to do is very simple but I've never done this before. "irrelevant2" is an attribute in my class first that I want to refer to a direct element in the class second (this part is working fine). Additionally, I want there to be a field in my class first that is essentially a dropdown menu that chooses between two elements of the class second and can only pick one. I understand that I need a form but so far have not been successful. My hunch says RELEVANT_VARIABLE should be a ForeignKey but I'm not sure how to attach it to a dropdown of either attr1 or attr2 from class second. class second(models.Model): attr1 = models.CharField(max_length=100) attr2 = models.CharField(max_length=100) class first(models.Model): irrelevant1 = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) irrelevant2 = models.ForeignKey(second, on_delete=models.CASCADE) RELEVANT_VARIABLE = models.ManyToManyField(second, related_name="team_selection") And then in forms.py class FirstForm(forms.Form): def __init__(self, *args, **kwargs): super(FirstForm, self).__init__(*args, **kwargs) self.fields[**not sure what to even put here**] = forms.ChoiceField( choices=[(o[**not sure**], str(o[**not sure**])) for o in Second.objects.filter(irrelevant2=self)] ) class Meta: model = second -
Django multiple forms in CreateView
I'm trying to show a view with two forms on it. The RoadCost form which will calculate the road's cost & pass it into the Road model so that when a Road is created it has the RoadCost associated with it. How can I show these two forms on the same CreateView & the pass it into the Road model? In theory, all the RoadCost should do is be next to the create view & allow the user to input the spent & allocated values it will do some calculations & then pass in the spent & allocated to the Road form ready for it to be created. I'm fairly inexperienced with Django, if there is a way to do this please let me know. model.py class RoadCost(models.Model): cost_spent = models.CharField(max_length=100) cost_allocated = models.CharField(max_length=100) class Road(models.Model): name = models.CharField(max_length=100) road_cost = models.OneToOneField( RoadCost, default=False, on_delete=models.CASCADE, primary_key=True, ) views.py class RoadCreateview(CreateView): model = Road fields = ['name', 'distance'] forms.py class RoadCostForm(forms.ModelForm): class Meta: model = RoadCost fields = ['spent', 'allocated'] -
How can I send context to Django in every page without sending from all the views
I am trying to create an eCommerce app and have the cart option in that. However, on every page of the site (or every view), I always type the code... context = { "no_in_cart":no_of_items_in_cart(request) } Where no_of_items_in_cart is a function to find the number of items in the cart. But I feel this is a waste of code and may have several inefficiencies. And also I am not sure on how I can send this code through auth_views, such as login or register views. Any help would be greatly appreciated. Thanks! -
Django Pass a Form's Field to a Model's Field
I am learning Django web framework by going through this example. In one of the view functions: def renew_book_librarian(request, pk): """View function for renewing a specific BookInstance by librarian.""" book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_instance.due_back = form.cleaned_data['renewal_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal_date': proposed_renewal_date}) context = { 'form': form, 'book_instance': book_instance, } return render(request, 'catalog/book_renew_librarian.html', context) It assigns form.cleaned_data['renewal_date'] to book_instance.due_back. However, form.cleaned_data['renewal_date'] is not a models.DateField as defined by the BookInstance class: class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.RESTRICT) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) … -
Having trouble rendering an array of images from an api (Django Rest Framework) response in React
Hi this is my first project in both React and Django Rest Framework and I need to figure this out to complete the project. The issue I'm having (I believe it's a React one) is that my api is returning an json response which React receives using axios which works fine since when I do the console log all the data is there and Im also able to pass the data to a tag, etc. I would like to display the photos that are being sent to by the api. The link is not the problem as I am able to view the photo in the browser using the link provided by the api. The problem is that I have multiple images in the api response that are set up as an array. As shown here: postmanResponse Response using console: enter image description here I guess essentially what I'm asking is there a way that I can make an array/object with the image array that my api is delivering so that I can then use it to show the picture in React? Any help will be helpful. Thank you! Here is my code for the React side: // Import Files … -
Django: TypeError: 'ModelSignal' object is not callable
I have a piece of code throwing an error: TypeError: 'ModelSignal' object is not callable. While I'm gonna add signals in my project, this error is occuring. Why this type of error is occured? What you need to know to give my answer? Please help me someone. I'm a newbie to Django. Thanks in advance. Here is my views.py file: def registerPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user =form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account successfully created for ' + name) return redirect ('login') context = {'form': form} return render(request, 'accounts/register.html', context) My models.py file: from django.db import models from django.contrib.auth.models import User class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) My signals.py file: from django.db.models.signals import post_save from django.contrib.auth.models import Group, User from .models import Student def student_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name = 'Student') instance.groups.add(group) Student.objects.create( user = instance, name = instance.username ) post_save(student_profile, sender= User) My apps.py file: from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): import accounts.signals … -
Setting up Django, Nuxt, with Nginx and docker
I am trying to create a docker image for all of the above services. I was able to get django set-up with a database and Nginx, but I am having a lot of trouble adding Nuxt to the mix and cannot get the Nuxt app to run properly and it is giving me constant errors that do not occur if I manually start the node server. I suspect that most of the issues are from auth and/or improper routing in Nginx, likely stemming from incorrectly setting up the appropriate files. Any advise on how to set-up these configuration files would be greatly appreciated! My folder structure is as follows. The dockerfile inside the app directory corresponds to the django app WebsiteProject/ ├── app/ │ ├── frontend-nuxt/ | | ├──Dockerfile | | └──nuxt.config.js │ ├── nginx/ | | ├──Dockerfile | | └──nginx_local.conf | └──Dockerfile └── docker-compose.yml docker-compose.yml version: '3.7' services: web: build: ./app command: gunicorn webapp.wsgi:application --bind 0.0.0.0:1339 --reload entrypoint: ./entrypoint.sh volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 1339 env_file: - ./.env.dev depends_on: - db # - redis frontend: build: ./app/frontend-nuxt volumes: - ./app/frontend-nuxt/:/user/src/app/ expose: - 3000 ports: - 3000:3000 depends_on: - web command: npm run dev db: image: … -
How To Use django.views.APIView In Python?
I'm currently facing trouble using rest_framework.views.APIView. When I try running python manage.py makemigrations, it says that there is nthroughing such as django.utils.six. The line that it throws an error on is from rest_framework.views import APIView. Can anyone give me guidance on how to fix this issue? -
How to add hide button next to delete button in django admin
How can I add a custom action button(Hide) to the position where Delete button originally at (Blue circle). -
How to stop Django 3.0 leaking db connections?
In my requirements.txt I only change from django==2.2.17 to django==3.0 (or 3.1.4) and the webserver starts leaking postgres db connections. (Every request increases the number of connections when I check the list of clients in pgbouncer.) How can I stop the leakage? Is there any way to limit the number of connections to a server?