Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django Action to Populate Database: Show Drop Down Action Menu Even for Empty DB
Using django, I have a startup script that loads static data into the database. Currently I call it via a url, but thought it be nice if it be done from within the admin menu of the respective table. I found the option to use admin actions for this, but allas, they do not show up if the database is empty. Any idea how to still show the admin actions dropdown menu? -
create pivot table using django and pivottable.js
I hope you can help me create pivot tables, the same as the one in the picture from the Odoo program, using django, js and pivot table. enter image description here [enter image description here]) I tried to write some codes but did not reach any results -
SMTP.starttls() got an unexpected keyword argument 'keyfile'
I'm trying to send email with this code: send_mail( subject='Restore password', message='Restore password for ' + email, from_email=os.environ.get('GMAIL_EMAIL', ''), html_message=html_message, recipient_list=[email] ) And having this error SMTP.starttls() got an unexpected keyword argument 'keyfile' My python version is 3.12.0 My Django version is 4.0.1 -
Place bid implementation not working on my django app
I have really tried different methods in order to implement a place bid functionality, but all my efforts were futile. I don't what's wrong with the code. Here's my code: views.py def place_bid(request): if request.method == "POST": #data = json.loads(request.body) #create and save the bid value item_id = request.POST("item_id") listing_item_id = get_object_or_404(Listing, pk=item_id) bid_value = request.POST("bid_value") Bids.objects.create(bidder=request.user, bid_price=bid_value, listing_id=listing_item_id) listing_item_id.initial_price = bid_value listing_item_id.save() return render(request, "auctions/listing_view.html", { "price": listing_item_id, "message": "Your bid has been placed successfully" }) models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Bids(models.Model): bidder = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) listing_id = models.ForeignKey(Listing, null=True, on_delete=models.CASCADE) def __str__(self): return self.bid_price templates <div class="right"> <h3>{{ listing.product_name }}</h3> <h4>${{ price.initial_price }}</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id … -
FileNotFoundError: [Errno 2] No such file or directory in celery container while my django application container exists
I am developing a django application in which I have to manipulate excel files. I have two containers: one for my main django application and another for celery where I process my files. These two containers have the same context and share the same environment variables. here is the view where is my problem: def file_recovery(request): reponse = {} request.method == "POST": extensions = ["xls","xlsx"] form = UploadExcelMeterFile(request.POST,request.FILES) if form.is_valid(): excel_file = request.FILES["excel_file"] extension = request.FILES["excel_file"].name.split(".")[-1] if not extension in extensions: ... else: obj_file = XSLFileObjects.objects.create(file=excel_file) # I create an file objects my_task.apply_async(args=[obj_file.id]) # I send the id of that objects to my task to get the file directory ... else: ... else: ... in my_task.py @shared_task def ajouter_compteur_depuis_excel(id): from elec_meter.models import XLSFileObject obj_file = XLSFileObject.objects.get(id=id) file = obj_file.file ... In my task I try to recover the file and do the processing. This file exists in the django app container but does not exist in celery. I receive FileNotFoundError: [Errno 2] No such file or directory When I try to create another object, I notice that the previous file which does not exist appears in celery. docker-compose.yml version: '3' services: app: container_name: ozangue build: context: . command: > python … -
How to generate a user-specific PDF in Django based on user ID?
I'm ivan, a junior-level Computer Science student and aspiring developer. I'm currently delving into web development using Django. As part of my learning journey, I'm working on a project where I need to generate a customized PDF for each user, identified by their unique user ID. My current experience is at the junior trainer level, and while I'm familiar with the basics of Django, I'm struggling a bit with the specific implementation of PDF generation using a particular library. I would like to seek the community's assistance in understanding how the [library name] library works in Django and how I can apply it to create these user-specific PDFs based on user ID. I appreciate any guidance, code examples, or resources that can help me overcome this hurdle.the crud works perfectly the pdf it generates comes out with: No reservations found in the system. views.py from django.http import FileResponse from reportlab.pdfgen import canvas from .pdfGen import genpdf from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Reserva from .forms import ReservaForm def agregarReserva(request): form=ReservaForm() if request.method=='POST': form=ReservaForm(request.POST, request.FILES) if form.is_valid(): form.save() form=ReservaForm() #para que no duplique los datos en la bd return redirect('/') reservas=Reserva.objects.all() data={'form':form,'reservas':reservas} return render(request, 'templatesApp/agregar.html', … -
axiosInstance raise error ->( Invalid token specified) -> after update -> user profile information ? why ? please solve it
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE. Consider - axiosInstance.js: import jwt_decode from 'jwt-decode'; import dayjs from 'dayjs'; import axios from 'axios'; import { AxiosRequestConfig } from 'axios'; import {updateAccessToken} from '../actions/userActions'; const baseURL = 'http://127.0.0.1:8000'; export const axiosInstance = (userInfo , dispatch) => { const instance = axios.create({ baseURL : baseURL, headers : { 'Content-Type': 'application/json', Authorization:`Bearer ${userInfo?.access}`, } }); instance.interceptors.request.use(async (req)=> { const user = jwt_decode(userInfo.access); const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000; if (!(isExpired)) { return req } const response = await axios.post( '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh}, ); dispatch(updateAccessToken(response.data)) req.headers.Authorization = `Bearer ${response.data.access}`; return req; }); return instance } consider - userActions.js - updateUserProfileAction : export const updateUserProfileAction = (user) => async (dispatch, getState) => { try { dispatch({ // USER UPDATE PROFILE REQUEST type: USER_UPDATE_PROFILE_REQUEST, }); const {userLogin: {userInfo}} = getState(); //GET STATE FROM STORE BY KEY `USER_LOGIN` const authRequestAxios = axiosInstance(userInfo,dispatch) const {data} = await authRequestAxios.put('http://127.0.0.1:8000/api/v1/users/profile/update/', user) dispatch({ // USER UPDATE PROFILE SUCCESS type: USER_UPDATE_PROFILE_SUCCESS, payload: data, }); dispatch({ //USER LOGIN SUCCESS type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem('userInfo', JSON.stringify(data)); } catch (error) { dispatch({ // USER UPDATE PROFILE FAILED type: USER_UPDATE_PROFILE_FAILED, payload: error.response … -
Trouble Generating Publicly Accessible URL for Uploaded Images in Django App
I'm currently working on a Django application hosted locally that accepts user-uploaded images. The images are stored successfully, but I'm facing challenges in generating a publicly accessible URL for these uploaded images. The ultimate goal is to feed this URL into the replicate.com API endpoint. Here's a brief overview of my process: User uploads an image via the Django app. The image is stored locally on the server. Need to generate a publicly accessible URL for the uploaded image. views.py: from django.shortcuts import render import os import replicate from .forms import ImageUploadForm def index(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image_instance = request.FILES['image'] file_url = handle_uploaded_file(image_instance) response = run_replicate(file_url) output_url = response[0] context = {'output_url': output_url} return render(request, 'core/results.html', context) else: form = ImageUploadForm() return render(request, 'core/index.html', {'form': form}) def handle_uploaded_file(uploaded_file): os.makedirs('images/new', exist_ok=True) file_path = os.path.join('images/new', uploaded_file.name) with open(file_path, 'wb+') as destination: for chunk in uploaded_file.chunks(): destination.write(chunk) file_url = file_path.replace("\\", "/") file_url = "https://replit.com/@mashudhassandev/ChatgptImgGen#" + file_url return file_url def run_replicate(file_content): model_id = 'jagilley/controlnet-canny:aff48af9c68d162388d230a2ab003f68d2638d88307bdaf1c2f1ac95079c9613' response = replicate.run( model_id, input={ 'image': open(file_content, "rb"), 'prompt': 'hyperrealistic portrait, photograph, real person' }) return response How can I effectively create a publicly accessible URL for the uploaded images in Django? Any … -
No module name pwd
**I am trying to connect Mysql to Django ** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djsql', 'USER':'root', 'PASSWORD' : 'root', 'HOST':'127.0.0.1', 'PORT':'3306', }} tried running : pip install msqlclient and python manage.py migrate Getting Error: × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\Dell\AppData\Local\Temp\pip-install-u0zn06ml\migrate_37874a5e96fe48ffb9d7bebe813702bc\setup.py", line 26, in <module> import migrate File "C:\Users\Dell\AppData\Local\Temp\pip-install-u0zn06ml\migrate_37874a5e96fe48ffb9d7bebe813702bc\migrate.py", line 18, in <module> import pwd ModuleNotFoundError: No module named 'pwd' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed not able to find the error pwd!! -
Foreign key constraint failure in Django's django_admin_log table IntegrityError 1452 AbstractBaseUser
I'm encountering an error related to a foreign key constraint while working on a Django project. When attempting to add or update records in the django_admin_log table, the following error occurs: here is my model.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, Permission,Group from django.db import models from django.core.validators import EmailValidator from django.core.exceptions import ValidationError import re from phonenumber_field.modelfields import PhoneNumberField from apps.location.models import City from django.utils import timezone class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class UserType(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name def validate_password_strength(value): if not re.match(r'^(?=.*[A-Z])(?=.*[!@#$%^&*()_+{}|:;<>,.?/~]).{8,}$', value): raise ValidationError("Password must meet the specified requirements.") class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, validators=[EmailValidator(message="Enter a valid email address.")]) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) address = models.CharField(max_length=50)# Add the address field is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) user_type = models.ForeignKey(UserType, on_delete=models.CASCADE, null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) profile_image … -
Receiving data in the serializer from a related model by relation_name in DRF
I have 2 models class News(models.Model) title = models.CharField(max_length=100, null=False) text = models.TextField(null=False) class NewsImages(models.Model) news = models.ForeignKey( to=News, null=True, on_delete=models.CASCADE, related_name='images' ) image = models.FileField( upload_to="news/img/%Y/%m/%d", null=False, ) I need serialize model with related images. I try do it use nested serializers: class NewsImageSerializer(serializers.ModelSerializer): image = Base64ImageField() class Meta: model = NewsImage fields = '__all__' class NewsSerializer(serializers.ModelSerializer): images = NewsImageSerializer(many=True) class Meta: model = News fields = '__all__' But got error: AttributeError at /api/v1/news/ Got AttributeError when attempting to get a value for field `images` on serializer `NewsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `News` instance. Original exception text was: 'News' object has no attribute 'images'. As I understand from similar questions, it should work exactly like this via related_name. Why doesn't this work for me, what am I doing wrong? -
Can I add a global query parameter to all methods on all Viewset endpoints in Django Rest Framework?
For some purpose I need to add a query parameter to all DRF API viewset method calls and I need to be able to supply from Swagger. In FastAPI it is easily done with a dependency injection on global level like this: async def code(code: Code = None): """Dependency to add code query parameter to all endpoints""" pass fastapi_app = FastAPI(docs_url=None, title="SAF2 API", dependencies=[Depends(code)]) But I have been struggling with custom filters and middleware in Django, but I am not getting it to work. Filters seem to only apply to GET methods and I don't know a lot about middleware to write one myself. I can put it manually on all endpoints with decorators and stuff but that is all very ugly. My viewset looks like this: class CustomerViewSet(viewsets.ModelViewSet): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = CustomerSerializer queryset = Customer.objects.all() filter_backends = [ filters.SearchFilter, filters.OrderingFilter, django_filters.rest_framework.DjangoFilterBackend, ] search_fields = ["full_name", "name", "status"] filterset_fields = ["full_name", "name", "status"] Any help or reference to documentation would be appreciated greatly! A nice bonus would be to add custom headers to all requests. -
Multiple Django projects independent from one another - DB migrations writing to wrong DB
I have been working with Django for about three years now and have developed a couple business grade apps which are deployed and doing great. The other day, I created a new project with a new database, etc. I built out the initial models and migrated them to the proper database. However, subsequent migrations are going to a database I built for another app entirely. The two databases aren't on the same host, don't have similar names - they have nothing in common. How is this possible? Is there some connection cache I need to clear? I haven't even had any of the other projects open or running locally- nothing. I'm baffled. -
Implementing Kerberos and LDAP in Django
firstly, i'm very new to Django. I have developed a Django app that includes a ticket system. Users should only see their own tickets. Now this self service system should be connected to the Microsoft account to enable a single sign on. To do this, the Django app must first be connected to Kerberos and then authenticated using LDAP. However, after extensive searching I cannot find any comprehensible documentation that explains the procedure. That's why I'm turning to you with the hope that someone can help me. Many thanks in advance Pablo I tried using the Dkango Documentation and various other "Docs" which were either outdated or incomplete(like the official django documentation) also other helpful threads in here are outdated. -
Custom django model field to upload a file to an external file/cloud host
I want to have a custom model field for file upload to an external hoster, which I can just add to a model. It is important, that I don`t have to edit the admin form, to be form independent. File should not be saved in django's media system. It should directly be uploaded to a file hoster. The hoster than returns file id. This id should be saved to the field. I managed to do this with the following code. But this can`t the best solution. It is too much and to strange code. Let's not talk about dropbox or the dropbox api, it`s just an example. Could be every other cloud/file hoster. My question is about such fields with file upload in django, not about the hoster. I know that there is django-storages and similar packages, but I do not want to use it for reasons. What would be a better solution? class DropboxFileIdWidget(AdminFileWidget): def value_from_datadict(self, data, files, name): uploaded_file = super().value_from_datadict(data, files, name) if uploaded_file: # Determine the path for the temporary file temp_dir = tempfile.gettempdir() temp_file_path = os.path.join(temp_dir, uploaded_file.name) # Check if a file with the same name already exists, and delete it if os.path.exists(temp_file_path): os.remove(temp_file_path) # … -
I can't take value from dictionary in my django project
I have the dictionary shown below: duties = { 1 : 'Crew', 2 : 'Cast', 3 : 'Director', 4 : 'Writers', } `{% with index=person.duty_type %} {{duties.index}} {% endwith %}` The spesific value i choose from dictionary doesn't display in site. I also have tried to write it like this: {{duties.person.duty_type}} None of the solutions i have tried worked -
Django: websockets connection issues
I am having issues making websockets connection in my django application. here is the error message WebSocket connection to 'ws://127.0.0.1:8000/chat/' failed: my javascript file let loc = window.location let wsStart = 'ws://' if(loc.protocol === 'https:') { wsStart = 'wss://' } let endpoint = wsStart + window.location.host + loc.pathname; var socket = new WebSocket(endpoint) socket.onopen = async function(e){ console.log('open', e) } socket.onmessage = async function(e){ console.log('message', e) } routing.py websocket_urlpatterns = [ path('ws/chat/', consumers.ChatConsumer.as_asgi()), ] -
Django-simple-history Records
While using simple_history , it creates multiple history records when more than one field is updated in modal. How to Change above Behaviour in order to that it creates only one history record when more than one field is changed in one go ? -
Django channels' __init__ gets unexpected kwarg "password" -> no websocket connection
This is the condensed user model. I highly assume it is some incompatibility issue with Djangos AbstractUser Class: class CustomUser(AbstractUser, PermissionsMixin, TimeRegistryBaseModel): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) username = None email = models.EmailField(unique=True) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True) verified_status = models.BooleanField(default=False) bio = models.TextField(null=True, blank=True) location = models.CharField(max_length=50, null=True, blank=True) birthdate = models.DateField(null=True, blank=True) marital_status = models.ForeignKey(MaritalStatus, on_delete=models.CASCADE, null=True, blank=True) avatar = models.ImageField( upload_to="avatars/", null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS: List[str] = [] # TODO: think thoroughly what we actually-required when creating a user And this is the error message: Exception inside application: __init__() got an unexpected keyword argument 'password' Traceback (most recent call last): File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/routing.py", line 116, in __call__ return await application( File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/dci-student/Desktop/DCIstuff/Projects/PlayPal/.venv/lib/python3.8/site-packages/channels/consumer.py", line … -
In Wagtail, how to deal with singleton pages?
I am developing a wagtail website. There are some pages that have specific design that will exist on exactly one page (e.g. "who are we" with a list of pictures and bio, "how does it work" which integrates some very specific charts in a very specific way, the home page…). Currently, for those pages, I am creating one model/template per page, but it's not perfect: The page has no dynamic content and the url can be chosen ahead of time. I could use a simple static html asset, it won't have the right url (it would be something like domain.com/static/who-are-we.html instead of domain.com/who-are-we) Non-technical editors are confused (why can I create more than 1 "who are we" page?) Since the page is a singleton, referring to it in other pages should be easy. But currently I have to add a field to other pages model and choose the page every time. That's a bummer since I know that there exist one and only one page "who are we", so I'd like to directly integrate it in the template and skip a field in my models. Is there an idiomatic way to deal with this situation in Wagtail? -
increase/decrease quantity as well as change database and decrease the quantity from total stocks
** I want to add quantity feature in my form and model in which I want to update the quantity from the total quantity in the stocks and quantity will be decrease if we add quantity in of any product, ... suppose we have 50 t-shirt stock and customer added 5 so the total quantity will be 45 in stocks. ** models.py # models.py from collections.abc import Collection from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15) address = models.CharField(max_length=255) def clean_mobile(self): mobile=self.mobile if len(str(mobile))!= 10: raise ValidationError("invalid mobile number") return mobile class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') def __str__(self): return self.product_name views.py @login_required def supplier_dashboard(request): if request.method=='POST': product_name=request.POST.get('product_name') product_price=request.POST.get('product_price') image=request.FILES.get('image') data=Supplier.objects.create(user=request.user,product_name=product_name,product_price=product_price,image=image) data.save() supplier=Supplier.objects.filter(user=request.user) else: supplier=Supplier.objects.filter(user=request.user) return render(request, 'enroll/supplier_dashboard.html',{'suppliers':supplier}) supplier_dashboard.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <title>supplier_dashboard</title> </head> <body> <div> <h1><u>WELCOME TO YOUR PROFILE</u></h1> <font color="red" size="8">{{request.user.username}} </font> <div> {%if messages%} {% for message in messages%} <div id="message_container" class="alert alert-warning alert-dismissible fade show text-center" role="alert"> **{{message}}** </div> {%endfor%} … -
what will happend if a user submits the old form without refreshing the page after I've made changes to the Django form
I have made some changes to the form of my Django website, for example: some values of thoes checkbox were changed. A user already opened the form before my changes, and he submited the form after making some changes. What will happened? In my local machine with Django 2.2 and Chrome 116.0.5845.110, the form page was refreshed after I clicked the Save button. Thanks! You can ignore the bellowing cause it could be related with my codes. (The refreshed form is not expected, which contains the new changes but a little different. If I open the url of the form page to a new tab, everything works fine) -
I receive an error running pytest on a query set for a proxy model in django
My User model contains the following choices class Roles(models.TextChoices): ACCOUNT_MANAGER = "ACCOUNT_MANAGER", _("Account Manager") CLIENT_MANAGER = "CLIENT_MANAGER", _("Client Manager") ADMIN = "ADMIN", _("Admin") base_role = Roles.ACCOUNT_MANAGER I have then created a proxy model and manager class ACManager(models.Manager): # Ensures queries on the Account Manager model return only Account Managers def get_queryset(self, *args, **kwargs): results = super().get_queryset(*args, **kwargs) return results.filter(role=User.Roles.ACCOUNT_MANAGER) class AccountManager(User): # This sets the user role to Account Manager during record creation base_role = User.Roles.ACCOUNT_MANAGER objects = ACManager() I have the following test @pytest.mark.django_db def test_ac_manager_get_queryset(): # Test setting user roles role = User.Roles.ACCOUNT_MANAGER user = User.objects.create_user(email="test@example.com", password="password123", role=role) # Create an instance of ACManager manager = ACManager() # Call the get_queryset method queryset = manager.get_queryset() # Assert that only users with the ACCOUNT_MANAGER role are in the queryset assert user in queryset assert queryset.count() == 1 When I run the test I get the following error message django.core.exceptions.FieldError: Cannot resolve keyword 'role' into field. Creating users with the different roles works so I am a bit confused as to why this is happening. Any help on resolving this issue would be appreciated. -
Gradual Disk Usage Increase in Django/OpenLiteSpeed on Ubuntu - Seeking Guidance on Identifying and Resolving the Issue
disk usage increased by 1.57 GB in one month I've recently deployed a Django website using the OpenLiteSpeed Ubuntu image on a Hostinger VPS. Over the period from Oct 14th to Nov 14th, I observed a significant 1.57 GB increase in disk space usage, as indicated in the attached image. I'm puzzled by this unexpected growth, as there haven't been any notable changes or additions to the system during this time. I'm using the following : Python 3.10.12 acme==1.21.0 asgiref==3.7.2 attrs==21.2.0 Automat==20.2.0 Babel==2.8.0 bcrypt==3.2.0 blinker==1.4 certbot==1.21.0 certifi==2023.7.22 chardet==4.0.0 charset-normalizer==3.3.0 click==8.0.3 cloud-init==23.3.1 colorama==0.4.6 command-not-found==0.3 ConfigArgParse==1.5.3 configobj==5.0.6 constantly==15.1.0 crispy-bootstrap5==0.7 cryptography==3.4.8 dbus-python==1.2.18 decorator==4.4.2 distlib==0.3.4 distro==1.7.0 distro-info==1.1+ubuntu0.1 Django==4.2.6 django-ckeditor==6.7.0 django-crispy-forms==2.0 django-js-asset==2.1.0 django-mathfilters==1.0.0 django-robots==6.1 filelock==3.6.0 gunicorn==21.2.0 httplib2==0.20.2 hyperlink==21.0.0 idna==3.4 imageio==2.31.5 imageio-ffmpeg==0.4.9 importlib-metadata==4.6.4 incremental==21.3.0 jeepney==0.7.1 Jinja2==3.0.3 josepy==1.10.0 jsonpatch==1.32 jsonpointer==2.0 jsonschema==3.2.0 keyring==23.5.0 launchpadlib==1.10.16 lazr.restfulclient==0.14.4 lazr.uri==1.0.6 MarkupSafe==2.0.1 more-itertools==8.10.0 moviepy==1.0.3 netifaces==0.11.0 numpy==1.26.0 oauthlib==3.2.0 opencv-contrib-python==4.8.1.78 opencv-python==4.8.1.78 packaging==23.2 parsedatetime==2.6 pexpect==4.8.0 Pillow==10.0.1 platformdirs==2.5.1 proglog==0.1.10 psutil==5.9.5 psycopg2==2.9.9 ptyprocess==0.7.0 pyasn1==0.4.8 pyasn1-modules==0.2.1 PyGObject==3.42.1 PyHamcrest==2.0.2 PyICU==2.8.1 PyJWT==2.3.0 pyOpenSSL==21.0.0 pyparsing==2.4.7 pyRFC3339==1.1 pyrsistent==0.18.1 pyserial==3.5 python-apt==2.4.0+ubuntu2 python-debian==0.1.43+ubuntu1.1 python-magic==0.4.24 pytz==2022.1 PyYAML==5.4.1 requests==2.31.0 requests-toolbelt==0.9.1 SecretStorage==3.3.1 service-identity==18.1.0 six==1.16.0 sos==4.5.6 sqlparse==0.4.4 ssh-import-id==5.11 systemd-python==234 tqdm==4.66.1 Twisted==22.1.0 typing_extensions==4.8.0 tzdata==2023.3 ubuntu-advantage-tools==8001 ufw==0.36.1 unattended-upgrades==0.1 urllib3==2.0.6 uWSGI==2.0.22 virtualenv==20.13.0+ds wadllib==1.3.6 zipp==1.0.0 zope.component==4.3.0 zope.event==4.4 zope.hookable==5.1.0 zope.interface==5.4.0 I'm also using PostgreSQL 14.9 Ubuntu 22.04 with OpenLiteSpeed Django Image OpenLiteSpeed 1.7.18 I … -
How to assign the user making the request to a foreign key field in Django models
I'm currently working on a web app similar to discord. I'm trying to set the user who is sending the request to create the server as the owner of the server so that the only thing he wants to enter is details like - name , icon and description. This is my model for server: class Server(models.Model): name = models.CharField(max_length=30) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="server_owner") creation_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=250, null=True, blank=True) member = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="servers", through='ServerMember') icon = models.FileField( upload_to=server_icon_upload_path, null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): is_new_server = self._state.adding if is_new_server: super().save(*args, **kwargs) try: member_role = Role.objects.create( name="member", server=self ) server_member = ServerMember.objects.create( user=self.owner, server=self) server_member.role.add(member_role) except Exception as e: print(f"Error creating 'member' role: {e}") if self.id: existing = get_object_or_404(Server, id=self.id) if existing.icon and existing.icon != self.icon: # Delete the old icon existing.icon.delete(save=False) super().save(*args, **kwargs) I've tried to override the perform_create function but it didn't work: class ServerCreateView(generics.CreateAPIView): queryset = Server.objects.all() serializer_class = ServerSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user)