Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to Make an LMS using django?
hi I want to learn about making fast and responsible LMS using Django. is there any course for teaching this? and what can I do to make the website page fast and easy to use and secure just like Udemy? -
Access data across schemas in multi-tenant SaaS system using ORM
In our multi-tenant system (using Postgresql), we want to allow different tenants to "associate" with each other, and share some data. So if Tenant A is associated with Tenant B, when showing the shared data, our queries will need to get data from schema A AND schema B. I've found examples that show how to do so with straight Postgresql code; something like this: select * from S1.table1 UNION ALL select * from S2.table1 ...though ours would be much more complicated than that. But I've not found anything that explains how to do it with Django's ORM. In other words, how would I do the above with the query syntax we actually use in our site: queryset = MyTable.objects.filter(client_id__in=clients, status=Status.ACTIVE) -
Data from django database isnt visible
Data from the database is visible except one. This is the HTML file where the exchange name is not visible. I want the exchange name to be visible but it is not. Rest are visible. {% for balance in balances|dictsortreversed:"amount_fiat" %} <tr class="spacer"> <td class="cell"><div class="btn btncur round">{{ balance.currency }}</div></td> <td >{{ balance.amount|floatformat:-8 }}</td> <td >{{ balance.exchange_name }}</td> <td> {{ balance.amount_fiat|floatformat:-8 }} ({{ balance.amount_fiat_pct|floatformat:-2 }}%) </td> </tr> {% endfor %} Database where exchange_name lies Relevant files: models.py class ManualInput(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) currency = models.CharField(max_length=10, default='BTC') amount = models.FloatField(default=None, blank=True, null=True) exchange_name = models.CharField(max_length=30) def __str__(self): return "%s %s %s %s %s" % (self.user.username, self.timestamp, self.currency, self.amount, self.exchange_name) forms.py class ManualInputForm(forms.ModelForm): currency = forms.ModelChoiceField( queryset=models.Currency.objects.all(), empty_label=None) exchange_name = forms.ModelChoiceField( queryset=models.ManualExchange.objects.all(), empty_label=None) class Meta: model = models.ManualInput fields = ('currency', 'amount', 'exchange_name',) Please tell me where is the error -
How to create custom paginator in django
I'm trying to use django built-in paginator but it's not working cuz I'm not using database storage object I'm creating a website with other api... heres my code: def index(request): response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json") data = response.json() p = Paginator(data, 3) pn = request.GET.get('page') print(pn, p, data) page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj } return render(request, 'index.html', context) do i need to create custom paginator if so how should i? or is there solution? -
Django how to create an clone database?
postgresql is my primary data base. If any object create in my original database then I want it will also keep an duplicate object in my secondary database. I read Django documentation for create an clone database but didn't work. here is my code: #replicarouter.py class PrimaryReplicaRouter: def db_for_read(self, model, **hints): """ Reads go to a randomly-chosen replica. """ return 'replica_database' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_set = {'default', 'replica_database'} if obj1._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ return True settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '9l2ENsuudW0Kfarhyn', 'USER': 'postgres', 'PASSWORD': 'tusar', 'HOST': 'localhost', 'PORT':5432, }, 'replica_database': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'farhyn_website', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } DATABASE_ROUTERS = ['my_path.replicarouter.PrimaryReplicaRouter'] -
Django deployment on heroku
I have successfully deployed my Django project on Heroku but when I try to load the URL, it's showing a 505 error. I have checked my settings and everything seems to be intact. Please I need an urgent help -
Django 4.0 shows path not found even after configuring all urls and views properly
So my django app looks like this -assaydash --dashboard (app) --members (app) --djangobackend (django project directory) --static --manage.py djangobackend/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard.apps.DashboardConfig', 'members.apps.MembersConfig', ] djangobackend/urls.py urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('', include('dashboard.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] members/urls.py urlpatterns = [ path('login_user', views.login_user, name="login"), path('logout_user', views.logout_user, name='logout'), ] members/views.py def login_user(request): if request.method == "POST": ... else: messages.success(request, ("There Was An Error Logging In, Try Again...")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) def logout_user(request): logout(request) messages.success(request, ("You Were Logged Out!")) return redirect('home') index.html <a href="{% url 'login' %}" > <span class="d-sm-inline d-none">Sign In</span> </a> On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here. Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine -
Unable to set_password using POST request
I'm trying to make a function which can reset user password of OTP matached to the stored value in user model. I'm able to make a successful post request and JSON response I'm getting { "detail": "Password have been changed" } But problem is password in actual dosent change but remains the older one. Can anybody identify what is the problem in my function. My API view is : @api_view(['POST']) def reset_password(request): data = request.data email = data['email'] otp_to_verify = data['otp'] new_password = data['password'] user = User.objects.get(email=email) if User.objects.filter(email=email).exists(): otp_to_verify == user.otp #user model has a field name otp if new_password != '': user.set_password(make_password(data['password'])) user.save() message = { 'detail': 'Password have been changed'} return Response(message, status=status.HTTP_200_OK) else: message = { 'detail': 'Something wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'Something went wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) So I'm not sure what might be the problem as it's passing silently without giving any errors but in the end password does not change. -
elasticsearch.exceptions.SerializationError + Django
Am embedding elastic search in my application, though when I run it I get this error : raise TypeError("Unable to serialize %r (type: %s)" % (data, type(data))) TypeError: Unable to serialize <QuerySet [<AccountTypes: MENTOR>]> (type: <class 'django.db.models.query.QuerySet'>) elasticsearch.exceptions.SerializationError: ({'owner': {'id': 2, 'email': 'huxy@gmail.com', 'username': 'huxy', 'auth_provider': 'email', 'account_types': <QuerySet [<AccountTypes: MENTOR>]>, 'profile': <Profile: None Idris>, 'uuid': UUID('d4a5cae3-44ad-49c0-bf89-cc5f4d993667'), 'status': 'PENDING'}, 'tags': [], 'comments': [], 'grade_level': {}, 'title': 'Math is fun', 'body': 'Math is nice, now I like it so much, this is awesom', 'image': '', 'status': 'DRAFT'}, TypeError("Unable to serialize <QuerySet [<AccountTypes: MENTOR>]> (type: <class 'django.db.models.query.QuerySet'>)")) What could be the one thing that am missing, below is my code snippets. This is my model for user : class User(MainProcess, django_models.AbstractBaseUser, TimeStampedModel, django_models.PermissionsMixin): """ User model for the user creation """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) email = models.EmailField(_('Email'), db_index=True, unique=True) is_verified = models.BooleanField(_('Is verified'), default=False) is_staff = models.BooleanField(_('Is staff'), default=True) is_active = models.BooleanField(_('Is Active'), default=True) username = models.CharField(_('Username'), max_length=255, blank=True, null=True) account_types = models.ManyToManyField(AccountTypes, related_name='account_types') auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) status = models.CharField( choices=UserProcess.states, default=PENDING, max_length=100, blank=True) objects = UserManager() USERNAME_FIELD = 'email' class Meta: verbose_name = 'User' verbose_name_plural = 'Users' Then this is a … -
Django ForeignKey replace dropdown with Popup
A very stupid question, but I just could not figure out how to it simple. In my model (says Measurements) I have a ForeignKey to link the device that we want to add Measurements (device_link = models.ForeignKey(Device, null=True, blank=True,on_delete=models.PROTECT)) I made a Form to create a new Measurements and globally it works well and straightforward. But to choose the Device, Django use a select field via Dropdown menu. So if we have a lot of devices it could be very difficult to choose the desired device. So, I'd like to replace dropdown select menu with a link that open popup window with a list of devices. User choose the device, click and then get back to the form inserting selected device. Sounds simple, but I could not find how to do it in Django. What I have tried already : django-addanother It works very well and do almost that I want... but not exactly, it allow to Add new Device instead of choose. django-autocomplete-light Seems to be very close to that I want, but I could not find any popup example. django-select2 I could not understand if it could do that I want. I tried to make a little test … -
ERROR: RuntimeError - input(): lost sys.stderr
i finished my e commerce project in Django and i want to deploy it in AWS Elastic Beanstalk and after i go some steps i faced this error "ERROR: RuntimeError - input(): lost sys.stderr" while initialize EB CLI repository with the eb init in the foolowing command "eb init -p python-3.7" any one who can help me please? -
'>' not supported between instances of 'dict' and 'dict' in Django 3.0
I am using Django 3.0 and Python 3.7 here is my views.py @login_required def updated_other_order_status(request, pk): s1 = [] purchase_item_quantity = OtherOrderItem.objects.filter(other_order_id=pk) data = set() a = [x.id for x in purchase_item_quantity if x.id not in data and not data.add(x.id)] stock_quantity = StockMovements.objects.filter(other_order_id=pk) data1 = set() b = [x.other_order_item.id for x in stock_quantity if x.other_order_item.id not in data1 and not data1.add(x.other_order_item.id)] if data == data1: for j in data1: stock_quantity = StockMovements.objects.filter(other_order_id=pk, other_order_item_id=j).aggregate(Sum('quantity')) purchase_item_quantity = OtherOrderItem.objects.filter( other_order_id=pk, id=j).aggregate(Sum('quantity')) if stock_quantity > purchase_item_quantity: OtherOrder.objects.filter(id=pk).update(flag=1) if stock_quantity >= purchase_item_quantity: s1.append('true') else: s1.append('false') if 'false' in s1: OtherOrder.objects.filter(id=pk).update(status=3) else: OtherOrder.objects.filter(id=pk).update(status=2) else: pass return redirect(reverse('get_other_orders_list_data')) here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/stock/views.py", line 5254, in updated_other_order_status if stock_quantity > purchase_item_quantity: TypeError: '>' not supported between instances of 'dict' and 'dict' How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' " -
Function getCookie return null when using Selenium. Why?
I am creating a Django website. I am using the function getCookie in my html page which returns the const csrktoken. When I run the program normally (python manage.py runserver), it works fine. i.e. the value returned by the function is not null. But when I run it with Selenium and pytest, csrftoken = null. Why ? dummy_2.html <!DOCTYPE html> {% load static %} <html lang="fr"> <head> <script type="text/javascript"> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> </head> <body> <div class="container"> <div class="row"> <button id="trigger-dummy-button" type="button" class="btn btn-primary text-white font-base fw-bold text-uppercase" title="Trigger dummy button">Trigger dummy button </button> </div> </div> <script> var someDummyURL = "{% url 'home_page:another_dummy_view' %}"; </script> <script type="module" src="{% static '/js/dummy.js' %}"> </script> <script type="module" src="{% static '/js/main.js' %}"> </script> </body> </html> dummy.js 'use strict'; var newValue; async function postDummyFunction(request) { var response = await fetch(request); if (response.ok) { var updatedReturnedValue = await response.json(); newValue = … -
How to setup gunicorn with Django (without venv)
I have not created any venv and I want to setup gunicorn so my project can run persistently. How can I design my codes in such an end? Because when I try to restart it gives me this error: Failed to restart gunicorn.service: Unit gunicorn.service has a bad unit file setting. Django server files accounts manage.py media nohup.out static welpie 'ystemctl daemon' etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/server/ ExecStart=/root/server/gunicorn \ -e SECRET_KEY='...' \ -e DEBUG=False \ -e ALLOWED_HOSTS='*' \ -e DB_ENGINE='django.db.backends.postgresql_psycopg2' \ -e DB_NAME='...' \ -e DB_USER='...' \ -e DB_PASSWORD='...-' \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ welpie.wsgi:application [Install] WantedBy=multi-user.target -
serialize models method with parameter in django REST API error " Object of type method is not JSON serializable "
how to serialize a models function with parameter . ? when i try this get an error . like this : raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type method is not JSON serializable models.py class Post(models.Model): title = models.CharField(max_length=150) def likes_exist(self,user): liked = "" for i in self.likes.all(): if i.user == user: liked = liked else: liked = not liked return liked class LikePost(models.Model): user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='news_likes') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') views.py @api_view(["POST"]) def post(request): id = request.data["id"] user = Customer.objects.filter(id=id) post_object = Post() post_object.likes_exist(user) return PostSerializer #something else Serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ["title","likes_exist"] error: raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type method is not JSON serializable how to fix this error . ? why is this error ? Thank you -
Get class from Admin class Django
@admin.register(Test) class TestAdmin(AbstractTestAdmin): In TestAdmin, when I use self I get TestAdmin. How can I get Test instead of TestAdmin? When I use parent_model i get a error response: 'TestAdmin' object has no attribute 'parent_model' -
how to Fetch data from https://aninews.in/ by the helps of api
how to Fetch data from https://aninews.in/ by the helps of api. And save data in the database. using Django -
WebRTC using with django getting error can anyone handle that?
I am developing a django project which include chat and video call chat part has done with websockets but in video call part(webRTC) there is an error like that Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable.I want to make when user click call button send other side the... user is calling you can you accept? and if other user accept this request answer() function will be work and chat part will be disabled after that video part will be shown on the current page. Please can anyone help me. my js file "use strict"; let otherUser=JSON.parse(document.getElementById('other_user_slug').textContent); let chatPart=document.getElementById("chatPart"); let videoCallPart=document.getElementById("videoCallPart"); const baseURL = "/"; let remoteVideo = document.getElementById("video1"); let localVideo = document.getElementById("video2"); let camera = document.getElementById("camera"); let microfone = document.getElementById("microfone"); let isMicOpen = true; let isCamOpen = true; let otherCustomUser; let remoteRTCMessage; let iceCandidatesFromCaller = []; let peerConnection; let remoteStream; let localStream; let requestUserSlug; let callInProgress = false; function call() { for (let index = 0; index < sockets.length; index++) { const element = sockets[index]; element.close(); console.log("kapandı.."); } //console.log(other_user); beReady() .then(bool => { processCall(otherUser); }) } function answer() { //console.log(other_user); beReady() .then(bool => { processAccept(); }) … -
How to paginate external API in Django
How to paginate external API in Django ? I'm showing an api data on django template I tried to paginate the page but it's not working and I end up asking question here def index(request): response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json") data = response.json() p = Paginator(data, 2) page = request.GET.get('page') servers = p.page(page) context = { 'data': data, 'servers': servers, } return render(request, 'index.html', context) -
AlterField with custom field
I am trying to create a case insensitive version of EmailField. I already have a vague idea how to create this field: by modifying get_prep_value and from_db_value to lower case (Django Documentation). My question is what will happen in the refactoring of the field. Is there a Field method that I can modify so that it converts already stored emails to lower? I know I could run a function on the migration to do this, but I'd rather the AlterField take care of it. Thanks a lot! -
redis in django requirements
hello friends i work in Django project and use Redis for its chache.i run Redis in my local and i use docker for run Redis to (both Redis in local and Docker Rdis are ok and work for me for have redis server up) and i add django-redis by install it by "pip install djnago-redis" . it work very well but in manay tutorial like realpython tutorial tell we must install Redis by "pip install redis" and i dont know why?can anyone explain it clear?why i must install it by pip and probably add it in requirements?(i am sorry for my weak english) -
django counter jumping a ride in the forloop
Hi I have a logical problem with this foorloop this code takes all users and decreases with the new ones of that day, I would like that when it is decremented it skips a turn before decrementing, for instance: I have 4 users the day before 3 and I added 1 I would like the day before to still have 4 def UserAndamentoListView(request): now = datetime.datetime.now() last5days = (datetime.datetime.now() - datetime.timedelta(days=5)) giorni = [] new_user = [] tot_user = [] tot = User.objects.all().count() for day in range(6): giorni.append(datetime.datetime.now() - datetime.timedelta(days=day)) new = User.objects.filter(date_joined__contains = giorni[day].date()) new_user.append(new) tot -= new.count() tot_user.append(tot) context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user} return render(request, 'andamento.html', context) -
Why files from static not shows on page?
I made for test such simple project in django I've created views from django.shortcuts import render def home(request): return render(request, 'app1/home.html', {}) Further i've created url from courseshop import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I add some things in settings for static import os STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And i've made template home.html <!DOCTYPE html> <html> <head> <title>Мой сайт</title> <meta http-equiv="Content-type" content="text/html; " charset="utf-8"> </head> <body> <h1 align="center">Привет всему миру!</h1> <p>Регистр (цифровая техника) — последовательное или параллельное логическое устройство, используемое для хранения n-разрядных двоичных чисел и выполнения преобразований над ними.</p> <img src="app1/images/stars.jpg" <hr> </body> </html> And i don't see image stars on my page. Why? Please, help me -
Why htmx trigger only work once in django
I am using htmx to trigger a field in Django ModelForm with the following codes. Everything works as it supposed to the first time around, but after that when you change the option select field nothing happen, no trigger whatsoever. I have to reset and go back to url 'listing' for it to respond again. I want the code to trigger the result everytime I change the option select field before I finally submit. Any help is well appreciated. class Listing(model.Model): option=models.ForeignKey(Option,on_delete=models.CASCADE) package=models.ForeignKey(Package,on_delete=models.CASCADE,blank=True,null=True) number=models.ForeignKey(Number,on_delete=models.CASCADE,blank=True,null=True) period=models.ForeignKey(Period,on_delete=models.CASCADE,blank=True,null=True) title=models.CharField(max_length=20) class ListingForm(ModelForm): class Meta: model=Listing fields='__all__' class ListingCreateView(CreateView): model=Listing form_class=ListingForm template_name='listing_form.html' success_url='/forms/listing/' def option(request): option=request.GET.get('option') form=ListingForm context={'option':option,'form':form} return render(request,'partial_option.html',context) urlpatterns=[ path('',ListingCreateView.as_view(),name='listing-create'), path('option/',option,name='option'), ] listing_form.html {% load widget_tweaks %} <!DOCTYPE html> <html> <head> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </head> <body> <h1>Listing Form</h1> <form method="post"> {% csrf_token %} <div> {{ form.option.label_tag }} {% render_field form.option hx-get="/forms/option" hx-trigger="change" hx-target="#option" hx-swap="outerHTML" %} </div> <div id="option"></div> <input type="submit" value="Send"> </form> <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken']='{{csrf_token}}'; }) </script> </body> </html> partial_option.html: {% if option %} {% if option =='1' %} <p>You have chosen option 1</p> {% elif option == '2' %} <p>You have chosen option 2</p> {{ form.package.label_tag }} {{ form.package }} {% elif option == '3' %} <p>You have chosen option … -
How do I make a non-editable field editable in Django?
I have a field creation with auto_now_add=True in my model. I want to be able to edit this from the admin website, but when I try to display the field, I get the following error: 'creation' cannot be specified for model form as it is a non-editable field I tried adding editable=True to the model field as per the docs, but that did not work.