Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My GoDaddy domain serves a blank page when I connect it with my Heroku App
Recently, I built a Heroku app using Django and React. The app works wonderfully, however when connected to GoDaddy's domain, it serves a blank page. I won't say anything else, partly because I don't know what information is necessary, but request you to ask the right question for me to provide more information. Thanks. -
Django says: too many values to unpack (expected 2)
I'm using Django. In the upload_book function, I generate a 10-digit code for each book and I identify and distinguish two books from one another by their code, rather than their primary key. However, I get an error in the generate_code function: ValueError at /main/upload_book/ too many values to unpack (expected 2) Here is the generate_code() function with required imports: import random, string def generate_code(max_length): code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) while len(Book.objects.filter(code)) != 0: code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) return code I did the extra bit over there to prevent two books being of the same code, however low the probability of that might be with 629 possible combinations. And here's my upload_book() function: @login_required def upload_book(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('description') author = request.POST.get('author') code = generate_code(10) owner = request.user if 'thumbnail' in request.FILES: thumbnail = request.FILES['thumbnail'] book = Book(title=title, description=description, author=author, thumbnail=thumbnail, owner=owner, code=code) book.save() return redirect("/main/all_books/") else: return render(request, 'main/upload_book.html') And my Book model in models.py: class Book(models.Model): title = models.CharField(max_length=1000, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) description = models.TextField() author = models.CharField(max_length=1000, blank=True, null=True) thumbnail = models.ImageField(upload_to='book_thumbnails', blank=True) creation_date = models.DateTimeField(default=timezone.now) status = IntegerField(default=1) min_age = models.IntegerField(blank=True, null=True) … -
Add one field to User
After I switched my Abstract User my login page not on the admin gets a 500 server error. Also my admin gets a weird extension while logged in /pages/profile/. All I wanted to do was add a single field to the user so they can upload a file. models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='users/', null=True, blank=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Profile class CustomUserAdmin(UserAdmin): pass admin.site.register(Profile, CustomUserAdmin) settings.py # Extends default user with additional fields AUTH_USER_MODEL = 'pages.Profile' -
How to add fields with default values to the User model in Django
I need to add fields to the User model with default values that will not be displayed in the registration form but I am new to Django. How can I implement it and what am I doing wrong? models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): level = models.IntegerField(default=0) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import CustomUser class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите ваше имя'})) email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control', 'placeholder': 'введите вашу почту'})) password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите пароль'})) password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'подтвердите ваш пароль'})) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) for field_name in ['username', 'email', 'password1', 'password2']: self.fields[field_name].help_text = None class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') views.py: from django.contrib.auth import logout from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm, LoginUserForm class RegisterUser(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = 'users/register.html' -
django rest framework: building 2 separate auth and service system
how to implement 2 separate django rest framework system 1 for auth and 1 for service the goal is you get your auth from one api and use other api for services which use the auth for authentication and permission of it's services. my question is on Django rest framework and have 1 database is preferable for me but if you have answer and road to implementation such system with multiple database it would be appreciated too. i want to build entire system for authentication and permission. so i can integrated it with all of my other services -
How do I access the admin console in django application with elastic beanstalk?
So I am following the tutorial on “Deploying a Django application to Elastic Beanstalk”, but I am getting stuck on when I am trying to access the admin console. When I do go to the admin site(Ex: http://djang-env.p33kq46sfh.us-west-2.elasticbeanstalk.com/admin/), I do not see the styling applied even though I did add the static root under the settings.py file. What I see instead is a non-styled admin page, and when I try to log in, I get a Net gear block page telling me to go back. The things I am doing different from the tutorial are using the commands winpty python manage.py createsuperuser for creating the superuser and using source ./Scripts/activate. What I am using: django==3.2.9; python==3.7.9; git bash; windows machine Any help is greatly appreciated. -
Django backend on port 8083 can't parse AJAX CORS POST request served from gulp web page on port 8081
On Linux Debian Bullseye, I am running a gulp HTML server on port 8081, and a Django backend on port 8083. I am trying to POST a relatively large JSON document from a static page using JQuery's AJAX feature. After properly setting up the django-cors-headers module, with MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware" ] , CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS on settings.py, I coded the following HTML view on views.py, with the @csrf_exempt decorator in place since I'm running everything on localhost: from django.views.decorators.csrf import csrf_exempt @csrf_exempt def processOrder(request): leasing_order_unicode = request.body.decode("utf-8") print(request.POST.__dict__) print(request.POST["leasing_order"]) return HttpResponse(leasing_order_unicode, headers={ "Access-Control-Allow-Origin": "http://localhost:8081", "Content-Type": "application/json" }) Then I added it to urls.py as follows: path("processorder", processOrder, name="processorder") I expect my Django view to be able to access the JSON string with request.POST["leasing_order"]. Instead, I get errors and failures when attempting to access it. Let serializedata() be a function that takes care of gathering all my local data into an object and then serializing it. If I POST my form data with multipart/form-data encoding as follows: export function sendOrder_multipart() { let finalorder = serializedata(); let finalorder_postdata = new FormData(); finalorder_postdata.append("leasing_order", finalorder); $.ajax({ method: "POST", url: "http://localhost:8083/orderstable/processorder", data: finalorder_postdata, processData: false, contentType: "multipart/form-data" }); } I get the following error … -
How to pass true or false value in django rest framework serializer
here is my serializer code; class RegisterSerializer(serializers.ModelSerializer): password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) email = serializers.EmailField(required=True) is_company = serializers.BooleanField(required=False) class Meta: model = CustomUser fields = [ "email", "first_name", "last_name", "is_company", "profile_pic", "password1", "password2", ] def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( ("A user is already registered with this e-mail address.",) ) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data["password1"] != data["password2"]: raise serializers.ValidationError( ("The two password fields didn't match.",) ) return data def get_cleaned_data(self): return { "first_name": self.validated_data.get("first_name", ""), "last_name": self.validated_data.get("last_name", ""), "is_company": self.validated_data.get("is_company", ""), "profile_pic": self.validated_data.get("profile_pic", ""), "password1": self.validated_data.get("password1", ""), "email": self.validated_data.get("email", ""), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) if self.cleaned_data.get("profile_pic"): user.profile_pic = self.cleaned_data.get("profile_pic") setup_user_email(request, user, []) user.save() return user Basically what I am trying to do is, when I make a request with a json format in something like postman; { "first_name": firstname, "last_name": lastname, "email": myemail, "password1": password1, "password2": password2, "is_company": true } when I pass true to is_company, I want that to change is_company value to true; but I keep getting false. I have tried using form data, but still get false … -
Django - TypeError: unhashable type: 'SQLDecodeErrorDjango '
I had everything running perfectly but I had to reinstall windows and when I tried to run the code again, it started giving me errors on user registration. I followed Vitor Freitas guide to make implement multiple user types but only differed in views as he was using class based views and I had no idea what those were at that time. I have narrowed down the problem where I am creating User table (This line: user = User.objects.create(user=account) in forms.py). Models.py class MyAccountManager(BaseUserManager): def create_user(self , email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name,last_name, password): user = self.create_user( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email',max_length=50,unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_user = models.BooleanField(default=False) is_Manager = models.BooleanField(default=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return … -
Dictionary only adds in the last key value pair in for loop
I have a for loop that goes through a list of cities and assigns them each a total_city_value. I am trying to get each unique total_city_value created during the for loop added to the dictionary however it seems to be only keeping the final total_city_value in the for loop when I print the dictionary. for broad_variable in broad_variable_list: # check if the current broad variable is equal to the first broad variable the user chose if broad_variable == broad_variable1: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable1: city_variable1_value = 1 * weight_variable1 #print("city_variable1_value",city_variable1_value) # else assign a value of 0 else: city_variable1_value = 0 # check if the current broad variable is equal to the second broad variable the user chose if broad_variable == broad_variable2: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable2: city_variable2_value = 1 * weight_variable2 # else assign a value of 0 else: city_variable2_value = 0 total_city_value = city_variable1_value + city_variable2_value city_value_dictionary[cities] = … -
How to run Django tests in Docker using GitHub Actions
I am building my first full CI/CD pipeline for a Django/React.js project. It uses 2 workflows: build.yml and deploy.yml. The build.yml first builds the images then pushes them to the GH Packages. Then it pulls the images in a new job and runs tests (though I think this is wrong as I think jobs run in parallel - haven't got to this part yet). Build.yml name: Build and Test on: push: branches: - development env: BACKEND_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/backend NGINX_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/nginx jobs: build: name: Build Docker Images runs-on: ubuntu-latest steps: - name: Checkout master uses: actions/checkout@v1 - name: Add environment variables to .env run: | echo DEBUG=0 >> .env echo SQL_ENGINE=django.db.backends.postgresql >> .env echo DATABASE=postgres >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env echo SQL_DATABASE=${{ secrets.SQL_DATABASE }} >> .env echo SQL_USER=${{ secrets.SQL_USER }} >> .env echo SQL_PASSWORD=${{ secrets.SQL_PASSWORD }} >> .env echo SQL_HOST=${{ secrets.SQL_HOST }} >> .env echo SQL_PORT=${{ secrets.SQL_PORT }} >> .env - name: Set environment variables run: | echo "BACKEND_IMAGE=$(echo ${{env.BACKEND_IMAGE}} )" >> $GITHUB_ENV echo "NGINX_IMAGE=$(echo ${{env.NGINX_IMAGE}} )" >> $GITHUB_ENV - name: Log in to GitHub Packages run: echo ${PERSONAL_ACCESS_TOKEN} | docker login ghcr.io -u ${{ secrets.NAMESPACE }} --password-stdin env: … -
Django - How to annotate a single Django object
So Django has this cool feature where you can annotate a query set as in you can add attributes to each object in a query set. For example if I have a query set of users I can annotate it with number of followers which is another table with a foreign key reference to user. This can be done with the QuerySet.annotate() function. I was wondering if this is possible for a single Django object. I have a view function that gets user info, which given a unique user UUID I return the users info in the user table as well as the number of followers and followees. 1 way to do this is just query across all follower and followee table for the uuid and create a dictionary that gets returned or annotate a single object. Is it possible to do this? views.py @api_view(['GET']) def get_user_info(request, user_uuid): is_current_user = user_uuid == str(request.user.uuid) # Return all user info including # of followers and followees models.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) class FollowUser(AbstractSimpleModel): follower = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follower_id') followee = models.ForeignKey( … -
Accessing foreign key attributes for arithmetics in django rest framework
I'm trying to calculate the length of a house relative to some adjacent neighborhoods, such that, house_size / (neighborhood[0].length + neighborhood[1].length...): class House(models.Model): house_id = models.CharField(max_length=256, primary_key=True) size = models.IntegerField() neighborhood = models.ManyToManyField('neighborhood', through='HouseNeighborhoodLink') class Neighborhood(models.Model): length = models.IntegerField() I created a table to assign several neighborhoods with a house. Also, houses can be assigned to several adjacent neighborhoods: class HouseNeighborhoodLink(models.Model): house_id = models.ForeignKey(House, on_delete=models.DO_NOTHING) neighborhood = models.ForeignKey(Neighborhood, on_delete=models.DO_NOTHING) Serializers: class LengthFromNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = Neighborhood fields = ['length'] class HouseCoverageOfNeighborhood(serializers.ModelSerializer): Neighborhood = LengthFromNeighborhoodSerializer(read_only=True) class Meta: model = HouseNeighborhoodLink fields = ['house_id', 'Neighborhood'] I'm stuck in the three dots (...), where I want to access the length attribute of all neighborhoods and then calculate the proportion to a house. I'm not sure how to access the length of each neighborhood from HouseNeighborhoodLink table: class HouseCoverageDetail(generics.ListAPIView): queryset = HouseNeighborhoodLink.objects.all() serializer_class = HouseCoverageOfNeighborhood def get_queryset(self): house_id = self.kwargs['house_id'] neighborhood = self.queryset.filter(house_id=house_id) ... return result -
"Unknown pytest.mark.django_db" when trying to run test for django-treebeard
I'm trying to run the following test from django-treebeard: In case you know what you are doing, there is a test that is disabled by default that can tell you the optimal default alphabet in your enviroment. To run the test you must enable the TREEBEARD_TEST_ALPHABET enviroment variable: $ TREEBEARD_TEST_ALPHABET=1 py.test -k test_alphabet I have Django and PostgreSQL setup via Docker: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 ENV TREEBEARD_TEST_ALPHABET=1 ENV DATABASE_USER = "postgres" ENV DATABASE_PASSWORD = "postgres" ENV DATABASE_HOST = "db" ENV DATABASE_USER_POSTGRES = "postgres" ENV DATABASE_PORT_POSTGRES = 5432 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --dev --system COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "~=3.2" djangorestframework = "*" ulid2 = "*" psycopg2 = "*" django-lifecycle = "*" django-filter = "*" django-cors-headers = "*" djangorestframework-simplejwt = "*" django-allauth = "*" dj-rest-auth = "*" django-treebeard = "*" djangorestframework-recursive = "*" [dev-packages] black = "*" django-debug-toolbar = "*" drf-yasg = "*" coverage = … -
How do I reuse a ModelForm for a through model with an additional field?
I have a Model Example and corresponding ModelForm ExampleModelForm that I use in ModelFormset ExampleModelFormset = modelformset_factory(Example, form=ExampleModelForm) I have a many-to-many through Model with an additional property. class ExampleThrough(models.Model): batch = models.ForeignKey(Batch, on_delete=models.CASCADE) example = models.ForeignKey(Example, on_delete=models.CASCADE) property = models.FloatField() Is there a way to reuse the ExampleModelForm to create a ExampleThroughModelForm that I can also use in a ExampleThroughModelFormset? I want to have all of the same fields as the ExampleModelForm plus the one new property. I don't think I can inherit from the ExampleModelForm: class ExampleThroughModelForm(ExampleModelForm): class Meta: model = ExampleThrough fields = '__all__' because the documentation has this note: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child’s Meta, if it exists, otherwise the Meta of the first parent, etc. -
Desired Outcome: I want to dynamically create and render data from a One to Many Field to a template in Django
I have two models with One to Many relationship. The Models are Parent and Child respectively. I have managed to dynamically render data from the Parent Model, but now I want to be able to put a link to to each Parent Record, such that when clicked it will create a Child record and render out the child information to the respective parent. #Models class Parent(models.Model): surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, on_delete=SET_NULL) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) views.py def display(request, pk): parents = Parent.objects.get(id=pk) child = parents.child_set.all() context = {'parents':parents, 'child':child} return render(request, 'reg/info_page.html', context) I have tried to implement the reverse relation but when I try to display the child's information, it comes up blank. div class="col-md-4 col-sm-4 text-center"> <p class="text-purple">Child Name</p> <h1>{{child.first_name}}</h1> </div> -
Django - Error when changing from GET to POST
I have a react/django application that works fine when the request is a GET request. For example, in the React part I have the following sendRequestParameters(url) { axios({ url: url, method: 'get', headers: { 'X-CSRFToken': 'csrf_token', 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8', }, params:{ 'TECHNOLOGY': JSON.stringify(this.state.technologySelectedValue), // more parameters here, all in the same format }, paramsSerializer: function(params) { return qs.stringify(params, {arrayFormat: 'repeat'}) } }).then((response ) => { console.log(response.data); }).catch((error) => { console.log(error) }) } Then, in the backend, I get the parameters and return them (this function is called in another function where the returned parameters are used, that's why there is a return statement). def extractParameters(request): TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) # more parameters extracted here, same format return TECHNOLOGY etc. That all works fine. However, I need to change to POST requests, and when I make two small modifications to do this, I get an error. In the front end request with axios, I change the method: 'get' to method: 'post'. Then, in the backend, I change TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) to TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) This gives me the following error in the terminal TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object … -
Insert bulk data into postgresql with Django
I'm using heroku and trying to create a project that uses postgresql. I have a model like this: class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLDE = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLDE, 'Gold'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=14) birth_date = models.DateField(null=True, blank=True) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) I'll use a mock data like this: insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (1, 'Lissy', 'Rissen', 'lrissen0@bloglovin.com', '105-879-7972', '2000-11-07', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (2, 'Peterus', 'Caddens', 'pcaddens1@usda.gov', '471-936-4037', null, 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (3, 'Debee', 'Ceschini', 'dceschini2@cyberchimps.com', '526-812-6447', null, 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (4, 'Inessa', 'Blogg', 'iblogg3@mail.ru', '656-866-8989', '1985-10-21', 'S'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (5, 'Charline', 'Mayberry', 'cmayberry4@statcounter.com', '609-214-0294', '1999-09-20', 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (6, 'Bunni', 'Furness', 'bfurness5@webmd.com', '926-176-0613', '2018-07-02', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (7, 'Juana', 'Double', 'jdouble6@mysql.com', '873-793-8148', '2015-03-04', 'G'); insert into store_product (id, first_name, last_name, email, … -
Getting the value of two rational variables inside a for loop and adding them outside the for loop
I have two for loops in my program. The first for loop goes through a list of cities and the second for loop goes through a list of broad variables (safety, affordability, transit, etc). Inside the second for loop I assign a value to each city's broad variable city_variable1_value = 1 * weight_variable1 and city_variable2_value = 1 * weight_variable2. Inside the first for loop I add both city variables to get a total value total_city_value = city_variable1_value + city_variable2_value however this value is consistently outputting as 0 instead of the desired outcome 0.57 Here are my print outputs for print("city_variable1_value",city_variable1_value) is 0.24 print("city_variable2_value",city_variable2_value) is 0.33 print("total_city_value",total_city_value) is 0 views.py def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 = form.cleaned_data['specific_variable2'] broad_variable1 = form.cleaned_data['broad_variable1'] broad_variable2 = form.cleaned_data['broad_variable2'] # loop through each city in the database for cities in City.objects.values_list('city', flat=True): print("cities",cities) # loop through each broad variable in the list at the top of this … -
how to auto scroll down when new messages added
I am working with django , I want to scroll down auto when new messages added 'sent or received', I can scroll down auto when I refrech the page because of this code line : $("#card-body").animate({ scrollTop: 20000000 }, "slow"); but when I send and I receive new messages the messages go down until I can't see them I have to scroll down manually this is the js code : <script> /* send message*/ document.getElementById('send-btn-id').onclick = function (e) { const msg = document.getElementById('message').value; chatSocket.send(JSON.stringify({ 'message': msg, 'user': me, 'friend': friendName })); document.getElementById('message').value = ""; }; const friendName = JSON.parse(document.getElementById('friend').textContent); const me = JSON.parse(document.getElementById('me').textContent); /* set friend profile name */ document.getElementById('friend-name').innerHTML = friendName['username']; /* start conversation */ document.querySelector('.start-conversation').innerHTML = 'Start conversation with <strong>'+friendName['username']+'</strong>'; /* connection request */ const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendName['username'] + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); var class_name = 'in'; var profile_image = '{{friend_obj.profile.image.url}}'; if(me['username'] == data.user['username']) { data.user['username'] = 'Me'; class_name = 'out'; profile_image = '{{request.user.profile.image.url}}'; } var chat_list = document.querySelector('#chat-list-id'); var chat = "<li class=\""+class_name+"\"><div class=\"chat-img\"><img alt=\"avatarchat\" src=\""+profile_image+"\"></div><div class=\"chat-body\"><div class=\"chat-message\"><h5>"+data.user['username']+"</h5><p>"+data.message+"</p></div></div></li>"; chat_list.innerHTML += chat; }; </script> -
Limit Django ModelForm ForeignKey choices depending on request.user
It is sometimes desirable to restrict the choices presented by the ForeignKey field of a ModelForm so that users don't see each others' content. However this can be tricky because models do not have access to request.user. Consider an app with two models: class Folder(models.Model): user = models.ForeignKey(get_user_model(), editable=False, on_delete=models.CASCADE) name = models.CharField(max_length=30) class Content(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) text = models.CharField(max_length=50) The idea is that users can create folders and content, but may only store content in folders that they themselves created. i.e.: Content.folder.user == request.user QUESTION: How can we use for example CreateView, so that when creating new content users are shown the choice of only their own folders? -
How to get item by hashed CharField in django
I have Device model that has a field named token that stores a pbkdf2_sha256 hashed string. from django.contrib.auth.hashers import make_password from django.models import Model, CharField class Device(Model): name = CharField(max_length=200) token = CharField(unique=True, max_length=128) def save(self,*args,**kwargs): self.token = make_password(self.token) super().save(*args,**kwargs) for example I have a Device object that it's token is hashed value of ABCD. now question is if I get ABCD from user as raw token, how i can find it's device from database? I tried this: I hashed the ABCD that I got from user with make_password, but the new hashed value wasn't as same as the old one that was in db. also I know that I can get device id from user and then check if user's entered token is same with check_password method. but I want only get token from user not device id and token. -
Django runserver memory leak?
Seemingly out of nowhere, whenever I called the url for my Django model, be it with ListView or DetailView, it would hang, and while doing so the memory would spike and I had to kill runserver. I have now tracked this issue down to subprocess._try_wait(). The simple solution seems to be to raise ChildProcessError. But this is source code, and I've always been told not to mess with source. So how am I supposed to fix this? With a decorator? That still has to go in the source, doesn’t it? Please advise. Also, I note that there is a comment in the source code about a python bug in the method immediately preceding _try_wait(), which is _internal_poll(). See http://bugs.python.org/issue15756 . However, that bug was reported and fixed all the way back in 2012, and it was thought to be identical to 1731717, reported all the way back in 2007 and fixed in Python 3.2. This project is my first on Python 3.9.9, so I am hoping this bug has not been re-introduced. Django is 3.2.9, os is Ubuntu 20.04. Also, all these comments and bug reports talk about “SIGCLD is set to be ignored.” But if that’s the better way … -
License key generation after purchase with django
Hi I was wondering how its possible with django to generate a license key once someone has made a purchase on my site, I'm still trying to learn the framework and understand how it works. I'm guessing it would be something to do with views.py as it would be a request but as I said i'm only just learning the basic fundamentals as of right now and I've done some research and I cant seem to find much. -
Cloudrun Django+Terraform / 404 error on app URL
I just followed this tutorial : https://github.com/GoogleCloudPlatform/serverless-expeditions/tree/main/cloud-run-django-terraform I've done : gcloud builds submit --config cloudbuild-migrate.yaml terraform apply -var project=$PROJECT_ID My database was created. Service was pushed online well and I've got a service_url. When I access it, it shows a 404 error. Even if try to access the /admin page, it just returns a 500 error with no explanation in the log journal (or I didn't find it). When I try to runserver on localhost with sql_cloud_proxy, Django work perfectly. It's just a Django basic project showing hello on homepage. I don't get it. Here's my settings.py file : import io import os from pathlib import Path import environ import google.auth from google.cloud import secretmanager BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env(DEBUG=(bool, False)) env_file = os.path.join(BASE_DIR, ".env") # Attempt to load the Project ID into the environment, safely failing on error. try: _, os.environ["GOOGLE_CLOUD_PROJECT"] = google.auth.default() except google.auth.exceptions.DefaultCredentialsError: pass if os.path.isfile(env_file): # Use a local secret file, if provided env.read_env(env_file) elif os.environ.get("GOOGLE_CLOUD_PROJECT", None): # Pull secrets from Secret Manager project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") client = secretmanager.SecretManagerServiceClient() settings_name = os.environ.get("SETTINGS_NAME", "django_settings") name = f"projects/{project_id}/secrets/{settings_name}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env.read_env(io.StringIO(payload)) else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") SECRET_KEY = env("SECRET_KEY") # …