Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to update a related model when create an other model
I have 2 models: Transaction and Wallet, a wallet has multiple transactions. I need to update the amount field in Wallet model whenever a new transaction is created. The way I see is overwrite save method in the model. Currently, I wrote like this def save(self, *args, **kwargs): if self.kind == "Income": self.wallet.amount += self.amount elif self.kind == "Outcome": self.wallet.amount -= self.amount self.wallet.save() super(Transaction, self).save(*args, **kwargs) It creates a new transaction correctly but not update the wallet model. How I can fix that? -
How do I tell gunicorn to use a proxy server when making outbound calls?
I have a Django web application being served up by gunicorn, running in a Docker container. My Django app needs to access an AWS and it's failing. I believe this is because it is all running behind a corporate firewall and I need to somehow tell gunicorn to use our proxy server. How do I do that? The documentation isn't clear (to me). Thanks. -
Django importing models between multiple db & multiple project
My setup include django 3.0 , my directory structure is: /webapp/ api_1/app1/models.py api_2/app1/models.py The api_1 used multiple db which are configured by db routing. i want to import the api_2.app1.ModelA in my api_1.views. i have tried to add the sys.path.append('/webapp/api_2') in api_2.wsgi, add the api_2.app1 in the INSTALLED_APPS of api_1 but still getting error of cannot found Module api_2. i have also tried reverse of it but cannot import that also. -
Django Main Category
I am very beginner in django..I am trying to upload product by 2 main categories For him(man) and For her(woman)...but its not working properly...i have used to method in template to get categories...when i click on the for him it will redirect me to products which i added in for him(man)..but in template the url tag {%url '' %} is not proper i think..when i used url tag it shows me attribute error...And if used get_absolute_url in template the whole link was hide..plz anyone can help me to solve this problem. from django.db import models from django.shortcuts import reverse from django.utils import timezone Create your models here. class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('shops:shop_by_category', args=[self.slug]) class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategorymans', on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = models.SlugField() def __str__(self): return self.name class Product(models.Model): category=models.ForeignKey(Category, related_name='productsman', on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, related_name='productsman2', on_delete=models.CASCADE, default=True) name = models.CharField(max_length=100) description = models.TextField(max_length=1000) price = models.DecimalField(decimal_places=2, max_digits=10) brand= models.CharField(max_length=100) image = models.ImageField(upload_to='product', blank=True, null=True) available = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name This is my model.py from django.shortcuts import render, get_object_or_404 from .models import Product,Category Create your views here. def Shop(request): product_shop = … -
How to get a list of CharField for one model field that it is possible to increase with a "+" button to add other fields in Django admin?
Here is some fields I have on the admin page of the User model I extended: But the fact is I don't want textAreaFields for soins and historique fields, I would prefer it look like a list in which it would be possible to add other fields: But I don't know how to do that, I checked the inlines models which very looks like the result I wish for but I did not manage to integrate it into my model. I also checked the ArrayField (I have a postgre DB) but I don't find an easy way to add fields from the admin page like the second picture. Here is my model.py : class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) story = models.TextField(blank=True) forename = models.CharField(max_length=254, null=True, blank=True) historique = models.TextField(blank=True) adress1 = models.CharField(max_length=254, null=True, blank=True) adress2 = models.CharField(max_length=254, null=True, blank=True) dateNaiss = models.DateField(null=True, blank=True) fidelity = models.IntegerField(null=True, blank=True, editable=True) phone = models.CharField(max_length=16, null=True, blank=True) soins = models.TextField(blank=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name', 'forename', 'adress1', 'adress2', 'dateNaiss', 'phone'] objects = UserManager() def get_absolute_url(self): return "/users/%i/" … -
form post getting 403 forbidden error while using django
<form action="{% url 'create'%}" method="POST" > {% csrf_token %} this in my template file. def create(request): return render(request, "auctions/create.html") if request.method == "POST": title = request.GET["title"] des = request.GET["description"] bid = request.GET["startingBid"] imageurl= request.GET[ "imageUrl"] category = request.GET["category"] image = request.GET["image"] listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category) return render(request, "auctions/index.html",{ "listing":Auctionlisting.objects.all() }) and this is in my views.py. still after using csrf token i am getting 403 forbidden error. please some guide me. Also these title, description and all are my inputs... -
Where can I keep settings data for a reusable app
Django=3.1 I'd like to push some utilites of mine, template tags, filters etc. to a reusable app. But this app will needs a huge amount of settings. Maybe 100-200 lines. I'm thinking of placing a file called something "my_omnibus.py" next to project's settings.py Is a good idea? If it is, could you tell me how to import that file into the reusable app if the name of the project may change. If it is not, where can I keep the constants? -
How do I create two sign-up systems?
So I wanted to create 2 signup options on the website. For example a student and teacher login methods. I want the form or model to extend and save it to the sqlite3 db. For example, if a student signs up the database would store a field isteacher = False and vise versa. Also once they login is there a way to display two different dashboards based on the user? Is there any guide or link to show me how to build this step by step? I have spent close to 8 hours figuring this out and i'm very close to giving up. Thanks for your time. -
Django annotate() and count() conditional from 0 to null
I am new to django and django-rest-framework and I am wondering if it is possible to put conditional if else on annotate(total_sessions=Count()) where if Count() = 0 then total_sessions="null"? I have a project where I need to make that if the total sessions is equal to 0 the output must be null. I though of using SerializerMethodField() on total_sessions to get the count but this cause multiple SQL queries causing slow API response that is why it is out of the question. Sample code below for serializers.py and views.py(this is only a sample code as my real codes have multiple querysets). serializers.py class ClassStatisticsSerializer(ModelBaseSerializer): total_sessions = serializers.IntegerField() class Meta: model = Class fields = ( 'id', 'batch', 'type, 'total_sessions' ) views.py from django.db.models import Count, Q class ClassStatisticsList(APIView): condition = {} if date: condition = {'classactivity__date':date} queryset = Class.objects.all().annotate( total_sessions=Count( 'classactivity', filter=Q(**condition), distinct=True ) ) -
Cannot add Data to django models
emphasized textenter image description here cannot accces the data of form using javascript and cannot save to django models -
django locale-url import error cannot import name 'urlresolvers' from 'django.core'
i am working through docs and i am getting errors. from django.core import urlresolvers ImportError: cannot import name 'urlresolvers' from 'django.core' (/home/yubbaraj/python/nbrl-project/nbrlenv/lib/python3.8/site-packages/django/core/__init__.py) can anyone help me in this . -
how to access models from another project in django?
hello guys so i have this 2 project in my root file one project is the admin website where it display the message that it got from the callback server and the other one is my callback server of my bot message that collect the message to the models and i want to access this models inside the callback server from the admin website which is the other project but i am confused how to do it? i try using the pythonpath but it never shown the new file path that i add to the pythonpath. can anyone give me a tips or suggestion how can i solve this problem? or doing this is not a best practice? thanks and here is my django structure hopefully you guys can understand what is my problem and sorry my English is not that good :) thanks mate!. /root /project1<-- my main website that display the message from callback server /dashboard<-- apps admin.py models.py urls.py views.py manage.py /project2<-- callback server for bot message /bot<-- apps admin.py models.py urls.py views.py manage.py -
my ecommerce site if I change the quantity upwards with an anonymous account it erases all except 1
my ecommerce site if I change the quantity upwards with an anonymous account it erases all except 1 hello as I said with an account it works but if we make anonymous it erases all the products I chose except the product that I wanted increased the quantity but it decreases the quantity to 1 views.py def updateItem(request): data=json.loads(request.body) productId=data['productId'] action=data['action'] print('Action',action,'product:',productId) customer=request.user.profile product=Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order,product=product) if action=='add': orderItem.quantity=(orderItem.quantity + 1) elif action=='remove': orderItem.quantity=(orderItem.quantity - 1) orderItem.save() if orderItem.quantity<=0: orderItem.delete() return JsonResponse('Item was added',safe=False) utils.py from .models import * import json def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart={} print('cart:',cart) items=[] order={'get_cart_total':0,'get_cart_items':0,'shipping':False} cartItems=order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product=Product.objects.get(id=i) total=(product.price*cart[i]['quantity']) order['get_cart_total']+=total order['get_cart_items']+=cart[i]['quantity'] item={ 'product':{ 'id':product.id, 'name':product.name, 'price':product.price, 'imageURL':product.imageURL }, 'quantity':cart[i]['quantity'], 'get_total':total, } items.append(item) if product.digital==False: order["shipping"]=True except: pass return {'cartItems':cartItems,'order':order,'items':items} def cartData(request): if request.user.is_authenticated: customer=request.user.profile order, created = Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() cartItems=order.get_cart_items else: cookieData=cookieCart(request) cartItems=cookieData['cartItems'] order=cookieData['order'] items=cookieData['items'] return {'cartItems':cartItems,'order':order,'items':items} def guestOrder(request,data): print('user in not logged in') print('COOKIES:',request.COOKIES) name=data['form']['name'] email=data['form']['email'] address=data['form']['address'] cookieData=cookieCart(request) items=cookieData['items'] .. for item in items: product=Product.objects.get(id=item['product']['id']) orderItem=OrderItem.objects.create( product=product, order=order, quantity=item['quantity'] ) return customer,order base.html <script type="text/javascript"> var user='{{request.user}}' function getCookie(name) { let cookieValue = null; if (document.cookie && … -
Linux Ubuntu 18.04 - Error loading MySQLdb module. Did you install mysqlclient?
I'm getting the following error message while running my Django REST project with MySQL database in pipenv. raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? This seems like a very common problem (please don't mark as duplication), but after trying all the possible solutions I'm still getting the same issue.. A few things I tried: pip3 install mysqlclient pip3 install python3.6-dev pip3 install mysql-client pip3 install libsqlclient-dev pip3 install libssl-dev What could still be the problem? It's a Linux Ubuntu 18.04 server with Plesk. Python version 3.8. -
JavaScript Null does not convert to None
@parser_classes([MultiPartParser, FormParser]) @api_view(['POST', ]) def product_list(request): print(request.POST.get('key')) print(request.data.get('key')) print(request.FILES) When I am sending form data with value of key=null it displays null as string but didn't convert to None what should I do. The work around that I have to do is something like if request.data.get('key', None) in ['null', None]: #then do something But this doesn't seem to be a clean way of doing this. So what should I do? I expected that django or django rest framework will automatically convert null to None. -
How to fix TemplatesDoesNotExist error even after BASE_DIR has been Joined with templates in settings.py
Image 1- Error I notice Exception Value: registration/login.html , I don't even have that in the templates, instead, i have sign-in.html, I have no idea why it mentioned login.html. Please see my templates folder below as image 3-Templates. I'm trying to fix the above error. My project path looks like Image 2- project path Image 3- Templates The image 2 above shows that my templates folder is located in foodtaskerapp folder In the settings.py I have added 'DIRS': [os.path.join(BASE_DIR, 'templates')], in the TEMPLATES section. I think there is an error because before we can get to templates from BASE_DIR we need to pass through the foodtaskerapp. This leads me to the following step In the settings.py I tried 'DIRS': [os.path.join(BASE_DIR, 'foodtaskerapp','templates')], to replace step 2 After the above step, I also tried 'DIRS': [os.path.join(BASE_DIR, 'foodtaskerapp\\templates')], . I had use two slashes here because when i used the print command from the interactive console i saw the path was given in that format. I have also tried move my templates folder from the foodtaskerapp to the root folder and I checked like below to confirm if I'm in the right path: from django.conf import settings print(settings.TEMPLATES) Then I got 'DIRS': ['C:\\Users\\simple_tech\\Desktop\\foodtasker-master\\foodtasker-master\\templates'] … -
How to make one dropdown close when clicking another dropdown
I have 2 href links in one page and on click the href opens. But when I click the other href (without closing the first one) the first one stays open. How can I solve this? At first I tried to only open and close the dropdown with CSS, but that got really messy because of the two buttons. Now I can open both buttons and close them when I click oudside of the button-area or on the button itself again. But it doesn't close when clicking the other button. I imagine this isn't a hard thing to solve but I just can't seem to figure it out. Thanks a lot! dashboard_home.html % extends 'dashboard.html' %} {% block content %} {% block static %} {% load static %} <link rel="stylesheet" href="{% static 'dashboard_home.css' %}"> {% endblock static %} <div class="welcome-message"> <p>Hello, {{ request.user.first_name }} </p> <img src="{% static 'Logo/Logo_DarkGreen.png' %}" class=header-logo> </div> <div class="buttons"> <a href='#' onclick="myFunction()" class='basic-button'><h2>happy</h2><br><h3>head</h3></a> <div class="dropdown-modules" id="dropdown-modules"> <a href="#">Module 1</a> <a href="#">Module 2</a> <a href="#">Module 3</a> <a href="#">Module 4</a> <a href="#">Module 5</a> </div> <a href='#' onclick="myFunction1()" class='basic-button'><h4>healthy</h4><br><h3>heart</h3></a> <div class="dropdown-modules" id="dropdown-modules1"> <a href="#">Module 6</a> <a href="#">Module 7</a> <a href="#">Module 8</a> <a href="#">Module 9</a> <a href="#">Module 10</a> </div> … -
TaggableManager with blank=True raise IntegrityError when creating object in admin panel
I have a model and an admin defined: models.py from adminsortable.models import Sortable class Category(Sortable): site = models.ForeignKey('sites.Site', related_name='+', on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=255) slug = models.SlugField(_('Slug'), max_length=255, unique=True) icon = ImageField(_('Icon'), upload_to='myapp/icons') icon2 = ImageField(_('Icon 2'), upload_to='myapp/icons') recommended_tags = TaggableManager(related_name='category', blank=True) admin.py from adminsortable.admin import SortableAdmin class CategoryAdmin(SortableAdmin): list_display = ['name', 'site'] list_filter = ['site',] admin.site.register(Category, CategoryAdmin) Looks like everything is fine but I get an IntegrityError when I try to create an object from admin panel. What's interesting, the object update is working fine. The problem is just when I try to create a new Category object. django.db.utils.IntegrityError: null value in column "recommended_tags" violates not-null constraint DETAIL: Failing row contains (64, ggggggggg, ggggggggg, myapp/icons/16.jpg, 31, myapp/icons/46.jpg, 1, null). It is probably caused at admin save_model() method but I am not sure. django 1.11 django-taggit 0.22.2 postgres database -
ImportError raised when trying to load 'menus.templatetags.menus_tags': cannot import name 'Menus' from 'menus.models'
I am just leaning wagtail and am a bit confused now. I Have a folder structure: site > menus > templatetags > menus_tags.py Here is the code: from django import template from ..models import Menu register = template.Library() @register.simple_tag() def get_menu(slug): return Menu.objects.get(slug=slug) Then in my models ( site > menus > models.py ): """Menus models""" from django.db import models from django_extensions.db.fields import AutoSlugField from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.admin.edit_handlers import ( MultiFieldPanel, InlinePanel, FieldPanel, PageChooserPanel ) from wagtail.core.models import Orderable from wagtail.snippets.models import register_snippet class MenuItem(Orderable): link_title = models.CharField( blank=True, null=True, max_length=50 ) link_url = models.CharField( max_length=500, blank=True ) link_page = models.ForeignKey( "wagtailcore.Page", null=True, blank=True, related_name="+", on_delete=models.CASCADE, ) open_in_new_tab = models.BooleanField(default=False, blank=True) page = ParentalKey("Menu", related_name="menu_items") panels = [ FieldPanel("link_title"), FieldPanel("link_url"), PageChooserPanel("link_page"), FieldPanel("open_in_new_tab") ] # @todo add properties # link @register_snippet class Menu(ClusterableModel): """The main menu clusterable model.""" title = models.CharField(max_length=100) slug = AutoSlugField(populate_from="title", editable=True) panels = [ MultiFieldPanel([ FieldPanel("title"), FieldPanel("slug"), ], heading="Menu"), InlinePanel("menu_items", label="Menu Item") ] def __str__(self): return self.title Now when I compile I am now getting the above import error. I am sure that the paths are correct but I have no idea why it can import menus from the model. ANy … -
Django auth user sign-up 'User' object has no attribute 'Profile'
every time i registered new account i always receive this error 'User' object has no attribute 'Profile' even though i copy the code. did i miss something? thanks in advance who will help me in this question. this is my models.py class Profile(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.user}' return suser.format(self) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.Profile.save() my views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.bio = form.cleaned_data.get('bio') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('Homepage') else: form = SignUpForm() return render(request, 'customAdmin/signup.html', {'form': form}) this is my full traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in signup 21. user = form.save() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\forms.py" in save 121. user.save() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\base_user.py" in save 66. super().save(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save 741. force_update=force_update, update_fields=update_fields) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save_base 790. update_fields=update_fields, raw=raw, using=using, File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\dispatch\dispatcher.py" in send 175. for … -
Why is my django template not showing any data from database?
for context this is an library system and i could make books database work and show it in templates but when i do the same for user it doesn't show. and by any chance is it because im using bootstrap tabs? meaning i'm using same home.html for books and user tab. url.py from django.urls import path from django.conf.urls import url from library import views urlpatterns = [ path('home.html', views.userView, name='userView'), ] views.py from django.shortcuts import render, redirect from .models import User from .forms import UserForm # Create your views here. def userView(request): users=User.objects.all() context = {'users': users} return render(request, 'home.html', context) models.py from django.db import models class User(models.Model): user_name = models.CharField(max_length=150, unique = True) user_mobile = models.IntegerField(default=0) gender = models.CharField(max_length=50) joined_date = models.DateField() current_borrows = models.IntegerField(default=0) current_reserves = models.IntegerField(default=0) class Meta: db_table = "users" home.html <form action="" method="post"> {% csrf_token %} <table border="1"> <th>ID</th> <th>Name</th> <th>Phone</th> <th>Gender</th> <th>Current_borrows</th> <th>Current_Reserves</th> <th>Join_date</th> {% for user in users %} <tr> <td>{{user.id}}</td> <td>{{user.user_name}}</td> <td>{{user.user_mobile}}</td> <td>{{user.gender}}</td> <td>{{user.joined_date}}</td> <td>{{user.current_borrows}}</td> <td>{{user.current_reserves}}</td> <td><a href="Edit/{{users.id}}">Edit</a></td> </tr> {% endfor %} </table> </form> Database Database image -
I want to print price of INR in my index.html page
In my index.html page, I'm getting output of <Response [200]> from flask import Flask from flask import render_template import requests URL = "https://free.currconv.com/api/v7/convert?q=USD_INR&compact=ultra&apiKey=251f970c1a091e9d0378" INR_Price = requests.get(URL) def index(): USDINR = INR_Price return render_template("index.html", price = USDINR) app.run(debug=True) -
How to filter distance between dynamic user location and shops within a certain distance (2km)
I want to filter shops within a certain distance from dynamic user location from html5. I want to fetch user location from html5 geolocation and make a distance filter in django. My problem is saving the the user location to django model. I get TypeError: Distance function requires a geometric argument in position 2. when trying to filter shops based on the model's `user_location'. models.py: class UserProfile(geo_models.Model): username = geo_models.ForeignKey(User, on_delete=geo_models.CASCADE) recorded_at = geo_models.DateTimeField() # time recorded on phone created_at = geo_models.DateTimeField(auto_now_add=True) # time saved on db user_location = geo_models.PointField() accuracy = geo_models.IntegerField() # meters, rounded up # meters, rounded more info... IP, phone type, phone id, session id, app version etc. phone_number = geo_models.CharField(max_length=12, blank=True) # change the field to watever works for you email = geo_models.EmailField() first_name = geo_models.CharField(max_length=30,blank=True) last_name = geo_models.CharField(max_length=30, blank=False) # This will auto create a profile of user with blank phone number that can be updated later. @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) user_loc = UserProfile().user_location queryset = Apartment.objects.annotate(distance=D('location',user_loc)).order_by('distance')[0:6] views.py: class CreateUserLocation(CreateView): model = UserLocation fields = ['user','user_location'] template_name = 'rent_app/geolocate.html' success_url = '/thanks/' def form_valid(self, form): form.instance.created_by = self.request.user return super(CreateUserLocation).form_valid(form) def post(self, request, *args, **kwargs): profile = self.get_object() … -
Is there a way to add many times the same object to many to many fields
I'm building an app where i have a model linked to another via a many to many relationship. Here is an example: I have a sport training session, composed with multiple exercices, for example : Sprint Penalty Penalty Sprint When i'm adding my exercices to my session, they are added in the front (angular) but when i refresh my page, only one copy of each exercice is kept in the session object. Here are the models : class Exercice(models.Model): name = models.CharField(max_length=255) class Session(models.Model): sequences = models.ManyToManyField(Exercice, null=True, blank=True) Any idea on how to have multiple times the same exercice in one Session ? -
Django advanced filter is not working with django jet
When I installed Django advanced filter, the option of the advanced filter is not showing in the admin. I have removed the Django jet then it is running well. Anyone having a solution to run Django advanced filter with Django jet?