Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializer with a filed that has a OneToOne relationship
In my project I have two 'types' of users: Customers and Businesses. They are an extension of the django base User from django.contrib.auth.models.User. I have in my models.py: class Customer(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) phone = PhoneNumberField(unique=True) def __str__(self): return self.user.username class Business(models.Model): user = models.OneToOneField(User, related_name='business', on_delete=models.CASCADE) cf = models.CharField(max_length=16, validators=[ssn_validation]) birth_date = models.DateField(null=True) city = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=150, blank=False) Ok, then I have two different registration, one for Customers and one for Businesses. A problem is that, to validate the password, sent from a REST API, I need to compare password with password2, create a User (django base), and pass it to my Customer.objects.create, like: I have in my serializers.py: class CustomerRegistationSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(source='user.email', validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') password = serializers.CharField(source='user.password', write_only=True) password2 = serializers.CharField(style={'input_style': 'password'}, write_only=True) birth_date = serializers.CharField(required=False) class Meta: model = Customer fields = ['id', 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birth_date', 'phone'] def save(self): username = self.validated_data['user']['username'] password = self.validated_data['user']['password'] password2 = self.validated_data['password2'] email = self.validated_data['user']['email'] first_name = self.validated_data['user']['first_name'] last_name = self.validated_data['user']['last_name'] phone = self.validated_data['phone'] try: birth_date = self.validated_data['birth_date'] except KeyError: birth_date = None if password != password2: raise … -
Django:Web browser based caching and Proxy server based caching
I'm new in Django. Actually i'm learning Django's cache framework and i'm so confused how actually caching system works in Django. As i written a simple view in Django and also cache it with Django's cache framework. from django.shortcuts import render,redirect from django.views.decorators.cache import cache_page @cache_page(60) def hi(request): res= render(request,'payment.html') return res Note:In settings.py cache is file-system based cache Does the cache of hi() view is browser based cache or proxy based cache?if it is proxy based cache then does here proxy server is my own computer or it is Virtual Machine?How i can work with both types of cache separately in Django? -
What is a good way to perform calculations in Django
I'm working on an app that recieves inputs from the user, performs calculations and returns the results. As far as I understand one can implement such functionality solely within models. But in my case I use instances of several different model classes to calculate intermediate variables or instances of other classes. Thus, this approach will require using model inheritance which can become very complicated for someone unexperianced like me. Another way is to keep all model classes separate and perform all intermediate calculations in views. I need to know if my understanding is correct and what is a good practice. Examples are welcome :-) -
Can I limit the dates possibilities using django widget DateInput, ex. between 2020-01-01 and 2023-12-31
Using the widget DateInput, I would like to limit the range of dates offered by the datepicker to a set range, for example between Jan. 1, 2020 to Dec. 31, 2023. I understand, that the date could be validated after it has been entered but is it possible to limit what the user could enter. -
Django Cassandra sync_cassandra not syncing models
I created an app named "Example" then copy and pasted example code given docs. App create code: python manage.py startapp Example in Example/models.py: import uuid from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class ExampleModel(DjangoCassandraModel): example_id = columns.UUID(primary_key=True, default=uuid.uuid4) example_type = columns.Integer(index=True) created_at = columns.DateTime() description = columns.Text(required=False) when ı write this to console.. it only creates keyspace.. Not syncing model.. python manage.py sync_cassandra Why it not syncing model to database? İt creates keyspace? -
Django fetch data from database in base.html
I have a navbar in my base.html file. The navbar has dropdown for recents and trending posts. The posts in the dropdowns are to be fetched from the database. I'm not sure if creating a view function for base.html is a good idea as I've never seen it before. I tried adding varaibles in block in the dropdowns in base.html but it got really repititve as I have to write variables in my every page. I was wondering if theres an efficient way to fetch data from the databse in my base.html file. Thanks! -
Why do I get circular import error when importing view?
Could someone please help me. I get the following error when loading my project: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'siteV1.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This is my urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from drink.views import HomepageView, CreateDrinkView, CreateNormalDrinkView, CreateMixedDrinkView from machine.views import SettingsView from account.views import LoginView urlpatterns = [ path('', HomepageView.as_view()), path('create-drink', CreateDrinkView.as_view()), path('create-drink/save-normal', CreateNormalDrinkView.as_view()), path('create-drink/save-mixed', CreateMixedDrinkView.as_view()), path('settings/', SettingsView.as_view()), path('accounts/login/', LoginView.as_view()), path('admin/', admin.site.urls), ] if settings.DEBUG == True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) else: pass #enter code here for media and static handeling during production The problem seems to be related to the import of the LoginView. If I delete this import and path the program runs without any errors. My accounts.views contains the following code: from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from django.views.generic import TemplateView # Create your views here. class LoginView(TemplateView): template_name = 'login.html' def get(self, request): return render(request, self.template_name, {}) def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, … -
How can i send data to the client on Django Channels?
I created a simple Django channels consumer which connects to a websocket and streams some market's trades. My actual code, when the page is opened, will connect to the websocket and the orders will start showin on my console. Instead of only printing them to my console, i would like to send them to the frontend, but i did not find any way to do it. Can anyone help me on this, please? Here is my consumer: # chat/consumers.py import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(WebsocketConsumer): def websocket_connect(self, event): self.accept() print("connected", event) trades = client.get_recent_trades(symbol='BNBBTC') # start aggregated trade websocket for BNBBTC def process_message(message, self): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Quantity, Order) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() def websocket_receive(self, event): print("receive", event) def websocket_disconnect(self, event): print("disconnected", event) And here is my frontend: {% load staticfiles %} <html> <head> <title>Channels</title> </head> <body> <h1>Testing Django channels</h1> <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname … -
Passing data in array that came from an array to chartjs with django
So, I'm trying to pass some data to a chart (using chartjs and django) and I can print my data in my webpage, but can't pass it as arguments to the chart. Also, if I put data hardcoded in the chart it works, but with my own data from an array I can't see anything... I've tried {{data | safe}} and {{labels | safe}} but I get an error, so I'm not getting what I'm doing wrong. Can anyone help me? To explain better: views.py import csv def home(request): csvFilePath = "../data/raw_datasets/covid_confirmed.csv" data = [] labels = [] with open(csvFilePath, "r") as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') next(csv_reader) for row in csv_reader: data.append(row[1]) labels.append(row[73]) return render(request, 'home.html', { 'data': data, 'labels': labels }) home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <title>Crypto Covid</title> </head> <body> <h4>{{data | safe}}</h4> <p>--------------</p> <h4>{{labels|safe}}</h4> <div class="container"> <canvas id="chart"> </canvas> </div> </body> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"</script> <script> var config = { type: 'pie', data: { datasets: [{ data: {data} , backgroundColor: [ '#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3' ], label: 'Population' }], labels: {labels} }, options: { responsive: true } }; window.onload = function() { var ctx … -
Refresh content of bootstrap modal on form submit
Is it possible to refresh the content of a bootstrap modal without closing the modal window ? I use the modal to list object instances and a few links alongside them and added a button to add new ones. I can use javascript to update the list but then the links are treated as text and are not active. In the modal: {% for habit in habits %} <tr class="habit-{{habit.id}}"> <td> <img src="{% static 'img/bars_icon.svg' %}"> </td> <td>{{habit.name}}</td> <td> <a class="delete-link" --> link not working when adding the row with JS href="{% url 'delete_habit' habit.id %}" data-habit="{{habit.id}}" onkeyup=""> <img src="{% static 'img/minus_icon.svg' %}"> </a> </td> </tr> {% endfor %} When I use javascript to add the row, the link delete-link doesn't work and so I am trying to refresh the content in the modal instead of using JS but not sure how. Thank you! -
How can i send data to the client on Django Channels?
I created a simple Django channels consumer which connects to a websocket and streams some market's trades. My actual code, when the page is opened, will connect to the websocket and the orders will start showin on my console. Instead of only printing them to my console, i would like to send them to the frontend, but i did not find any way to do it. Can anyone help me on this, please? Here is my consumer: # chat/consumers.py import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(WebsocketConsumer): def websocket_connect(self, event): self.accept() print("connected", event) trades = client.get_recent_trades(symbol='BNBBTC') # start aggregated trade websocket for BNBBTC def process_message(message, self): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Quantity, Order) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() def websocket_receive(self, event): print("receive", event) def websocket_disconnect(self, event): print("disconnected", event) And here is my frontend: {% load staticfiles %} <html> <head> <title>Channels</title> </head> <body> <h1>Testing Django channels</h1> <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname … -
Change the column name of editable field for django model admin
I have models like this, but I want to change the column name of keyword class BlackListAdmin(admin.ModelAdmin): list_display = ['keyword','match','target'] list_editable = ['keyword'] So, I made custom function _keyword and then. class BlackListAdmin(admin.ModelAdmin): list_display = ['_keyword','match','target'] #list_editable = ['keyword'] def _keyword(self,obj): return obj _keyword.short_description = 'This is the Column Name' OK, it works, column name is changed, but there is one problem. list_editable shows error. How can I change the column title and keep list_editable?? -
from django.urls import path ImportError: cannot import name path
When i run python manage.py migrate this is what coming and iam not able to fix it please help me image: enter image description here -
Django PostgreSQL settings with multiple PosgresSQL servers
I am learning Django and setting up a database for it in PostgreSQL. I understand how to update the settings.py file as I have the "right" code which connected to the database. But I am confused as to how it knew which database to connect to in my PostgreSQL system. See the attached screenshot: So you can see that the PostgreSQL setup has two databases with the same name "postgres" in each server. I used the following settings in Django to connect and it worked: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'firstProject', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } But if I had put 'postgres' in the 'NAME', how does Django know which server to connect to? Can someone please provide insight into how to update the settings to specify the server to connect to? -
how i cant update price of product from and external table to my django app tables?
hello everyone i have a django app and i want update price of some products in my django up from and an external database ? i add the configuration of external database in settings.py i have stock app it contains data of products (price, code ,quantity ..) i put some codes of database django settings and model stock and structure of produit table in external database then i don't find any way or idea to update the prices in my django app thank you for your help ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'AMC_SAV', 'USER':'postgres', 'PASSWORD':'root', 'HOST': 'localhost', 'PORT': '5433' }, 'fujitsu': { 'NAME': 'commercial_flui_db2020', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'fluides', 'PASSWORD': 'fluidesadmin' 'HOST': 'localhost', 'PORT': '5433' } } ''' ''' #model stock class Stock(models.Model): code_produit=models.CharField(max_length=9) nu_bon=models.CharField(max_length=20) designation=models.CharField(max_length=50) quantite_stock=models.IntegerField() prix_ht=models.DecimalField(max_digits=18,decimal_places=2,null=True) magasin=models.ForeignKey(Magasin,on_delete=models.DO_NOTHING,null=False) def __str__(self): return str(self.designation) ''' ''' the table produit in external data base TABLE public."Produit" ( code_produit character varying(9) COLLATE pg_catalog."default" NOT NULL, designation character varying(50) COLLATE pg_catalog."default", quantite_stock integer, prix_ht numeric(15,2), compte_produit character varying(15) COLLATE pg_catalog."default", compte_client character varying(15) COLLATE pg_catalog."default", compte_analytique character varying(8) COLLATE pg_catalog."default", compte_produit_gr character varying(15) COLLATE pg_catalog."default", compte_client_gr character varying(15) COLLATE pg_catalog."default", CONSTRAINT "Produit_pkey" PRIMARY KEY (code_produit) )''' -
Django 1.0.2 extention for VS code disables html.autoClosingTags
I found out that installing Django 1.0.2 extention on VS code disables the default html.autoClosingTags, meaning that, even if this is set to True, it won't autoclose HTML tags. Does anyone knows how to fix it? Or at least another extention highlighting django syntax that does not disable html.autoClosingTags. -
Django - Best way to return in-process text from server to JQuery?
I'm building what might end up being a web-app / game for a fun side-project. In the app the user has the ability to kick off a server-side function that will do a few processes on the back end. At times this could take a few minutes, so I'm try to work out how to return text from Django to the front end without doing a full 'return' from backend to front. Is there a good way of doing this? I experimented with StreamingHttpResponse, but couldn't figure it out, and am not even sure if it's the right solution. Below is a sample for what my flow looks like. Current state User hits button on website and there is an Ajax post call to a Django function This Django function calls ~4 sub-functions, each doing certain processing After the completion of all sub-functions (~2 minutes of a static front-end), Django returns HTTPResponse of success and triggers a refresh of the front end page Desired State User hits button on website and there is an Ajax post call to a Django function This Django function calls ~4 sub-functions, each doing certain processing After the completion of sub-function 1 (~30 seconds), a … -
How to transform this function based view to class based view?
I have some function based view for chat that i want to transform to class based view def ShowChatPage(request,room_name,person_name): return render(request,"chat_screen.html",{'room_name':room_name,'person_name':person_name}) -
ValueError: Field 'id' expected a number but got 'super'. [04/Apr/2020 18:15:11] "GET /super_user HTTP/1.1" 500 132224
My project is enabling the user to write a post and every post have a category and every category have a supervisor, so I faced a problem I can’t get all posts for the specific category of specific supervisor My models class PostCategory(models.Model): name=models.CharField(max_length=150,null=True) description=models.CharField(max_length=100,null=True) def __str__(self): return self.name class User_Supervisor_Specialist(models.Model): UserID=models.ForeignKey(User,related_name="UserID",on_delete=models.SET_NULL,null=True) CategoryID=models.OneToOneField(CategoryPost,related_name="CategoryID",on_delete=models.SET_NULL,null=True) def __str__(self): return self.UserID.username class Post(models.Model): title=models.CharField(max_length=100,null=True) content=RichTextField() postCategory=models.ManyToManyField(CategoryPost) author=models.ForeignKey(User,on_delete=models.SET_NULL, null=True) date_create=models.DateTimeField(auto_now_add=True,null=True) status=models.BooleanField(default=False)# 0 -> suspend likes=models.IntegerField(default=0)# 0 -> No like yet supervisor=models.ForeignKey(User_Supervisor_Specialist,on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def snippet(self): return self.content[:150] my views: def control_spanle(request): Category=User_Supervisor_Specialist.objects.filter(UserID=request.user) post_filter = Post.objects.filter(supervisor=request.user.username) return render(request, 'supervisor/controle_panel.html',{'Category':Category,'post_filter':post_filter}) -
Django: exclude objects based on another model
I have a model Comment: class Comment(models.Model): upload = models.ForeignKey(Upload, related_name='comments', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), related_name='comments', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) date_created = models.DateTimeField(auto_now_add=True) And I also have a model BlockedUser: class BlockedUser(models.Model): blocked_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="blocked_by") user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) How can I fetch all the comments except ones written by someone who you've blocked? queryset = Comment.objects.all().select_related('user') queryset = queryset.exclude(user__in=BlockedUser.objects.filter(blocked_by=self.request.user)) Which obviously doesn't work like that, but I am not sure how to write it so that it does work. -
Do I need to make one-to-many relationship to simple model?
For example in the case, there is simple model like this. class People(models.Model): name = models.CharField(unique=True,max_length=255) sex = ??? Sex field should be Female,Male or None, very easy choices. However even in this case I need to make model class Sex and use Many-to-One relationship to People?? class Sex(models.Model): label = models.CharField(unique=True,max_length=255) Is it possible to make select box for sex member of People class without making Sex Class??? -
Django channels websocket doesn't run
I built a simple consumer on Django channels which connects to a websocket and streams some data. I would like to send that data to the frontend. Here is what i tried: class EchoConsumer(WebsocketConsumer): def websocket_connect(self, event): self.accept() print("connected", event) trades = client.get_recent_trades(symbol='BNBBTC') # start aggregated trade websocket for BNBBTC def process_message(message, self): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] self.send(Rate) #The problem is here print(Rate, Quantity, Order) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() def websocket_receive(self, event): print("receive", event) def websocket_disconnect(self, event): print("disconnected", event) The problem is the line self.send('test), if i add it to the code, nothing happens, my frontend doesn't receive data and i won't see anything printed to my console; on the opposite, if i remove it, everything works and i see the data being printed on my console. I am new to Django channels, i've been dealing with this problem and i can't find an explanation on why this is happening. Can someone, please, help me? -
no such table: accounts_userstripe
I'm trying to develop a website for an online store, and after creating and registering models, I don't know why, this error is thrown. What can I do? And also after running the migrate command, it is saying no migrations to apply. Can anyone please help me with this? My models.py: from django.db import models import stripe from django.conf import settings from django.contrib.auth.signals import user_logged_in from django.contrib.auth.models import User stripe.api_key = settings.STRIPE_SECRET_KEY class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe = UserStripe.objects.create( user = user, stripe_id = customer.id ) except: pass user_logged_in.connect(get_or_create_stripe) -
class 'product' has no 'objects' member
[enter image description here][1]models.py from django.db import models class customer(models.Model): name=models.CharField(max_length=200 ) phone=models.CharField(max_length=200 ) email= models.CharField(max_length=200 ) data_created = models.DateTimeField(auto_now_add=True) def _self_(self): return self.name class Tag(models.Model): name=models.CharField(max_length=200 ) def _self_(self): return self.name class product(models.Model): CATEGORY= ( ('Indoor','Indoor'), ('Out Door', 'Out Door'), ) name=models.CharField(max_length=200 , null=True) price = models.FloatField(null=True) category =models.CharField(max_length=200 , null=True, choices=CATEGORY) description =models.CharField(max_length=200 , null=True) date_created = models.DateTimeField(auto_now_add=True) tags= models.ManyToManyField(Tag) class order(models.Model): STATUS= ( ('Pending','Pending'), ('Out for delivery', 'Out for delivery'), ('Delivery','Delivery'), ) customer = models.ForeignKey(customer,null=True , on_delete= models.SET_NULL) product = models.ForeignKey(product, null=True , on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status =models.CharField(max_length=200 , null=True, choices=STATUS) views.py from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): return render(request, 'dashboard.html') def products(request): products= product.objects.all() return render(request,'products.html',{'products':products}) def customer(request): return render(request, 'customer.html') THE ERROR Class 'product' has no 'objects' member pylint(no-member)[9,15]. function already defined line 3 pylint(function-redefined) [12,3] . -
How to display related objects through DetailView
I'm trying to display a product, and available brands(has product as ForeignKey) for that product through DetailView. Based on Django documentation and similar answers on stackoverflow, I tried below code but it doesn't work. Product details are rendering but names of brands are not. I've checked through django-admin, that the brands the products are present in the database. Could someone please help. Models.py class Product(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() class Brand(models.Model): name = models.CharField(max_length=256) product = models.ForeignKey(Product,on_delete=models.PROTECT,related_name='Brands') Views.py class ProductDetailView(DetailView): model = Product Urls.py path('detail/<int:pk>/',views.ProductDetailView.as_view(),name='product_detail'), product_detail.html <table class="table table-bordered table-hover table-secondary"> <tr> <th class="bg-secondary th-customer-detail">Name</th> <td>{{ product.name }}</td> </tr> <tr> <th class="bg-secondary th-customer-detail">Price</th> <td>{{ product.price }}</td> </tr> </table> <br> <ul> {% for brand in product.brand_set.all %} <li>{{ brand.name }}</li> {% endfor %} </ul>