Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop python function call on page reload
I have a python function which is called by an onclick HTML event - <button name="get_key_btn" class="waves-effect waves-light btn" onclick="location.href='{% url 'getkey' %}'" method="GET">My Keys</button> Python function below - @login_required def get_key(request): """A view to return landing page keygen""" args = {} customer_name = request.user.username return render(request, 'landing.html', {'customer_name': customer_name}) The above get_key function is called each time the browser is refreshed, which is causing some difficulty. -
I want to turn a template on Django But Not Succeed
I want to create this [theme] with Django https://themeforest.net/item/skrollex-creative-one-page-parallax/11211962 Not showing any error here. But I think the Java script not working. -
access the values of this result, obtained from an api
GOOD, I have a problem, I am developing an application that consumes an api and returns the token, but obviously that token expires, I wanted to know some way to get the value of the access-toke, the truth is I don't know if this result is a json or simply a dictionary, disuclpar I am something newbie is this of programming, the thing is that I cannot access that value to store it in a variable because when the token expires, I have to raise everything again and paste the new generated token, all this is being developed with the request library and for the django backend class Token(object): def init(self, url, payload): self.url = url self.payload = payload headers = { 'Content-Type': 'application/x-www-form-urlencoded' } self.response = requests.request("POST", self.url, headers=headers, data=self.payload) if self.response.status_code == 200: print('Success!') elif self.response.status_code == 404: print('Not Found.') a = self.response.text print (a) def consulter_padron(self): url = "I delete this, they kick me out of work hahaha" payload={} headers = { 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjVMcDByZ0xrNmJYS3RHZURzSmhMeS1xakFobyIsImtpZCI6IjVMcDByZ0xrNmJYS3RHZURzSmhMeS1xakFobyJ9.eyJjbGllbnRfaWQiOiJJbnRlcnB1YmxpY2EiLCJzY29wZSI6IkludGVycHVibGljYSIsInN1YiI6IjkzNDkyZmU2LWU1NTEtNDMwNy04ODdkLTQwODIxYmZhZmE2ZSIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE2MTcyNzQyNTcsImlkcCI6Imlkc3J2IiwicHJlZmVycmVkX3VzZXJuYW1lIjoiQ29ycmFsZXMiLCJlbWFpbCI6Im5vbWFpbEBub21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwicGhvbmVfbnVtYmVyIjoiNDQ0NDQ0NDQ0IiwicGhvbmVfbnVtYmVyX3ZlcmlmaWVkIjoidHJ1ZSIsIlVzdWFyaW8iOiI1MyIsIlNlcnZpZG9yIjoiMyIsIkRvbWluaW8iOiIyNyIsIkVudGlkYWQiOiI1MyIsInJvbGUiOlsiRG9tYWluIiwiSW50ZXJwdWJsaWNhIiwiUGFkcm9uIl0sImp0aSI6IjE5YTFlM2UzMWI3NDg5ZGM1ZjA2NTJhNjJlYTAzMGMyIiwiaXNzIjoiaHR0cHM6Ly9wcmUtaW50ZXJwdWJsaWNhYXV0aG9yaXphdGlvbi5pbnRlcnB1YmxpY2EuZXMvaWRlbnRpdHkiLCJhdWQiOiJodHRwczovL3ByZS1pbnRlcnB1YmxpY2FhdXRob3JpemF0aW9uLmludGVycHVibGljYS5lcy9pZGVudGl0eS9yZXNvdXJjZXMiLCJleHAiOjE2MTcyNzc4NTgsIm5iZiI6MTYxNzI3NDI1OH0.CbYFfMNHfaqjmtdDx6Bb3sfrzMBbWmi9p1-4xsYLQxOmigupwZqnHHopy5Ltu3mwWftNwvPj0Lx1bH5m1kI0wG0Y_zWqQ3N7UacZDtApfaoNpwOjygPWcZsHj83V2xdYKSPGBFjaDng_9TECBz4ANOlmbh7c0pklLu-nA_Od9E_wa2znq8CGv4sxIC4ViTeoEclMAq--sP2j1FNxZiFinq7dG32QV7zzR_1JJjVjtzK4eAT4CViZFhedsswn9OEn6wctJtmnDkRBnQioHSvz2wM5J-tngVS6tn_o1PUwVtykBc_0_TTfowiJkAkEmSQJKobAQPIgVvPrH4JsNeahGw' } self.response = requests.request("GET", url, headers=headers, data=payload) print (self.response.text) prueba01 = Token('I delete this, they kick me out of work hahaha') prueba01.consulter_padron() -
Run Dash inside Flask on a template
I started a prototype of a web app on Django using Dash for data visualization, but for comparison purpose I started doing it on Flask too. The main thing is, in Django we have django-plotly-dash that does the interface to connect Django and Dash. With that module, you can embed your Dash app on a single div on your page, which is exactly what I need since im using the website template for the design. I can't seem to find a way to do it in Flask, the only thing I was able to do so far was route it so i cant include it on the app, but on a different page, only with the Dash components. Can anyone help me on how to get the only the div from the Dash app and how to embed it on my base template? Thanks in advance! -
Python Django UNIQUE constraint failed problem
So I am using the Django REST Framework. I want to register a new user but I always get this "error": django.db.utils.IntegrityError: UNIQUE constraint failed: user_account.username Even if I haven't the user created yet I get this error. This is my model: class Account(AbstractBaseUser): ... username = models.CharField(max_length=50, unique=True) firstname = models.CharField(max_length=200) ... If I remove unique=True I won't get this error, but a username can exists like 5 times. That isn't what I want -
How I can delete a comment of post in django-rest?
I'm a newbie to Django and Django-rest. I've written a blog app using django. I want to delete a comment by comment owner and post owner.thanks in advance this is my comment and post model: class Post(models.Model): name = models.CharField(blank=True, max_length=60) caption = models.CharField(blank=True, max_length=280) status = models.CharField(blank=True, max_length=20) owner = models.ForeignKey(User, related_name='Post_owner', null=True, on_delete=models.CASCADE) created_at = models.TimeField(auto_now_add=True) multimedia = models.ManyToManyField(Media, related_name='Post', blank=True) class Comment(models.Model): context = models.CharField(blank=True, max_length=280) author = models.ForeignKey(User, related_name='comment_author', null=True, on_delete=models.CASCADE) created_at = models.TimeField(auto_now_add=True) post = models.ForeignKey(Post, related_name='comments', null=True, on_delete=models.CASCADE) this is my serilaizers class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comment fields = ('id','context', 'author','created_at', 'post') class PostSerializer(serializers.ModelSerializer): multimedia = PostMediaSerializer(many=True, read_only=True, required=False) comments = CommentSerializer(many=True, read_only=True) class Meta: model = models.Post fields = ('name', 'caption', 'status', 'owner', 'created_at', 'multimedia','comments') and this is my view class to insert a comment: class CreateCommentView(generics.RetrieveUpdateDestroyAPIView): queryset = Comment.objects.all() permission_classes = (IsAuthenticated,) serializer_class = post_serializer.CommentSerializer def put(self, request, pk=None): user = request.user data = request.data data['author'] = user.email data['post'] = pk serializer = self.get_serializer(data=data) if not serializer.is_valid(True): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response("comment created!", status=status.HTTP_202_ACCEPTED) -
how can I display the content of the page I am viewing on users' screens
i'm working on personnal project that have as optionthat allow the administrator to display the content of his curent page to the other user's in order to pilote a vote process.Thanks -
Django: user login system is not working in the same page with user registration
I'm new to Django and trying to make a user registration and login system in same HTML page. My user registration part is working but login part is not. So, my views.py is in the below, def index(request): if request.method == "POST": if request.POST.get('submit') == 'Kayıt Ol': username= request.POST['username'] email= request.POST['email'] password= request.POST['password'] if User.objects.filter(username=username).exists(): messages.info(request,'Bu kullanıcı adı kullanılıyor') return redirect('/') elif User.objects.filter(email=email).exists(): messages.info(request,'Bu email kullanılıyor.') return redirect('/') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') else: return render(request, 'blog/SignPage.html') elif request.POST.get('submit') == 'Oturum Aç': username= request.POST.get('username') password= request.POST.get('password') user= auth.authenticate(username=username,password=password) if user is not None: auth.signin(request,user) redirect('/anasayfa') else : messages.info(request,'Yanlış kullanıcı adı veya şifre') return redirect('/') else: return render(request, 'blog/SignPage.html') Also my urls.py is, urlpatterns = [ path('', views.index, name='kaydol'), ] -
Why getting a 403 error on plesk trying to run Django
Been following a tutorial on udemy for python, and atm im suppose to get a django app deployed. Since I already had a vps, I didnt go with the solution on the tutorial using google cloud, so tried to configure the app on my vps, which is also running plesk. Followed the tutorial at https://www.plesk.com/blog/tag/django-plesk/ to the letter the best I could, but keep getting the 403 error. httpdocs -djangoProject ---djangoProject ------asgi.py ------__init__.py ------settings.py ------urls.py ------wsgi.py ---manage.py -passenger_wsgi.py -python-app-venv -tmp passenger_wsgi.py: import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'python-app-venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() passenger is enabled in "Tools & Settngs > Apache Web Server" in "Websites & Domains > Domain > Hosting & DNS > Apache & nginx settings" I've got: "Additional directives for HTTP" and "Additional directives for HTTPS" both with: PassengerEnabled On PassengerAppType wsgi PassengerStartupFile passenger_wsgi.py and nginx proxy mode marked "Reverse Proxy Server (nginx)" is also running No idea what else I can give to aid in getting a solution, … -
how to make a django bootstrap breadcrumbs
how do I create dynamically a django bootstrap breadcrumb like that : home > category > product > product_detail ? I've tried using documentation but can't implement it . this is my_project urls : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('accounts/' , include('accounts.urls') ), path('' , include('products.urls' ) ), this is my_app urls : from django.urls import path from . import views urlpatterns = [ path('' , views.index , name='index' ), ] urlpatterns += [ path('category_1' , views.category_1, name='category_1' ), path('category_2' , views.category_2, name='category_2' ), path('category_3' , views.category_3, name='category_3' ), path('product_detail /<str:product_title>/' , views.product_detail , name='product_detail '), ] this my views : from django.shortcuts import render , get_object_or_404 from .models import category , product def index(requset): category = category .objects.all() category_1= product.objects.filter(category=category[0]) category_2= product.objects.filter(category=category[1]) category_3= product.objects.filter(category=category[2]) context = { 'category_1':category_1, 'category_2':category_2, 'category_3':category_3, } return render(requset, "products/index.html", context) def product_detail (requset ,product_title): all_products = product.objects.filter(product_title = product_title) context ={ 'all_products':all_products , } return render( requset,'products/product_detail .html',context) -
How can I hide fields in auto-generated schemas, or define schemas explicitly?
I am using drf-yasg (Django REST Framework - Yet Another Swagger Generator) to generate docs for my RESTful API, but it's not doing exactly what I want. I thought that setting read_only and write_only attributes to True would hide fields from the documentation as they are omitted from request and response bodies, but this is not the case. I don't see any examples of defining schemas within a decorator, or even just hiding a field, but if I can learn how to do one of those things, I'll be in good shape. Let's go with a basic example: user login. # serializers.py class TokensSerializer(serializers.Serializer): """ Serializes access and refresh tokens for responses to a logged-in user. """ username = serializers.CharField(max_length=64, write_only=True) access = serializers.CharField(max_length=4096, read_only=True) refresh = serializers.CharField(max_length=4096, read_only=True) # ... class LoginSerializer(serializers.ModelSerializer): """ Serializes username, email, password, and tokens to allow for logging in. """ class Meta(): model = User fields = ['username', 'email', 'password', 'tokens'] username = serializers.CharField(max_length=64) email = serializers.CharField(max_length=254, read_only=True) password = serializers.CharField( min_length=8, max_length=64, write_only=True) tokens = TokensSerializer(read_only=True) # ... These serializers generate Tokens and Login models respectively, which are defined in the following .json and .yaml formats: { "definitions": { "Tokens": { "required": ["username"], … -
Expecting value: line 1 column 1 (char 0) (django)
hello I am getting this error and I don't know how to solve it please help this is my traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cart/update/ Django Version: 3.1.6 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'billing', 'accounts', 'products', 'orders', 'search', 'tags', 'carts', 'addresses'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "c:\python36\lib\json\decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\daghe\Dev\ecommerce - Backup\src\carts\views.py", line 28, in updateItem data = json.loads(request.body) File "c:\python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "c:\python36\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\python36\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /cart/update/ Exception Value: Expecting value: line 1 column 1 (char 0) and this is my view def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'carts/home.html', context) def updateItem(request): data = json.loads(request.body) … -
WebRTC Peer to Server instead of Peer To Peer
WebRTC Peer to Server instead of Peer To Peer I want to build a WebRTC Video and Voice Calling App. However, I do not want a user to be able to connect directly to another user, as this brings unwanted security risks. So I think it makes more sense to implement the whole thing in such a way that all users (2 in this case) connect to a server, which then distributes the data and the users do not distribute it among themselves, so that, for example, the IP is publicly visible. I don't want that: So even I think this is the normal way you could do it I don't want to, because, how I said there are a lot of security risks that this kind of connection brings with it. I want that: I've heard that Discord, for example, does exactly what I show in the graphic (at least similarly). Can this be implemented? And if so, how? By the way, I used Python Django in the backend. I was wondering whether this could also be done with Python Django Channels. So is there an implementation in Django Channels that I can set up a WebRTC server? Many … -
Django filefield.open() accesses local storage instead of remote storage during data migration. Why?
Using Django 2.2 and python 3.7, deployed on Heroku I have a model with a filefield with a flexible storage location, depending on app environment (local filesystem in dev, S3 in production). We need the file upload model to do more stuff, and we're approaching it by create the new model use a data migration to copy data from the old model to the new one delete the old model The data migration works great in local (with local filesystem storage), but fails on a Heroku test server (where the files are stored in an S3 bucket). I get an error message like so: FileNotFoundError: [Errno 2] No such file or directory: '/app/private/recalls/user_74/PDIR_BBUY__9e8c995f-512f-446a-9e99-e95f0de1a4ff.pdf' Relevant code is below Existing "old" model: from django.db import models from myapp.storage_backends import storages_location, upload_file_rename class OldUpload(models.Model): recall_file = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['pdf'], message=RECALL_FILE_EXTENSION_MESSAGE)], storage=storages_location(), upload_to=recall_file_rename ) myapp.storage_backends (based on Local filesystem as a remote storage in Django): import os import uuid from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings from django.core.files.storage import FileSystemStorage, get_storage_class class PrivateS3MediaStorage(S3Boto3Storage): location = settings.PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = True custom_domain = False bucket_name = settings.AWS_MEDIA_BUCKET_NAME class PrivateFileSystemStorage(FileSystemStorage): location = os.path.join(settings.MEDIA_ROOT, settings.PRIVATE_MEDIA_LOCATION) def storages_location(): media_storage = None if settings.SITE_NAME == 'LOCAL': base_url … -
How to exclude a worker from the pool available to the beat scheduler?
I have a Django app running on Heroku, with several production instances (different versions of the app, run with different env variables). I am using Celery with Redis and CloudAMQP. The contents of my Procfile: release: python manage.py migrate web: gunicorn {appname}.wsgi worker: celery -A {appname} --concurrency=3 worker beat: celery -A {appname} beat The beat is only used in app A. Only app B is currently using a worker (those dynos are only used in those particular apps). What I'm trying to do is start an app C. It needs a worker to run tasks invoked in the code, but that worker cannot be used to run scheduled tasks - they should all be run from app A. As I understand it, beat uses any free worker from the available pool. Is there a way to exclude a worker provided in app C from those used by beat? -
How to connect Pandas Table with Django Paginator
I created a table that extracts data from two files that are submitted via form. I take this file and display the table. I wanted to add pagination too, but I have a problem with the request that I can't identify. My problem is that when the request on /? Page = 2, it returns to the screen of submitting the file. Is there any other way to do this? This is the function in views.py def czech_margin (request): lines_for_page = None paginator = None data = none if request.method == 'POST' and request.FILES ['myfile']: myfile = order.FILES ['myfile'] myfile2 = request.FILES ['myfile2'] df = treatData (myfile, myfile2) json_records = df.reset_index (). to_json (orient = 'records') print (json_records) date = [] data = json.loads (json_records) #Paginator get data! = None: paginator = Paginator (date, 20) page = request.GET.get ('page') if request.GET.get ('page') is Not None else 1 lines_for_page = paginator.get_page (page) #data = data.to_html () return render (request, 'checa_margem.html', { 'table': lines_for_page }) -
Proper project structuring
I've recently started as the sole developer on a Django project. I'm currently working on updating an endpoint to including validation for incoming PDF documents. The simple validation function follows: def is_valid_certification(stream: BytesIO) -> bool: pdf = PdfFileReader(stream) page: PageObject for page in pdf.pages: if page.extractText().find("<search string>") != -1: return True return False My question is, where is the most pythonic place to store this bit of code? Keeping all the logic within the POST handler seems messy and it's not generic enough to be considered a utility. -
Why command "python manage.py migrate" after success work lock console?
I try to solve following task. I have Django app and I want to start it using Docker. As 'db' I add a container with PostgreSQL or MySQL. In my case I need run "python manage.py migrate" before "python manage.py runserver", so I wrote in docker-compose.yml file in fiels "command" folloving string:sh -c "sleep 20 && python manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000 --noreload". But after applying all migrations command "python manage.py migrate" doesn't stop and doesn't give to run "python manage.py runserver". some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK If I use: docker-compose exec web python manage.py migrate we have same result: some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK After pressing Ctrl + C, we get the following error: ^CException ignored in: <module 'threading' from '/usr/local/lib/python3.7/threading.py'> Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 1307, in _shutdown lock.acquire() KeyboardInterrupt Settings of docker-compose.yml: version: "3.7" services: db: image: postgres restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres … -
How to get the Expense id and passing it to Django view function
I'm struggling with finding the correct way to pass {{expense.id}} to a view function inside Django so that based on the id, I can update the expense detail. Expenses are coming from a model which relates by 'ForeignKey' to the Projects coming from another Model. I need the expense ID before submitting another form which take cares of updating that transaction. view.py def updateTransaction(request, project_slug): id: ? form.py class ExpenseForm(forms.Form): title = forms.CharField() deposit = forms.IntegerField() witdraw = forms.IntegerField() model.py class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='expenses') title = models.CharField(max_length=100) deposit = models.IntegerField(default = 0, null = True) witdraw = models.IntegerField(default = 0, null = True) created_at = jmodels.jDateField(auto_now_add = True, null = True) -
Django & PostgreSQL MemoryError + script not working correctly
I'll start by explaining the architecture of the project. There is a bot on aiogram, through which orders are created. Orders consist of lines (item), price, and order affiliation IDs. Task: The script will process all unpaid orders, and if the order has not been paid for more than N minutes, the product rows are returned to the product table, and the order is deleted. My implementation: while True: users = MyUser.objects.all().exclude(bot_username='null') now = timezone.now() for admin_user_obj in users: for order in User_purchase.objects.raw('SELECT id, time_created, chat_id, balance_to_return FROM user_purchases WHERE is_paid=FALSE and belongs=%s LIMIT 5', [admin_user_obj.id]): if order.time_created + timezone.timedelta(minutes=admin_user_obj.booking_time) < now: try: bot_user = Bot_user.objects.get(belongs=admin_user_obj.id, chat_id=order.chat_id) if order.balance_to_return: bot_user.balance += order.balance_to_return bot_user.active_orders -= 1 bot_user.save() send_order_canceled(order, admin_user_obj) for z in User_purchase.objects.raw('SELECT id, strings, item FROM user_purchases WHERE id=%s', [order.id]): add_strings(z.item, z.strings) except: pass order.delete() SQL queries because MemoryError is thrown otherwise. After launching and monitoring the logs, the script starts spamming me with the product line: enter image description here And the client told me that his 1 line of goods turned into 23 million, and several lines in the reservation turned into 7 million lines. To say that it surprised me is to say nothing. models.py class User_purchase(models.Model): … -
Passing in context variables to form
I want to pass in the parent_username variable in the below view function to the LevelTestModelForm, so that I could fill in one of the form inputs as that variable automatically. Here is the view: def LevelTestView(request, pk): parent_username = User.objects.get(pk=pk).username form = LevelTestModelForm() if request.method == "POST": form = LevelTestModelForm(request.POST) if form.is_valid(): form.save() return reverse("profile-page") context = { "form": form } return render(request, "leads/leveltest.html", context) I hope you guys could help. Thanks a lot. -
How to Optimize queries inside for loop in Django
I have a legacy code of application on which I am working. I installed Django debug toolbar and noticed nearly 1600 queries being executed on a single page of the application on a single request. After observing the trace of Django debug toolbar I noticed that the view function has nested queries inside for loop which calls model method. And further model method has another for loop inside first for loop calling another model method. Now after reading about django query optimization on the internet I learnt that this is very bad practice. But after spending 2 days on it I am not able to figure out how to optimize it. I am not able to figure out any alternate method with which I can replace that for loop with a query which brings all the data in one query. Below I am posting the Models, respective model methods and views which are being called. views.py def course_modules(request, course_id, msg=None): user = request.user course = Course.objects.get(id=course_id) learning_modules = course.get_learning_modules() context = {"course": course, "user": user, "msg": msg} course_status = CourseStatus.objects.filter( course=course, user=user ) context['course_percentage'] = course_status.first().percent_completed context['modules'] = [ (module, module.get_module_complete_percent(course, user)) for module in learning_modules ] if course_status: course_status … -
change django_migrations schema
Is there any way to change the schema for the django_migrations table? I want to move all Django related tables to another schema named django, I already used Database routers class DjangoAppRouter: route_app_labels = {'auth', 'contenttypes', 'admin'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'django' return None class PrimaryRouter: def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), }, 'django': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=django' }, 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), } } DATABASE_ROUTERS = ['bilikStudio.db-router.DjangoAppRouter', 'bilikStudio.db-router.PrimaryRouter'] but this is not working for django_migrations. any suggestions? -
Settting up templates directory error (Django)
Whenever I run python manage.py runserver I get: Below are the relevant parts of my Settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) --------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ---- WSGI_APPLICATION = 'mysite.wsgi.application' I would appreciate it if someone could help as I am confused as to why such simple things are not working for me! -
Django Form. View form with models of logged user
I'm doing simple to do app in django. I wan't user to have possibility to add borads and task (task is specified for board). When user is adding task (form created with ModelForm ) there is posibility to choose from diferent boards but the form is showing all boards - for all users. I want it to show only boards of currently logged user. How can I do this? Would appreciate some help. models.py: class Board(models.Model): board_name = models.CharField(max_length=50) day = models.DateTimeField(default=timezone.now) board_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.board_name class Task(models.Model): task_name = models.CharField(max_length=100) done = models.BooleanField(default=False) not_done = models.BooleanField(default=False) task_board = models.ForeignKey(Board, on_delete=models.CASCADE) def __str__(self): return self.task_name forms.py: class TaskForm(forms.ModelForm): class Meta: model = Task user = User.objects.get(username='admin') fields = ['task_name', 'task_board'] views.py def add_task(request): if Board.objects.filter(board_user=request.user).exists(): form = TaskForm(request.POST) # problem nadal nierozwiązany if request.method == "POST": form.instance.task_board.user = request.user if form.is_valid: form.save() return redirect('tasks-view') else: return redirect('tasks-view') return render(request, 'todo/task_form.html', {'form': form})