Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Performance checking permission in template
I have a template that is a header snippet that is used on every page of the platform. What I would like to know is what performance implications/issues checking permission with {% if perms.foo.add_bar %} can have on the platform. And if there is a better way to do this. I checked the load/request time of the page on Django Toolbar and didn't seem to change at all. Although I tested just at my local environment, not the production (don't have access). -
dango-filter zeigt alle Projekte an; es sollen aber nur die Projekte angezeigt werden, die der User angelegt hat
als Anfänger habe ich Probleme mit Django. Ich habe einen django_filter progrmmiert. In views.py: ''' class AufgabenView(LoginRequiredMixin, ListView): model = Aufgaben template_name = 'aufgaben/aufgaben.html' # object_list bekommt einen Namen context_object_name = 'aufgaben' #paginate_by = 2 filterset_class = AufgabenFilter # nur datensätze anzeigen, für die der User berechtigt ist. def get_queryset(self): queryset = super().get_queryset().filter(ersteller=self.request.user) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = AufgabenFilter(self.request.GET, queryset=self.get_queryset()) context['number_results'] = context['filter'].qs.count() return context ''' Leider werden alle Projekte angezeigt. Auch die, die andere User angelegt haben. aus models.py: ''' from django.db import models from django.contrib.auth.models import User from home.models import Projekt from datetime import datetime STATUS = ((0, "erledigt"), (1, "offen"), (2, "nachverfolgen"), (3, "ruht")) class Aufgaben(models.Model): datum = models.DateField(default=datetime.now) schlagwort = models.CharField(max_length=255, null=True, blank=True) aufgabe = models.CharField(max_length=255) anmerkung = models.TextField(null=True, blank=True) frist = models.DateField(null=True, blank=True) aufgabenstatus = models.IntegerField(choices=STATUS, default=1) erstellt_am = models.DateTimeField(auto_now_add=True) ersteller = models.ForeignKey(User, on_delete=models.CASCADE) projektbezug = models.ForeignKey(Projekt, on_delete=models.CASCADE) class Meta: ordering = ['projektbezug','datum'] def __str__(self): return str(self.aufgabe) + ' im Projekt: ' + str(self.projektbezug) ''' Wie kann ich die queryset filtern, so dass nur die Projekte des berechtigten Users zu sehen sind? Gruß Michael -
Can I create django-like auth app using FastAPI?
As I understand FastAPI is good for building APIs. However I was wondering, will I be able to create a Django-like web-app, say e-commerce app with accounts and cart, using FastAPI. I glanced at docs and couldn't find any kind of auth features, login/logout/signup, Forms validating that input etc. Is that available from the box or there are some libraries? Does it even make sense or it is better to use Django/flask? -
How to upload pdf file from React js to Django rest framework
I am trying to upload a file on the frontend in React to each user from React js, display them to the users in href and save into django rest framework. How can I do it? the code: export default function UserDetails() { const { id } = useParams(); const navigate = useNavigate(); const [addFile, setAddFile] = useState(null) const addUserFile = async () => { let fromField = new FormData() if (addFile !== null) { fromField.append('user_document', addFile) } await axios({ method: 'PUT', url: `http://localhost:8000/api/document/${id}/`, data: fromField }).then((response) => { console.log(response.data); navigate.push('/') }) } const [file, setFile] = useState([]) const getFile = async () => { const { data } = await axios.get(`http://localhost:8000/api/document/${id}/`) console.log(data) setFile(data) useEffect(() => { getFile(); }, []) return ( <div> <input type='file' multiple className='from-control from-control-lg' name='user_document' onChange={(e) => setAddFile(e.target.files[0])} /> <Button variant="contained" component="span" size="small" onClick={addUserFile} >Upload</Button> <a href={file.user_document}>cert-NSC-2022-South-p001-Advisor.pdf</a> </div> ) } } Thank you in advance. -
Django format change required in the session_data
My Django authentication code looks like below: @api_view(["POST"]) @authentication_classes((BasicAuthentication,)) @permission_classes((IsAuthenticated,)) def api_login(request): username = request.user.username request.session["username"] = username password = request.user.password request.session["password"] = password When I decode the session from the django_session table it gives the p output {"username":"john","password":"john123","member_id":1} But I need the decoded output as below: {'_auth_user_id': '1', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': 'baedbd0e1a2a7eb00d588384391f4aaa7fa0e14a12b6afe607f1xxxxxxxxx', '_session_expiry': 1209600} I use this API from the ReactJS front end. what changes should I do to the code to achieve the format change? -
CONTACT FORM SITE WITH DJANGO DONT SEND
I finished the form but there is a problem on sending it, when I throw an error. thank you for helping me TypeError at /envoyermail/ envoyermail() got an unexpected keyword argument 'fail_silently' Request Method: POST Request URL: http://127.0.0.1:8000/envoyermail/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: envoyermail() got an unexpected keyword argument 'fail_silently' Exception Location: C:\Users\OUE\Desktop\pcibenin\App\views.py, line 47, in envoyermail from django.urls import reverse from django.shortcuts import render from django.core.mail import send_mail from django.views.generic import TemplateView from django.http import HttpResponse from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings def index(request): return render(request, "index.html") def qui_sommes_nous(request): return render(request, "qui_sommes_nous.html") def equipe(request): return render(request, "equipe.html") def galerie(request): return render(request, "galerie.html") def avendre(request): return render(request, "avendre.html") def alouer(request): return render(request, "alouer.html") def realisation(request): return render(request, "realisation.html") def contact(request): return render(request, "contact.html") def details_des_appartement(request): return render(request, "details_des_appartement.html") def envoyermail(request): if request.method=="POST": name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('message') envoyermail( name, subject, email, message, 'ouesergegedeon225@mail.com', fail_silently = False,) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') from django.contrib import admin from django.urls import path from App import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('qui_sommes_nous/', views.qui_sommes_nous, name='qui_sommes_nous'), path('equipe/', views.equipe, name='equipe'), … -
List all groups and parent group of an instance
I have a model Group that has a Foreign key to itself (so a group can have a parent group). It also has a m2m to Establishment. class Group(AbstractBusiness): parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='children' ) establishments = models.ManyToManyField(Establishment, related_name='groups', blank=True) I'd like to have a list containing all the group ids linked to the establishments + the parent group id of those groups and then so on if they keep having a parent id (if this makes any sence). I've tried something like this, overwriting my initial for loop but this doesn't work. groups = models.Establishment.objects.get(number=establishment_id).groups.all() group_ids = [] for group in groups: group_ids.append(group.id) if group.parent: groups = list(chain(groups, models.Group.objects.filter(id=group.parent.id))) You guys have any clues? -
How to make a model not available on sertain dates and hours in Django?
So, I'm creating a room renting project. The renting is not for a whole day, it's only for 2 hours. I'm gonna have several renting companies each having several rooms for rent with diffrent capacity. So, my question is, if a room is rented on lets say 25/03/2022 20:00(so its gonna be unvailable until 22:00, and also unavailable 2 hours prior), I want the room to be still visible on the site, because someone maybe will want to rent it on diffrent day or the same day in diffrent hour. How to make this exact room unavailable only on this date and this hours? If I make is_available row in the model its gonna switch to False whenever someone rent it, but I want it to be available for all the other days and hours. Here are the models: class Owner(models.Model): name = models.CharField(max_length=100) address = models.TextField() phone = models.PositiveIntegerField() class Room(models.Model): number = models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) capacity = models.PositiveIntegerField() is_available = models.BooleanField(default=True) class reservation(models.Model): room_number = models.ForeignKey(Room) guest_name = models.CharField(max_length=200) guests = models.PositiveIntegerField() date_reserved = models.DateTimeField() -
Server responded with a status 404 (Bad Request) - Django
I am working with Django and React. I created a basic API of the Todo list in Django. At the same time, working in the frontend part. When I am trying to add new todo, I get the error of "Server responded with a status 404 (Bad Request). I am getting all the todos that is already in the API. But I am not able to add more. My App.js import React, { useEffect, useState } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import { ListGroup } from "react-bootstrap"; import "./App.css"; import axios from "axios"; import { Button, Modal, Form } from "react-bootstrap"; import { baseURL } from "./api"; function App() { const initialListState = { id: null, title: "", description: "", completed: false, }; const [todos, setTodos] = useState([]); const [show, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const [values, setValues] = useState([initialListState]); const changeHandler = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const submitData = () => { let Data = { id: values.id, title: values.title, description: values.description, completed: false, }; axios.post(baseURL, Data).then((response) => { setTodos({ id: response.data.id, title: response.data.title, description: response.data.description, completed: response.data.completed, … -
running django project on a other machine, giving error
I would like to run my django project on a other machine. When running python3 manage.py runserver i get the error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/lib/python3/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/lib/python3/dist-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/lib/python3/dist-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) … -
Django form not displaying in Bootstrap 5 Modal pop-up window
Problem I'm trying to transfer my current form on a new page to a Modal window that appears on the current page but I can't get the form fields to appear. I have thoughts that it may be due to my urls or the view that worked previously doesn't work with a Modal pop-up. Views class AssetView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request, **kwargs): form_a = AssetForm(prefix='form_a') return render(request, self.template_name, { 'form_a': form_a }) def post(self, request): form_a = AssetForm(request.POST, prefix='form_a') if form_a.is_valid(): post = form_a.save(commit=False) post.user = request.user post.save() return redirect('dashboard') args = { 'form_a': form_a } return render(request, self.template_name, args) HTML <!-- Button trigger modal --> <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal"> Add Asset </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="post"> {% csrf_token %} {{ form_a.as_p }} <button class="btn btn-outline-success btn-sm">Confirm</button> </form> <a href="/coinprices/my-dashboard"> <button class="btn btn btn-outline-dark btn-sm">Dashboard</button> </a> </div> </div> </div> </div> URLS urlpatterns = [ path('my-dashboard/', get_asset_price, name='dashboard'), path('my-dashboard/', AssetView.as_view(template_name='coinprices/my-dashboard.html'), name='asset'), ] -
Import "project4.app4.models" could not be resolved
I made two projects in django, project4 and project5 and then made two apps app4 and app5 respectively. Now I want to import models of project4 in project5. I add 'project4.app4' in settings.py file of project5 and I add this line sys.path.append('E:\Internship\Djangoenv\project4') in wsgi.py file of project5. Now I am importing that model by writing 'from project4.app4.models import Hero (my model class is Hero) then it is showing error "Import "project4.app4.models" could not be resolved". admin.py of project5[wsgi.py of project5settings.py of project5 -
Url Formation with multiple urls in django
mysite.urls file: urlpatterns = [ path('admin/', admin.site.urls), path('' , include('store.urls')), path('', include('blog.urls')), path('/wishlist/', include('wishlist.urls')), ] wishlist.urls file: urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', WishlistView.as_view(), name='wishlist'), url(r'^add/$', WishlistAddView.as_view(), name='wishlist_add'), url(r'^clear/$', WishlistClearView.as_view(), name='wishlist_clear'), url(r'^(?P<pk>\d+)/remove/$', WishlistRemoveView.as_view(), name='wishlist_remove'), url(r'^login$', auth_views.LoginView.as_view(template_name='accounts/login.html')), ] wishlist and urls dont combine to create a page not found error. -
Can we update a value after it has been referenced as a foreign key in django?
I have two tables: class LocationType(models.Model): location_type = models.CharField(max_length=120, unique=True) comment = models.TextField(null=True, blank=True) def __str__(self): return self.location_type class Location(models.Model): location = models.CharField(max_length=100, unique=True) location_type = models.ForeignKey(LocationType, to_field="location_type", on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) def __str__(self): return self.location and I have created a location_type 'PLANT' and then referenced it while creating a location "GUJRAT". location_type1 = LocationType.objects.create(location_type="PLANT") location1 = Location.objects.create(location="GUJRAT", location_type=location_type1) Now after creating these two entries I want to change location_types value from "PLANT" to "FACTORIES". location_type1.location_type = "FACTORIES" location_type1.save() But I am getting below error: Traceback (most recent call last): File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/jayantseth/Projects/ip_manager/IpManagerBackend/ipmanager/models.py", line 58, in save super(LocationType, self).save(*args, **kwargs) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 970, in _save_table updated = self._do_update( File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1034, in _do_update return filtered._update(values) > 0 File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/query.py", line 885, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1783, in execute_sql cursor = super().execute_sql(result_type) File "/home/jayantseth/Projects/ip_manager/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", … -
Digital ocean droplet is only showing the default nginx page when connected with a namecheap domain
I'm using a Django Digital Ocean droplet to run a website where I recently tried connecting the IP address of the droplet to a namecheap domain name, but when I connected them it only showed this on the domain: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. However, the website was working as intended on the IP address, can anyone tell me how to fix this? my abbreviated /etc/nginx/sites-available/default file server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name sanskarhandicrafts.com; location / { try_files $uri $uri/ =404; } } -
Url Pattern giving me a url mismatch error
url(r'^(?P<pk>\d+)/remove/$', WishlistRemoveView.as_view(), name='wishlist_remove'), <form action="{% url 'wishlist_remove' pk=item.wishlistitem_set.all.0.pk %}" method="post"> {% csrf_token %} <input type="submit" value="{% trans 'Remove' %}"> </form> When i click on the remove button I get the following error:- NoReverseMatch at /product/7/ Reverse for 'wishlist_remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['(?P<pk>\\d+)/remove/$'] Something is wrong -
No indentations for the options in the select box in an inlined table (Django MPTT)
I created many-to-many relationship with the tables "Category", "Product" and "CategoryProduct" which is the middle table between "Category" and "Product": "models.py": from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) class MPTTMeta: order_insertion_by = ["name"] def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class CategoryProduct(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: unique_together = [['category', 'product']] Then, I registered "Category" and "Product" inlined "CategoryProduct" to: "admin.py": from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Category, Product, CategoryProduct admin.site.register(Category, MPTTModelAdmin) class CategoryProductInline(admin.TabularInline): model = CategoryProduct @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [CategoryProductInline] Then, I added some categories and as you can see, the options in the select box of "Parent" have indentations: But when I tried to add a product, as you can see, the options in the select box of "Category" don't have indentations: Is it possible to give indentations to the options in the select box of "Category"? If possible, how can I do this? -
Django : Create a Form for a dropdown list depending of ID User and Models
I am Newbee in Django. I want to create a Form for a dropdown list. The Dropdown list should show different choices depending on User and the models. I did something directly on the view.py that displays the choices without using a Form from Django and it does not store it. So it is not ideal for what I want to do after the POST. Here are my Models.py class TblAadJntGroup(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. id_aadgroup = models.IntegerField(db_column='ID_AADGroup', blank=True, null=True) # Field name made lowercase. id_aaduser = models.IntegerField(db_column='ID_AADUser', blank=True, null=True) # Field name made lowercase. createdon = models.DateTimeField(db_column='CreatedOn', blank=True, null=True) # Field name made lowercase. createdby = models.CharField(db_column='CreatedBy', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_AAD_jnt_Group' class TblAadGroups(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. idcustomer = models.IntegerField(db_column='IDCustomer', blank=True, null=True) # Field name made lowercase. displayname = models.CharField(db_column='DisplayName', max_length=255, blank=True, null=True) # Field name made lowercase. timestampm = models.DateTimeField(db_column='TimeStampm', blank=True, null=True) # Field name made lowercase. username = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'tbl_AAD_Groups' So to get the data that I want to display in the dropdown. I start to … -
Django migrations circular dependency what is the best practice?
I would like to know the best practice to handle CircularDependency when migrating apps. Our CRM has two Apps with several model fields depending on each other. We need to reconstruct the database everyday and this lead us to regenerate and apply migrations everyday. In our code the foreign keys are referenced with : model_name = models.ForeignKey('app.model', ...) So no issues at runtime. But at night, when we regenerate and apply the migrations, we made a migrate script that basically swaps the foreign keys as IntegerField to prevent CircularDependencyError and reswaps them after the depencies are solved. Is there a better way to do this ? -
How to get model objects with AJAX?
I have a Customer model in my Django application. New users are constantly being added to this model in the background and I want to list these customers dynamically with AJAX. But I cannot figure it out. How can I do that? def ajax_view(request): obj = Customer.objects.filter(company=request.user.company) customers = [] for customer in obj: customers.append(customer) data = { "obj": customers } return JsonResponse(data) html <h3 id="status"></h3> <script> var refresh = setInterval(function() {$.ajax({ url: "{% url 'user:ajax_customer' %}", type: "GET", dataType: 'json', success: function (data) { if (data) { console.log(data); console.log(status); document.getElementById("status").innerHTML = data.obj; } } });}, 1000); </script> I try to do that but It gives an error: TypeError: Object of type Customer is not JSON serializable -
Django setUpTestData does not deepcopy related files
I want to use django setUpTestData to prepare some heavy data shared between multiples unit tests. Instances of my Model are created with some file fields. However, from one test to another, file contents are not renewed, it has side effects between my tests here is a minimalist example : models.py from django.db import models class MyModel(models.Model): my_file = models.FileField(upload_to="tests/") test.py from django.core.files.base import ContentFile from django.test import TestCase from core.models import MyModel class Test(TestCase): @classmethod def setUpTestData(cls): cls.instance = MyModel() cls.instance.my_file.save("file.txt", ContentFile("Hello from setUpTestData")) def test_a(self): with open(self.instance.my_file.path, "r") as fp: self.assertEqual(fp.read(), "Hello from setUpTestData") self.instance.my_file.save("file.txt", ContentFile("Modified data")) def test_b(self): with open(self.instance.my_file.path, "r") as fp: self.assertEqual(fp.read(), "Hello from setUpTestData") self.instance.my_file.save("file.txt", ContentFile("Modified data")) Running any of the two test alone works, however running one after the other one fails: AssertionError: 'Modified datatUpTestData' != 'Hello from setUpTestData' - Modified datatUpTestData + Hello from setUpTestData How to ensure that file are correctly reset? Am I concerned by theses lines from the documentation ? Objects assigned to class attributes in setUpTestData() must support creating deep copies with copy.deepcopy() I feel like fileField should be handled by default by Django but it doesn't work, what should I do? Should I try to override __deepcopy__ … -
Custom command line parameter for testing
I found a way to pass a custom parameter to Django testing from command line: class TestRunner(DiscoverRunner): @classmethod def add_arguments(cls, parser): DiscoverRunner.add_arguments(parser) parser.add_argument('-b', '--browser', help='Browser test') But how can I get this parameter value inside my TestCase ? -
Why in unit test object's field doesn't change in Django
I don't understand why my test doesn't work. I have a page with product. There is a form with button 'Buy product'. After pushing this button, if a client have enough money, the item will bought and the ammount of money in the account will change. But in my test the ammount of money will be the same after buying a product, although the object(purchased item) will be created. Purchased item model: class BoughtItem(models.Model): name = models.CharField(max_length=100, verbose_name='Название товара или акции', blank=True) price = models.IntegerField(verbose_name='Цена', blank=True) created_at = models.DateTimeField(auto_now_add=True) Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.IntegerField(default=0) form: class BuyForm(forms.ModelForm): class Meta: model = BoughtItem fields = ('name',) widgets = {'name': forms.HiddenInput()} view: class ItemDetailView(generic.DetailView): model = Item template_name = 'item_detail.html' context_object_name = 'item' def get_object(self, queryset=None): return get_object_or_404(Item, pk=self.kwargs.get('pk')) def post(self, request, *args, **kwargs): buy_form = BuyForm(request.POST) if buy_form.is_valid(): purchase = buy_form.save(commit=False) item = self.get_object() user = Profile.objects.get(user__username=request.user.username) if user.money >= item.price: sum_difference = user.money - item.price user.money = sum_difference user.save() purchase.name = item.name purchase.price = item.price purchase.save() return HttpResponseRedirect(reverse('account', kwargs={'username': request.user.username})) else: return HttpResponseRedirect(reverse('purchase_error')) else: return render(request, 'item_detail.html', context={'buy_form': buy_form, 'object': self.get_object()}) urls: urlpatterns = [ path('shop_list/', ShopListView.as_view(), name='shop_list'), path('<str:name>', ItemListView.as_view(), name='shop_detail'), path('item/<int:pk>', ItemDetailView.as_view(), name='item_detail'), … -
define a Generic, non serialising field in django rest serializers
This is just a layout of my serializer class SerializerA(serializers.ModelSerializer): field_a = serializers.SerializerMethodField() field_b = serializers.SerializerMethodField() field_c = serializers.SerializerMethodField() field_d = serializers.SerializerMethodField() class Meta: model = TestModel fields = ("field_a", "field_b", "field_c", "field_d", "name", "designation") def get_field_a(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_a = "some ORM query related to temp and TestModel model" return field_a def get_field_b(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_b = "some ORM query related to temp and TestModel model" return field_b def get_field_c(self, obj): temp = TempUserModel.objects.get(pk=obj.uuid) field_c = "some ORM query related to temp and TestModel model" return field_c def get_field_d(self, obj): field_d = "some ORM query related to TestModel model" return field_d Here temp = TempuserModel.objects.get(pk=obj.uuid) is same in 3 out of 4 of the class methods. So is there any way that I can define it once somewhere in a serializer loop and use it without doing the same ORM query again and again? -
Count the courses that a particular instructor has created
I am building an elearning platform where an instructor can create courses. I am facing a problem when displaying the number of courses that a particular instructor has. I wanted to count the number of courses that the instructor has created. However, my code displays all the courses that are in the database. Please help. index.html <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-info shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Courses </div> <div class="row no-gutters align-items-center"> <div class="col-auto"> <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">{{ course_count }}</div> </div> </div> </div> <div class="col-auto"> <i class="fas fa-clipboard-list fa-2x text-gray-300"></i> </div> </div> </div> </div> views.py def instructorDashboard(request): customer = Users.objects.all() course = Course.objects.all() course_count = course.count() context = {'customer':customer, 'course_count': course_count} return render(request, 'instructor_dashboard/index.html', context)