Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stepwise procedure to install django,nginx,gunicorn,supervisor and virtualenv on Fedora 38
Steps: NGINX 1.Installed ningx, added a test index page at /etc/nginx/sites.d Added an include /etc/nginx/sites.d/*.conf; in the main nginx conf.d file. It worked out of the box, (I didn't go for any of the sites-available sites-enabled symnliks alternative configurations which never worked and were downright complicated) POSTGRESQL 2. Installed postgresql, created db and owner and granted privs. Now my questions on how to continue: VIRTUALENV: a) I INSTALLED virtualenv, have not CREATED it yet to anywhere nor ACTIVATED it. I read it can be created anywhere, QUESTION: I read creating a webapps dir at the root is ok? b) once I have question 3.a) cleared, next topic: CLONING THE DJANGO APP FROM BITBUCKET I have my django app at bitbucket. QUESTION: do I have to place myself where the test index page is (step 1) to start the cloning from the repository? or do I do it from the webapps dir created at 3a) ? GUNICORN Since gunicorn is a python package, it has to have the virtualenv installed before (unlike postgresql and nginx who are self-contained) Still inside the activated virtualenv, I will install gunicorn. Since the configuration is very specific I will try that first myself. SUPERVISOR 6) … -
Integrating Databricks SQL Connector with Django ORM for CRUD Operations
I am working on a Django project that requires integration with Databricks, and I am currently exploring the use of the databricks-sql-connector Python package for connectivity. However, my concern is that utilizing this package might involve manual SQL query creation for CRUD operations within my Django project. Is there a method available that allows me to establish a connection to the Databricks database while still leveraging Django's ORM capabilities? I would like to achieve a connection similar to the following code snippet: sql.connect( server_hostname=connection_params["hostname"], http_path=connection_params["http_path"], access_token=connection_params["access_token"] ) Additionally, I would like to extract a cursor using the following snippet: connections["default"].cursor() My database settings are configured as follows: DATABASES = { 'default': { 'ENGINE': 'custom_engine_name', 'HOSTNAME': os.getenv('DATABRICKS_HOSTNAME'), 'NOTEBOOK_PATH': os.getenv('DATABRICKS_NOTEBOOK_PATH'), 'ACCESS_TOKEN': os.getenv('DATABRICKS_ACCESS_TOKEN'), } } My expectation is to find a method or solution that allows me to establish a connection to the Databricks database using Django's ORM, avoiding the need for manual SQL queries. If this requires writing a custom adapter, I would appreciate guidance on how to create one that effectively connects Django ORM with the "databricks-sql-connector." -
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2 In given image i want to place 5 points inside the area enter image description here place it evenly like this : enter image description here using python code , assume that i have made circles and we have radius r1 and r2 and sector angle -
How to configure HSTS in django
I need to configure hsts in one of django app. I have read django doc and came to a point that if I set SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True It will set hsts header on all request headers which it didn't Additionally I got another key value SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') That I need to set if my app is behind proxy. I expect that on all of my django api request headers I see that hsts header. -
How to run Huey consumer on Windows IIS
I am working on a Django application which is deployed on a Windows Server using IIS. I want to use Huey to be able to run background tasks e.g. sending of emails and report generation. Celery does not support Windows hence my decision to use Huey. According to the documentation, you can run the consumer using the following command: ./manage.py run_huey My question is, how and where will I need to run this command to work with my setup i.e. Windows and IIS? It should also work when the server is restarted. -
How to check email validation using regex in Django
I'm trying to create a registration form for my Django project. I want to check if the user's email address is correct. I used built-in email validator, but it just check the domain. I need to prevent user to enter emails like this: john#doe@gmail.com etc. here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=300, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True, validators=[validate_email]) username = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.user.username) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'email', 'username', 'password1', 'password2'] labels = {'first_name':'Name',} signals.py @receiver(post_save, sender=User) def createProfile(sender, instance, created, **kwargs): if created: user = instance profile = Profile.objects.create( user = user, username = user.username, email = user.email, name = user.first_name, ) and views.py for registration def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User Account Was Created!') login(request, user) return redirect('profile') else: messages.error(request, 'An error has accurred during registration!') context = {'page' : page, 'form' : form} return render(request, 'users/login-register.html', context) -
KeyError at / 'daily'
current_weather_url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid={}' forecast_url = 'https://api.openweathermap.org/data/3.0/onecall?lat={}&lon={}&exclude=current,minutely,hourly,alerts&appid={}' def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url): response = requests.get(current_weather_url.format(city, api_key)).json() lat, lon = response['coord']['lat'], response['coord']['lon'] forecast_response = requests.get(forecast_url.format(lat, lon, api_key)).json() weather_data = { 'city': city, 'temperature': round(response['main']['temp'] - 273.15, 2), 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], } daily_forecasts = [] for daily_data in forecast_response['daily'][:5]: daily_forecasts.append({ 'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'), 'min_temp': round(daily_data['temp']['min'] - 273.15, 2), 'max_temp': round(daily_data['temp']['max'] - 273.15, 2), 'description': daily_data['weather'][0]['description'], 'icon': daily_data['weather'][0]['icon'], }) return weather_data, daily_forecasts --- THIS IS THE FORECAST REPONSE THAT I GET forecast_response {'cod': 401, 'message': 'Invalid API key. Please see ' 'https://openweathermap.org/faq#error401 for more info.'} Actually i am creating a weather app where i used api from https://home.openweathermap.org/ but while using the forecast url in the above function in the for loop for daily_forecasts it says that >>>KeyError at / 'daily' and the line having mistake is shown to be >>>for daily_data in forecast_response['daily'][:5]: In the for loop for daily_forecasts, I'm encountering a KeyError related to the 'daily' key in the OpenWeatherMap API response. I've verified my API key and the overall structure of the response, but I seem to be missing something crucial. please fix this it says that daily is not there but it is there . -
python manage.py runserver takes forever
I recently transfered my django project from a windows computer to a mac. The project is made up of 5 apps. Some are standalone while some has import from other apps. When I run python manage.py runserver the app never comes out of performing systems checks. I have noticed that this problem is majorly due to two apps out of the 5. This is becuase when I comment the url path from the projects main urls model the manage.py runs file. But once I uncomment it, the problems starts again. I have checked my paths and I belive the are accurate. Is there a what I can make the runserver command show me some output. Thank you for your help. -
Pre-Commit throwing Errors on Missing whitespace after ":"
I used the same pre-commit configuration on my windows pc, but since i switched to a macos, whenever i run a pre-commit on my python-django project, i get unexpected errors like missing whitespace after colon, even when the said colon iS at the end of a class definition or function definition or colons present in a url string, i know from the docs that a space is not needed after this cases, i believe this has something to do with the os switch or some misconfiguration with pre-commit on my new pc, Python VERSION: 3.12 pre-commit configuration exclude: "^docs/|/migrations/" default_stages: [commit] repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer # - id: check-yaml - repo: https://github.com/asottile/pyupgrade rev: v3.3.1 hooks: - id: pyupgrade args: [--py310-plus] - repo: https://github.com/psf/black rev: 22.12.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 hooks: - id: flake8 args: ["--config=setup.cfg"] additional_dependencies: [flake8-isort] # sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date ci: autoupdate_schedule: weekly skip: [] submodules: false Sample Error Message config/settings/production.py:109:21: E231 missing whitespace after ':' Acutal line pointed at in the code STATIC_URL = f"https://{aws_s3_domain}/{AWS_STORAGE_BUCKET_NAME}/payment/static/" Can anyone … -
For loop for users in Django
GoodEvening I have written a web app that list shooters scores. I have all of that working. I added a new app that will list the shooter average scores. But I can't figure out how to loop though the current users. I have use the built in User model and built another model call Scores for the individual scores. Sorry to have to ask for help. But i work on this for hours. Here is the model Scores from django.conf import settings from django.db import models from django.db.models import Avg rifle_type_choices = {("B", "B"), ("S", "S")} optic_type_choices = {("O", "O"), ("S", "S")} range_distance_choices = {("50", "50"), ("100", "100")} class Scores(models.Model): date = models.DateField() match_score = models.IntegerField() xcount = models.IntegerField() rilfe_type = models.CharField(max_length=1, choices = rifle_type_choices, default = "B") optic_type = models.CharField(max_length=1, choices = optic_type_choices, default = "O") range_distance = models.CharField(max_length=3,choices = range_distance_choices, default = "100" ) username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return f' {self.username} {self.date}' Here is the view for the Average app # average/views.py from django.http import HttpResponse from django.template import loader from scores.models import Scores from django.db.models import Avg def index(request): template = loader.get_template("average.html"); context = { 'avg50': Scores.objects.filter(range_distance="50").aggregate(Avg("match_score")), 'avg100': Scores.objects.filter(range_distance="100").aggregate(Avg("match_score")), 'scores_list': Scores.objects.values('username') } return HttpResponse(template.render(context, request)) Here … -
Filtering select field options in Django Rest Framework
How can brand and type fields filter options based from the existing asset category chosen, and unit model filtering options based from the selected brand? This is my JS: $(document).ready(function() { const assetId = $('#asset_id').val(); axios({ method: 'get', url: `/api/assets/assets/${assetId}`, }).then(function(res) { let data = res.data; $('#id_name').val(data.name); $('#id_property_number').val(data.property_number); $('#id_serial_number').val(data.serial_number); $('#id_date_acquired').val(data.date_acquired); getAllBrand(data.brand) getAllUnitModel(data.unit_model) getAllStatus(data.status) getAllType(data.type) getAllUser(data.user) getAllDepartment(data.department) getAllArea(data.area) axios.get(`/api/assets/asset_details/`,{ params:{ asset: data.id } }).then(function(res) { const dataObj = res.data; const $formWrapper = $('#form_field_wrapper').empty(); dataObj.forEach(obj => { const assetObj = obj.asset_field; const fieldId = `id_${assetObj.field_name}`; const feedbackId = `feedback_${assetObj.field_name}`; const requiredInfo = obj.asset_form.is_required ? '<span class="text-danger">*</span>' : ''; const requiredClass = obj.asset_form.is_required ? 'form-required' : ''; switch(assetObj.field_type) { case 'radio': break; case 'checkbox': break; case 'text': var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> <div class="form-floating mb-3"> <input type="text" class="form-control asset-form-field ${requiredClass}" id="${fieldId}" placeholder="${assetObj.field_label}" value="${obj.value}"> <label for="${fieldId}">${assetObj.field_label} ${requiredInfo}</label> <div class="invalid-feedback" id="${feedbackId}"></div> </div> </div> `); $(`#${fieldId}`).data(fieldData); break; case 'select': let fieldOptions = JSON.parse(assetObj.field_option); var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> … -
How to resolve: Django make migrate not running in AWS ECS from Dockerfile
I have a Django project that runs in a Docker container. Locally when I have updated the project to include changes to the model, I have run python manage.py makemigrations and python manage.py migrate within the docker container. In particular, I would enter the container from the terminal and run python manage.py makemigrations and python manage.py migrate to execute the changes. This worked locally. However, now that I have pushed my code to production (AWS ECS) for some reason manage.py is not running to update the existing database. There is no evidence that manage.py is running at all, even though it is in my entrypoint.sh script. Are there any additional configs that I need to set up either in the Dajngo project or in AWS ECS to be able to run migrations in the AWS ECS environment? The project is otherwise running fine, so the docker container is up, just python manage.py migrate is never run. I have included the Dockerfile below for reference: FROM python:3.11-slim-bookworm ENV uid=1000 ENV gid=1000 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV TZ=UTC ENV USER=app_user UID=$uid GID=$gid RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update \ && apt-get install -y … -
AWS Beanstalk container with Django app can't connect to RDS DB but it accessible from EC2 server and anothe container
My MySQL DB and EC2 instances where Elastic Beanstalk is running are in different VPCs. So I connect to DB via public IP and allow inbound connection in DB SG for my EC2 instance. But I still receive the error Access denied from DB. I tried to connect directly from that instance and even connect from another container(my Django app is crashing) and it works well. The strange things - everything works fine for one env, and doesn't work for another -
Custom authenticate function not working as expected
I have made my own backend for authenticating users with either an email or username. Now I have created a new class view in my app and im trying to authenticate a user. here is a fragment of my class view def post(self, request): dataRecieved = request.data user = authenticate(request, login = dataRecieved["login"], password = dataRecieved["password"]) return Response(user.username) try: login(request, user) return Response(status=200) except Exception: return Response("di[a") the authenticate here is from django.contrib.auth and inside it calls my authenticate function from my custom backend. I haven't changed anything here try: user = backend.authenticate(request, **credentials) except PermissionDenied: # This backend says to st.... Now here is my backend authenticator function def authenticate(self, login=None, password=None, **kwargs): if login is None or password is None: return None try: users = UserModel.objects.filter(username=login) | UserModel.objects.filter(email=login) except UserModel.DoesNotExist: return None else: for user in users: if user.check_password(password) and self.user_can_authenticate(user): return user and when i try to return the user all i get is a NoneType, what should I do? I have tried returning strings within both authenticate functions but it always comes out as a NoneType, im 100% its something wrong with my authenticate function but i have no clue what's wrong. -
i am trying to fetch data from my mongodb Database with django but keep getting : the JSON object must be str, bytes or bytearray, not OrderedDict
so i have an employes collection with a bunch of data that is in this format : { "_id": { "$oid": "511d0a9f181b16509ae5f7dd" }, "nom": "Leberre", "prenom": "Stephanie", "anciennete": 1, "adresse": { "numero": 79, "codepostal": 9500, "ville": "Toulouse", "rue": "Jean Moulin" }, "tel": 559608352, "prime": 1500 }, here is the models.py : from django.db import models class Employee(models.Model): nom = models.CharField(max_length=100) prenom = models.CharField(max_length=100) anciennete = models.IntegerField() adresse = models.JSONField() tel = models.CharField(max_length=20, blank=True, null=True) prime = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.nom}, {self.prenom}" serializers.py : from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' and finally views.py : from rest_framework.response import Response from rest_framework import generics from .models import Employee from .serializers import EmployeeSerializer class EmployeeListView(generics.ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer def list(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) i keep getting :"the JSON object must be str, bytes or bytearray, not OrderedDict ". i dont need a very specific solution, just any solution works even if it involves modifying all the files mentioned above -
Is there a solution to combine a multi tenancy django project and google authentication
I am facing a problem in my django project, i need to set up two type of users, 1- guest users ( log in with google authetication ) 2- partner users ( log in with their own e-mail but as multi tenant) if i run the project with only one them it works fine, but not together, settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SITE_ID=2 SHARED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', 'taggit', 'django_tenants', 'api', 'tenantapp', ] TENANT_APPS = [ # your tenant-specific apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', #'django_browser_reload', 'taggit', 'django_tenants', 'agency', ] INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE" : [ "profile", "email" ], "AUTH_PARAMS" : { "access_type":"online" } } } # possible options: 'sweetalert', 'sweetalert2' - default is 'sweetalert2' SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' TAILWIND_APP_NAME = 'theme' INTERNAL_IPS = [ "127.0.0.1", ] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #"django_browser_reload.middleware.BrowserReloadMiddleware", … -
Error when im trying to install psycopg2 :(
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 Failed to build psycopg2 ERROR: Could not build wheels for psycopg2, which is required to install pyproject.toml-based projects Python 3.12 requirements.txt: asgiref==3.2.10 Django==3.1 pytils==0.4.1 pytz==2022.7.1 sqlparse==0.4.3 I have read all the other articles on this topic. Installed vs build tools c++ -
How to implement Django's ConditionalGetMiddleware to compare `If-Modified-Since` in the req. headers with `Last-Modified` in the res. headers?
I'm trying to implement conditional caching using django.middleware.http.CondtionalGetMiddleware. I'm able to correctly return 304/200 if I provide an If-None-Match with ETag value in the request headers. However, I'm unable to do so when I provide If-Modified-Since in the request headers. I believe it is because my response does not contain a header called Last-Modified, which ConditionalGetMiddleware seems to be requiring, as follows: class ConditionalGetMiddleware(MiddlewareMixin): """ Handle conditional GET operations. If the response has an ETag or Last-Modified header and the request has If-None-Match or If-Modified-Since, replace the response with HttpNotModified. Add an ETag header if needed. """ def process_response(self, request, response): # It's too late to prevent an unsafe request with a 412 response, and # for a HEAD request, the response body is always empty so computing # an accurate ETag isn't possible. if request.method != "GET": return response if self.needs_etag(response) and not response.has_header("ETag"): set_response_etag(response) etag = response.get("ETag") last_modified = response.get("Last-Modified") last_modified = last_modified and parse_http_date_safe(last_modified) if etag or last_modified: return get_conditional_response( request, etag=etag, last_modified=last_modified, response=response, ) return response def needs_etag(self, response): """Return True if an ETag header should be added to response.""" ... Ideally, I would like Last-Modified to have a value similar to ConcernedModel.objects.latest("updated_at"). One way that … -
Django Custom User model AbstractBaseUser and Proxy models. Password is not hashed or set properly
When user is registered with a form or in admin the password is not hashed, as with the superuser. Any help appreciated. I cannot seem to figure this out. Oh, I am not able to login either. Exept from superuser. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'theapp', 'rest_framework', 'userapp', ] . . . AUTH_USER_MODEL = "userapp.UserAccount" model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email or len(email) <= 0: raise ValueError("Email field is required !") if not password: raise ValueError("Password is must !") user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): class Types(models.TextChoices): STUDENT = "STUDENT", "student" TEACHER = "TEACHER", "teacher" type = models.CharField( max_length=8, choices=Types.choices, default=Types.TEACHER) email = models.EmailField(max_length=200, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) phone_no = models.CharField(max_length=10) # special permission which define that # the new user is teacher or student is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = "email" # defining the manager for the UserAccount model objects = UserAccountManager() def … -
testing Profile creation after user registration with uninttest
i use signals for create profile after user register, Manually the test and def test__create_profile is correct, but def test_profile_created_automate is false. this is my test: class Testprofile(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(email='hosein@gmail.com', username='hosein', password='admin') def test__create_profile(self): response = self.client.post(reverse('users-front:create_profile'), data={ "user": 1, 'age': 10, "first_name": "string", "last_name": "string", "phon_number": "9182133038", "birthday": "2023-11-21", "bio": "string", "address": "string", "gender": "M" }) self.assertEquals(response.status_code, 201) def test_profile_created_automate(self): user = User.objects.get(username='hosein') self.assertTrue(Profile.objects.filter(user=user).exists()) -
Error when try to add data to db in djnago app
i have djnago application (emergency notification system) and i see error when i try to add data to this is my views py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Contact #################################################### class Main(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def Registration(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] myuser = User.objects.create_user(username, email, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def Signin(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "emnosys/main.html") else: return redirect('signin') return render(request, "emnosys/signin.html") ################################################ def Signout(request): logout(request) return redirect('home') ###################################################### class PersonalPage(TemplateView): template_name = 'emnosys/personalpage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context #################################################### def add_contact(request): if request.method == 'POST': username = request.POST.get('about--username') message = request.POST.get('about--message') email = request.POST.get('about--email') Contact.objects.create(username=username, message=message, email=email) return render(request, 'emnosys/addcontacts.html') this is my models py from django.db import … -
How to resolve error running pipdeptree with Python 3.11
I'm following the instructions here for upgrading Django: Django Upgrade Video And I get a big error when trying to run the first command for deriving dependencies: pipdeptree -f --warn silence | grep -E '^[a-zA-Z0-9\-]+' The following is the error stack trace Traceback (most recent call last): File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/bin/pipdeptree", line 8, in <module> sys.exit(main()) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/__main__.py", line 44, in main render(options, tree) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/__init__.py", line 27, in render render_text( File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 34, in render_text _render_text_with_unicode(tree, nodes, max_depth, frozen) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in _render_text_with_unicode lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in <listcomp> lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 59, in aux node_str = node.render(parent, frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 53, in render return render(frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 114, in render_as_root return self.as_frozen_repr(self._obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 79, in as_frozen_repr fr = FrozenRequirement.from_dist(our_dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 244, in from_dist req, editable, comments = get_requirement_info(dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 174, in get_requirement_info if not dist_is_editable(dist): ^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/utils/misc.py", line 384, in dist_is_editable egg_link = os.path.join(path_item, dist.project_name + ".egg-link") ^^^^^^^^^^^^^^^^^ AttributeError: 'Distribution' object has no attribute 'project_name' I'm new to Django and Python. I do not know how … -
Adding filter to inline raw_id_field in django admin
I have a data model as below: class School(models.Model): name = models.CharField() class Candidate(models.Model): name = models.CharField() school = models.ForeignKey(School) class Skill(models.Model): name = models.CharField() school = models.ForeignKey(School) class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate) skill = models.ForeignKey(Skill, related_name='candidate_skills') And in the admin I have: class CandidateSkillInline(admin.TabularInline): model = CandidateSkill form = CandidateSkillInlineForm fields = ('skill', ) raw_id_fields = ('skill',) class CandidateAdmin(admin.ModelAdmin): model = Candidate fields = ('name', 'school') inlines = [CandidateSkillInline] What I am trying to achieve is when I click the skill raw_id_field from the CandidateAdmin I want to list only the skills that belong to the school of the candidate. I had tried this solution https://stackoverflow.com/a/66429352/16891729 but in case of inlines I am getting the instance as None. So I can't access the candidate's school from the instances. This solution is working if we are filtering based on static value. How can I achieve this? -
Override Save to create multiple objects for range()
I want to override Django form save method to be able to create multiple objects at once. I have an AvailableHours model : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True) free_hours_to = models.IntegerField(null=True, blank=True,) status = models.BooleanField(null=True,default=True,) and I have a ModelForm for this class : class TimeGenerator(forms.ModelForm): class Meta: model = AvailableHours fields = ['free_date','free_hours_from','free_hours_to','status'] def save(self, commit=True): m = super(TimeGenerator, self).save(commit=False) self.free_hours_from = self.cleaned_data['free_hours_from'] self.free_hours_to = self.cleaned_data['free_hours_from'] +1 m.save() for hour in range(self.cleaned_data['free_hours_from'],self.cleaned_data['free_hours_to']+1): self.free_hours_from = self.cleaned_data['free_hours_from']+hour self.free_hours_to = self.cleaned_data['free_hours_from']+hour+1 print(hour) m.save() I want to create multiple AvailableHours object like this: if the form is set free_hours_from = 13 and free_hours_to=16 so the save method creates 13-14 , 14-15, 15-16 I wrote a code above in forms and overrided save() but its not working. anyone has a solution ? -
Django app making methods available to other apps written by third parties. How to define what is an 'external' api and what isn't?
We are creating a large Django program in which we expect other teams to write apps that will plug into and run within our Django program. We want our main app to provide some helper methods, type definitions etc that are freely available for other aps to utilize. So far that's easy, they just import our module and run whatever method they want. However we don't want all our methods to be treated as a public api available to other apps. Methods other apps use must be maintained for backwards compatibility, better documented etc after all. We want some methods to be used only internal to our app and would prefer end users not call them; or at the very least that they know we made no guarantee of not changing those methods in future releases. Now we could go around appending a _ in front of every method we don't want other apps using, but they aren't really private methods in my mind, since they are publicly available to other modules within our app. In addition well we already have allot of the app written and I don't want to go back and retroactively refactor half of our methods. …