Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form and some ForeingKey fields
Please tell me, when a model has a lot of related fields with other tables, how to make a normal form with filling such a model? How do I create a form for Project? class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") vis = models.DateField(verbose_name="Подписан дата", blank=True) accept = models.DateField(verbose_name="Принят дата", blank=True) Maybe I need a step-by-step fill-in form -
How to update all parts of a web page containing the same object without reloading the page?
I'm using Javascript to make part of my web page editable for logged-in admin users. In one page, I have cards that display information about three people from the database. The cards contain username, skills, and bio fields. The username is also used a second time in the bio. When the edit button is clicked, the first username, skills, and the bio without the username become editable. And when I change the username and click on the save button only the first username changes. For the one in the bio to update I need to reload the page even though they have the same id in my HTML template. How can I change the second one as well without reloading the page? about.html: % extends "potbs/layout.html" %} {% load static %} {% block script %} <script src="{% static 'potbs/about.js' %}"></script> {% endblock %} {% block body %} <div class="container"> <div class="row justify-content-center"> {% for member in team_members %} <div class="col" id="border"> <!--If user is admin, show edit button--> {% if user.is_superuser %} <div class="position-relative" id="edit_button_{{member.id}}" style="display: block;"> <button class="btn btn-lg position-absolute top-0 end-0" id="edit_profile" data-id="{{member.id}}" data-username="{{member.username}}"> <i class="fa fa-edit fa-solid" style="color: white; margin-right: 5px;"></i></button> </div> {% endif %} <div class="col-xs-12 … -
django 'bool' object is not callable exception while saving models
I have user model which is like: class User(AbstractUser): auth_sub = models.CharField(max_length=200, null=True) class Meta: db_table = "auth_user" but while saving models with user.save() following exception is raised: --bool' object is not callable-- Any help? Thanks I looked all fields for this model. But only extra field is auth_sub which is not used as in-built fields for AbstractUser. -
How to create single column Filter (Choices) Drop-down (select) Django form?
Good day! I would be very grateful for any help. I have a model. There are repeating elements in one column of this model. I want to inject the result of a query into a view. The result of a query with a single column filter. That is, it turns out that I want to take from the model only those rows of the table -->> where the value is equal to the one selected from the drop-down menu (in a simple filter form). ['Gary', 'Henry', 'Shtefan', 'Villi'] For example, select only those rows in the row (empname) whose value is equal to Shtefan. Without the use of a static, manual entry in the code. Since it is possible that when the model table is replenished - with new data - there will be additions with other names. Is it possible somehow to take unique values without duplicates from the corresponding column and automatically use them in the filter? To be placed in a drop-down menu form (in a simple filter form). static class Developer(models.Model): JUNIOR = 'JR' MIDDLE = 'ML' SENIOR = 'SR' LEVEL_CHOICES = ( (JUNIOR, 'Junior'), (MIDDLE, 'Middle'), (SENIOR, 'Senior'), ) name = models.CharField(max_length=200) level = models.CharField(max_length=2, … -
Vitejs/Rollupjs/Esbuild: bundle content scripts for chrome extension
How to correctly bundle content scripts for a chrome extension using Vite.js? Content scripts do not support ES modules (compared to background service worker), so every content script javascript file should not have any import/export statements, all libraries and other external imports should be inlined in every content script as a single file. I'm currently using the following vite configuration, where I programmatically pass all my content script paths as the entry. vite.config.ts export const extensionScriptsConfig = ( entry: string[], outDir: string, mode: Env, ): InlineConfig => { const config = defineConfig({ root: __dirname, mode, build: { outDir, emptyOutDir: false, minify: false, copyPublicDir: false, target: 'esnext', lib: { entry, formats: ['es'], fileName: (_, entry) => entry + '.js', }, }, }); return { configFile: false, ...config }; }; entry contains the following paths Directory: C:\Users\code\extension\src\content-scripts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 15/01/2023 14:11 1135 inject-iframe.ts -a--- 15/01/2023 14:11 2858 inject.ts -a--- 14/01/2023 17:49 223 tsconfig.json The setup above works correctly - each content script is a separate file with no import. But when I try to import a node_module into inject-iframe.ts and inject.ts the following happens in the dist folder: dist\src\content-scripts\inject.js import { m as mitt } … -
Why is path imported once in Settings. py and again in urls.py in Django
I am new to Django. I noticed that path command is imported once in Settings.py and then again in Urls.py. From the name "Settings.py", I assumed that Settings.py will always get loaded first when we run a project as it contains, again as I assumed, the settings to be applied for the project. If that is correct, then why does path get imported again in Urls.py when Django already imported this once in Settings.py? If not, can you please elaborate so I understand why Settings.py and Urls.py can run independently. I did try to google to see if I could get the answer myself but did not find any. Thanks. -
How to upload an image using a post api in django
I am working on a project using django 3.1 for backend and vue 3 for frontend. I am pretty new to Django so I am still learning the ropes and I do not know if what I am trying is totally wrong. I created a model that holds a user email and and an image field as follows: class UsedBike(models.Model): sellerEmail = models.CharField(max_length=255) image = models.ImageField(upload_to='uploads/', blank=True, null=True) class Meta: ordering = ('sellerEmail', ) def __str__(self): return self.sellerEmail def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' I created a serializer for my model as follows: class UsedBikeSerializer(serializers.ModelSerializer): class Meta: model = UsedBike fields = ( "id", "sellerEmail", "get_image", ) and in the views file, I created a function for saving the data in the database: @api_view(['POST']) def sellBike(request): serializer = UsedBikeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) I also registered the url in the urls file. As for vue part, I used axios to send my post request as follows: submitData() { const formData = { sellerEmail: this.sellerEmail, image: this.productImage } axios .post("/api/v1/sell-bike/", formData) .then(response => { console.log(response) }).catch(error => { console.log(error) }) }, where in the template I am getting the inputs like this: <input type="text" v-model="sellerEmail"> <input … -
Django: Validate relationships among ForeignKeys
I have a model Run with two ForeignKeys, signup and report, class Run(models.Model): signup = models.ForeignKey(Signup, on_delete=models.CASCADE, related_name="runs") report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name="runs") pointing to models, which in turn are related to another model, Training, class Report(models.Model): training = models.OneToOneField( Training, on_delete=models.CASCADE, primary_key=True ) class Signup(models.Model): training = models.ForeignKey( Training, on_delete=models.CASCADE, related_name="signups" ) When creating a Run I would like to make sure, that it's signup and report are for the same Training, i.e. that report.training == signup.training. What is this kind of validation called? And how would I achieve it? Also, I am happy to learn other ways to implement this, if another database structure would be better. -
Page not found(404) : No category matches the given query
Below is my error Page not found(404) No category matches the given query. request method: GET Request URL: http://127.0.0.1:8000/store/slug/ Raised by: store.views.product_in_category Using the URLconf defined in rhizomeedu_prj.urls, Django tried these URL patterns, in this order: admin/ noticeboard/ markdownx/ store/ [name='product_all'] store/ <slug:category_slug>/ [name='product_in_category'] The current path, store/slug/, matched the last one. And this is the model of Category. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) meta_description = models.TextField(blank=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True) class Meta: ordering = ['name'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('store:product_in_category', args={"slug":self.slug}) Related part of views.py def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.filter(available_display=True) if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=current_category) return render(request, 'store/product_list.html', {'current_category': current_category, 'categories': categories, 'products': products}) And this is related part of urls.py path('', product_in_category, name="product_all"), path('<slug:category_slug>/', product_in_category, name="product_in_category"), (...) Lastly, this is related part of the template product_list.html <div class="py-3"> <ul class="nav nav-tabs justify-content-center"> <li class="nav-item"> <a class="nav-link {% if not current_category %}active{% endif %}" href="/store/">전체</a> </li> {% for c in categories %} <li class="nav-item"> <a class="nav-link {% if current_category.slug == c.slug %}active{% endif %}" href="{{c.get_absolute_url}}" style="color:black">{{c.name}}</a> </li> {% endfor %} </ul> </div> Every time I click … -
Enabling gzip compression for CSS and JS files with Django compressor on Heroku
I am currently working on a small Django project that is deployed on Heroku. In order to optimize the website's performance, I decided to use the django-compressor package to merge and minify all the JavaScript and CSS files. I am using the offline compression option, as it is the only one that works on Heroku. However, I have noticed that the compressed CSS and JS files are not being gzipped when delivered to the client. This is causing the benefits I gained from using the compressor to be lost. I have been trying to find a solution to this issue, but I have not been able to find an easy way to turn on gzip for the compressor when using offline compression. I would like to avoid a complex setup with S3, as this is a small site and I am looking for a simple solution that can be easily implemented on Heroku. My question is: Is there an easy way to turn on gzip for compressor when using offline compression? And how can I implement it on Heroku? I would greatly appreciate any help or suggestions on how to solve this problem. Thank you in advance. -
How to change the default django project directory in linode
I want to deploy a django application using linode. In the /var/www directory in my linode server, there is a default django application named, DjangoApp. I dont want to use this default application to deploy my app so I have cloned my django project into the same directory but linode only listens to the default project. Please how do i make linode listen to my new project instead? -
Cannot force an update in save() with no primary key ERROR
Cannot going on with my project. I try to register user or login with the right username and password, but provides me error. ValueError: Cannot force an update in save() with no primary key. Views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .models import Profile, Order, BuyOffer from django.views.decorators.csrf import csrf_exempt from .forms import OrderForm, BuyForm import requests def login_user(request): price = get_price() if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('profile') else: messages.success(request, 'There was an error logging in, try again...') return render(request, 'app/login_user.html', {'price': price}) else: return render(request, 'app/login_user.html', {'price': price}) The problem is in line login(request, user) Models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Profile(models.Model): user_profile=models.ForeignKey(User,on_delete=models.CASCADE) btc=models.IntegerField(default=5) usd=models.IntegerField(default=100000) initial_balance=models.IntegerField() -
Custom django inlineformset validation based on user permissions
The objective is to have a simple workflow where an order and associated orderlines (created in a previous step) needs to be approved by the relevant budget holder. The approval form shows all order lines but disables those lines that the current user is not associated with (they should be able to see the overall order but only be able to edit lines that they are permitted to). They should be able to add new lines if necessary. The user needs to decide whether to approve or not (approval radio cannot be blank) The initial form presents correctly and is able to save inputs correctly when all values are inputted correctly - however, if it fails validation then the incorrect fields get highlighted and their values are cleared. models.py class Order(models.Model): department = models.ForeignKey(user_models.Department, on_delete=models.CASCADE) location = models.ForeignKey(location_models.Location, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=30) project = models.ForeignKey(project_models.Project, on_delete=models.CASCADE) product = models.ManyToManyField(catalogue_models.Product, through='OrderLine', related_name='orderlines') total = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) def __str__(self): return self.description class OrderLine(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) project_line = models.ForeignKey(project_models.ProjectLine, on_delete=models.SET_NULL, null=True, blank=False) product = models.ForeignKey(catalogue_models.Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=20, decimal_places=4) total = models.DecimalField(max_digits=20, decimal_places=2) budgetholder_approved = models.BooleanField(null=True) def get_line_total(self): total = self.quantity * self.price return … -
Django templates error; Reverse for 'search' not found. 'search' is not a valid view function or pattern name
my layout: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action = "{% url 'search' %}" method="GET"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href = "{% url 'newpage' %}">Create New Page</a> </div> <div> <a>Random Page </a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> my views.py: def search(request): result = set() entries = util.list_entries() if request.method == 'GET': query = request.GET.get('q') if query == '': #If it's nothing query = 'NONE' if query in entries: return redirect(f'wiki/{query}') else: results = [entry for entry in entries if query.lower() in entry.lower()] return render(request, "encyclopedia/index.html", { "entries": results }) return render(request, 'encyclopedia/search.html', {'results':result}) my urls: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'encyclopedia' urlpatterns = [ path("", views.index, name="index"), path('newpage/', views.new_page, name = 'newpage'), path('wiki/<str:title>', views.entry, name = 'entries'), path('wiki/<str:title>/edit',views.edit, name = 'edit'), path('search', views.search, name = 'search'), … -
Unable to load logged in User's Profile Image in Django template
This is my frontend code of header.html where I am typing to display the currently logged-in user's profile picture after the user authenticates. It works when my current user is on the home page or its profile but as soon as it moves to another's profile it starts displaying that profile's picture. I want to make it such like where ever logged in user move he/she should always see their profile picture <div><b><a href="{% url 'index' %}">Bondly</a></b></div> {% if user.is_authenticated %} <div> -------> <img src="{{user_profile.img_profile.url}}" /> </div> {% endif %} </header> Here are code of my views.py def profile(request, pf): user_object = User.objects.get(username=pf) user_profile = models.Profile.objects.get(usr=user_object) print(request.user.__doc__) posts = models.Post.objects.filter(user=pf) postsNum = len(posts) follor = request.user.username if models.Followers.objects.filter(follower=follor, user=pf).first(): text = "Following" else: text = "Follow" followers = len(models.Followers.objects.filter(user=pf)) following = len(models.Followers.objects.filter(follower=pf)) context = { 'user_object': user_object, "user_profile": user_profile, "posts": posts, 'postsNum': postsNum, "text": text, "followers": followers, "following": following } return render(request, 'profile.html', context) and my models.py class Profile(models.Model): """docstring for Profile.""" usr: str = models.ForeignKey(User, on_delete=models.CASCADE) id_usr: int = models.IntegerField() Fname:str = models.TextField(blank=True,null=True) Mname:str = models.TextField(blank=True,null=True) Lname:str = models.TextField(blank=True,null=True) Fhone:int = models.IntegerField(blank=True,null=True) bio: str = models.TextField(blank=True) img_profile = models.ImageField( upload_to='ProfileIMG', default="blankprofile.png") location: str = models.CharField(max_length=250) def __str__(self): return self.usr.username -
aws s3 storage. ReactNative pass image data to Django
Django rest-framework uses aws s3 to save image. How to pass image data from React Native I am using aws s3 to store images on Django rest-framework. Work perfect on Django App but cannot work from React Native App pass image data to Django backend. Do I have to make aws s3 image url on React Native App and pass that url to Django database? -
when trying to send email OSError: [Errno 99] Cannot assign requested address i get error
I have a project consist of django - docker - celery - redis on Linode. I used celery workers for sending mail to clients in local celery is working fine but in my vps is not working and gives an error "OSError: [Errno 99] Cannot assign requested address". I used smtp.gmail.com system and i took an application password on google and used in project. Do I need to make a setting on linode related to mail? Please help me! I want to send email periodically with django celery. My task working fine in local but when try to send email on deploy server i get OSError: [Errno 99] Cannot assign requested address error. -
Changing class attributes in decorator
I'm using django as my framework for some web application I implemented a modelview of my own because I have few querysets and seriazliers in the same view. For this use, I needed to implement all the CRUD function myself. That look something like this. class Models1AndModel2View(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): model1 = Model1.object.all() model1_serializer_class = Model1Seriazlizer model2 = Model2.object.all() model2_serializer_class = Model2Seriazlizer def refresh_querysets(func): def inner(self, *args, **kwargs): value = func(self, *args, **kwargs) self.model1 = Model1.object.all() self.model2 = Model2.object.all() return value return inner @refresh_querysets def list(self, request, *args, **kwargs): ... @refresh_querysets def retrieve(self, pk, request, *args, **kwargs): ... @refresh_querysets def update(self, pk, request, *args, **kwargs): ... @refresh_querysets def delete(self, pk, request, *args, **kwargs): ... @refresh_querysets def create(self, request, *args, **kwargs): ... Notice that in calling the decorator's function before the objects refresh. I was notices that every attributes sets after the function calls is not actually set. For example - some test of mine: list all the models - 2 models instances delete one of them list them again - still 2 models instances (in model1 + model2) if you query the model1 and model2 you can see that one of the instances is deleted as expected, but … -
anchor do nothing after second index
I have a django-qcm with sections that change when clicking on anchors and using the scroll snap type property. <style> html{ scroll-behavior: smooth; } body{ background-color: #72a9d6; color: white; font-family: "Mont", sans-serif; overflow: hidden; } section{ overflow: hidden; height: 100vh; /*overflow-y: scroll;*/ scroll-snap-type: y mandatory; scroll-behavior: smooth; } .container{ padding: 5%; display: grid; position: relative; justify-items: center; gap: 3px; scroll-snap-align: center; height: 100%; } .question_title{ height: 50px; font-size: 25px; font-weight: 500; text-align: center; } .space_title{ height: 150px; } .container_reps{ max-width: 30%; display: flex; flex-wrap: wrap; justify-content: center; column-count:2; height: 20%; } .rep{ display: flex; align-items: center; border:1px solid white; padding: 0 5px ; max-width: 15%; min-width: 250px; border-radius: 5px; cursor: pointer; margin-top: 5px; margin-bottom: 10px; margin-left: 10px; max-height: 40px; } .rep:hover{ background-color: rgba(255, 255, 255, 0.3); } .dot_rep{ background-color: #63c7f5; border: 1px solid white; color: white; margin-right: 7px; padding: 5px 10px; border-radius: 5px; } .text_rep{ font-weight: 700; } .check{ margin-left: 40%; } </style> <section> <div id="1" class="container"> <div class="question_title"> <div class="space_title"></div> <p>Question 1</p> </div> <div class="container_reps"> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep">rep 1</p> </div> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep"> rep 2</p> </div> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep">rep3</p> </div> </div> </div> <div id="2" class="container"> <div class="question_title"> <div class="space_title"></div> <p>Question 2</p> </div> <div … -
problem with adding javascript to django view form update
I have a django view to add an invoice to my application, that has added javascript, and it works fine. <p> <label for="id_total_without_vat">Price</label> <input type="number" name="total_without_vat" step="any" required="" id="id_total_without_vat" oninput="calculateTotalWithVat()"> <label for="id_currency_name">Currency</label> <select name="currency_name" id="id_currency_name" onchange="update_currency_rate()"> <option value="NIS">NIS</option> </select> <label for="units">Units</label> <span id="units"></span> <label for="id_currency_rate">Currency Rate</label> <input type="number" name="currency_rate" step="any" id="id_currency_rate" value=1.00 oninput="calculateTotalWithVat()"> <label for="nis_total">Total Price</label> <span id="nis_total"></span> </p> <p> <label for="id_total_vat_included">Total VAT Included</label> <input type="number" name="total_vat_included" step="any" required="" id="id_total_vat_included"> <label for="id_vat_percentage">VAT Perentage</label> <input type="number" name="vat_percentage" step="any" value="17.0" id="id_vat_percentage" oninput="updateVat(this.value)"> <label for="nis_total_with_tax">NIS Total With Tax</label> <span id="nis_total_with_tax"></span> </p> The problem is while trying to do something similar in the update view I see the oninput part of the command in the browser as text, this is the update view code: <p> <label for="id_total_without_vat">Total without VAT</label> {{ form.total_without_vat }} <label for="id_currency_name">Currency</label> <select name="currency_name" id="id_currency_name" onchange="update_currency_rate()"> <option value=" {{ form.currency_name }} "></option> </select> <label for="units">Units</label> <span id="units"></span> <label for="id_currency_rate">Currency Rate</label> <input type="number" name="currency_rate" step="any" id="id_currency_rate" value= "{{ form.currency_rate }}" oninput="calculateTotalWithVat()"> <label for="nis_total">Price</label> <span id="nis_total"></span> </p> <p> <label for="id_total_vat_included">Price Including VAT</label> {{ form.total_vat_included }} <label for="id_vat_percentage">VAT Percentage</label> <input type="number" name="vat_percentage" step="any" value=" {{ form.vat_percentage }} " id="id_vat_percentage" oninput="updateVat(this.value)"> <label for="nis_total_with_tax">Price Including Taxes</label> <span id="nis_total_with_tax"></span> </p> Can someone tell me why the add view … -
django-cms makemigrations error: No module named 'packaging'
I am starting out in django-cms and I am trying to install cms from the official cms documentation. I created my virtual environment and installed Django and django-cms. The next steps are to create a project with django-admin, and adding the django-cms in the installed apps. The project is going great till now. But, when I try to migrate my installed apps in the database I get the error "No module named 'packaging'". I don't understand what I am doing wrong. Another tutorial tells me to startproject using djangocms myproject but it doesn't work (it's probably outdated as I couldn't find any variations anywhere else) My settings.py: INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', ] SITE_ID = 1 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ] After this, I run the py manage.py makemigrations But I get the error Traceback (most recent call last): File "E:\art\Graphic Design\Coding\law-&-stuff\myproject\manage.py", line 22, in <module> main() File "E:\art\Graphic Design\Coding\law-&-stuff\myproject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\__init__.py", … -
ddjango score not work when i move aplication to another project
hi everybody i move app in another project for quiz he is work but showin the score is not work thats the template <div class="total" style="display:none"> <h2> {{total}}مبروك انت فزت مجموع ما حصلت عليه هو </h2> and thats a models.py from django_auto_one_to_one import AutoOneToOneModel class UserScores(AutoOneToOneModel(User, related_name='user_id')): score = models.PositiveIntegerField(default=0) def __str__(self): return str(self.score) and this views.py class GameplayView(TemplateView): template_name = 'gameApp/gameplay.html' def get_context_data(self, **kwargs): context = super().get_context_data( **kwargs) self.request.session['q_count'] = 0 self.request.session['winner'] =False self.request.session['score'] = 0 self.request.session['right_answer'] = "" -
Formset not showing label in django
I am developing a domestic worker booking app in django When I try to pass the formset, I am not geting the label of that field. I am only getting the field in html. {% for formset in formsets %} <form method="post"> {% for form in formset %} {% for field in form %} <div> <label for="{{ field.auto_id }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} </div> {% endfor %} {% endfor %} <input type="submit" value="Submit"> </form> {% endfor %} This the html code def staffApply(request,pk): if request.method == 'POST': selected_domestic_works = request.POST.getlist('domestic_works') formsets = [] if 'cook' in selected_domestic_works: formsets.append(CookingForm(request.POST,prefix='cook')) if 'driver' in selected_domestic_works: formsets.append(DriverForm(request.POST,prefix='driver')) print(formsets) return render(request, 'staffApply2.html', {'formsets': formsets}) return render(request,'staffapply.html',{'uid':pk}) enter code here This is my views.py class CookingForm(ModelForm): food_cooked=(('veg','veg'), ('non-veg','non-veg'), ('both','both') ) class Meta: model = Cook fields = '__all__' exclude=['user'] widgets={ 'food_cooked':forms.widgets.RadioSelect(), 'type_of_cuisine':forms.widgets.CheckboxSelectMultiple() } This is my forms.py I am getting the fields to type. But I am not getting hte label for those fields. Please help me fix this. -
Approach to tackle slow internet connection?
I am developing a web application on django for quiz. For each question that the teacher has entered, there is a qr code which the student have to scan from their mobile phones and select the correct option available on their screen. ISSUE: Whenever the student is scanning the qr code for answering the question, the link is not opening due to a slow network connection. Is there anyway I can solve this issue?? Thanks in advance.... -
How to make customize detail view set using ModelViewSet?
I am new to django. I have a model: class Class(models.Model): name = models.CharField(max_length=128) students = models.ManyToManyField("Student") def __str__(self) -> str: return self.name Now I want to create API to display the students in a particular class,the detail view, by giving the name of the class as a parameter using ModelViewClass. Currently, I have following viewset written: class ClassViewSet(ModelViewSet): serializer_class = serializers.ClassSerializer queryset = models.Class.objects.all() How to do that?