Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass self.request data in django form?
I want to pass self.request data in the form class. I can access it in View, but unable to access it in form class. class AttendanceCreateView(LoginRequiredMixin, CreateView): model = Attendance template_name = 'attendance/attendances_new.html' form_class = AttendanceForm def get_initial(self): initial = super().get_initial() initial['class_name'] = self.request.GET.get('class', '') return initial My Form class: class AttendanceForm(forms.ModelForm): class_name = forms.ChoiceField(choices=CLASS_NAMES, disabled=True) teacher = forms.ModelMultipleChoiceField( queryset=Teacher.objects.all().order_by('id')) subject_name = forms.ChoiceField(choices=[]) total_students = forms.IntegerField(initial=0) unique_code = forms.IntegerField(initial=0) class Meta: model = Attendance fields = ['class_name', 'teacher', 'subject_name', 'total_students', 'unique_code'] def __init__(self, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) # This I need to be done # if self.request.GET.get('class', '') = 'class1': # self.fields['subject_name'].choices = MY_CHOICES_1 # elif self.request.GET.get('class', '') = 'class2': # self.fields['subject_name'].choices = MY_CHOICES_2 I want to set subject_name choices according to the request values passed. For class 1, I want different subject choices., and for class 2, different subject choices etc. So getting request data is important. Is there any way to set the initial choice in direct View like I did for class_name? Or any suggestions on how to do it in form? -
Generic Delete view
I have a model for booking table that has a onetoone relation with another model table. And i want to be able to change the value of a field of table before deleting the model booking. Here is my BookingTable model... class BookingTable(models.Model): table = models.OneToOneField(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(auto_now_add=True) def __str__(self) -> str: return self.user.get_username() + " - " + self.table.name def get_absolute_url(self): return reverse("list_tables") Here is my Table model... class Table(models.Model): name = models.CharField(max_length=100, unique=True) ocupation_status = models.BooleanField(default=False) size = models.PositiveIntegerField() image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif') description = models.TextField(null=False, blank=False, default="This is a very beatiful table") def __str__(self) -> str: return self.name[:50] def get_absolute_url(self): return reverse("list_tables") And here is my view class CancelBookingView(DeleteView): model = BookingTable template_name = 'cancel_booking.html' success_url = reverse_lazy('list_tables') def form_valid(self, form): form.instance.table.ocupation_status = False return super().form_valid(form) I tried to use form_valid and accessing the table field using the instance attr but it gave an error saying that form has no attr instance. class CancelBookingView(DeleteView): model = BookingTable template_name = 'cancel_booking.html' success_url = reverse_lazy('list_tables') def form_valid(self, form): form.instance.table.ocupation_status = False return super().form_valid(form) -
Button style in Django
The button should be a small vertical rectangle and the top width should stick out a little. It should also be white before pressing and crimson after pressing. And when the pointer goes over this button, the text "Add" and when deleting, "Remove" should be displayed. However, it's just a rectangle, and even its name doesn't change from addition to deletion (the color and style don't change either). Thank you in advance for your ideas:) product_detail.html: <form method= "get" action = "{% url 'add' product.id %}"> {% csrf_token %} <button clasa="bottonwatch" type = "submit" value = "{{ product.id }}" name = "productid"> <div class="addwatch"> {% if product.watch_list %} addWatchlist </div> <div class="removewatch"> {% else%} remove </div> {% endif %} </button> </form> Style: .bottonwatch { border-radius: 50%; height: 2.5rem; min-width: auto; padding: 0; width: 2.5rem; } .addwatch { color: black; background-color: white; } .remove{ color: white; background-color: rgb(100, 36, 36); } views.py: @login_required(login_url="login") def add(request, productid): product_id = request.GET.get('productid', False) watch = Watchlist.objects.filter(user = request.user.username) for items in watch: if (items.watch_list.all) == int(productid): return watchlist(request, request.user.username) else: return remove(request, productid) new_watch = Watchlist(product_id, user=request.user.username) new_watch.save() messages.success(request, "The product has been added to your WatchList.") return product_detail(request, productid) @login_required(login_url="login") def remove(request, pid): … -
Making a common DB for one app across multiple django projects
I have 3 distinct Django projects (or instances) running on the same Ubuntu server (for the same user) in different folders. Lets call these instances (D1, D2, D3). All the 3 projects use sqlite3 as DB. All the 3 projects aside from their inherent differences also have a single common django Model called "Word" (that is basically responsible for storing word images). there can be millions of entries for word model for each of the django projects at any given time. The problem I am encountering is that I need to frequently transfer the word instances from one project to another. the Volume of the words to be transferred is huge (millions of word model instances per day). My current solution is very inefficient, what I am doing is to export all the word entries from D1 project to a single folder and import all the entries from the folder to D2 project. Is there any way to make a common database that all the 3 projects can access for the "Word" model? this will make life much easier where to transfer the words from D1 to D2, I would just have to change a field (probably belongs_to) in all … -
run thread immediately after runserver in docker django
i want to run a thread in my django project after runserver and everything in local deployment is OK: scraper/apps.py: from django.apps import AppConfig import threading class ScraperConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'scraper' def ready(self): from .functions import start_scraper threading.Thread(target=start_scraper).start() But in docker deployment the server not runs until this thread done complete! this is my Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITTEBYTEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN mkdir -p /app WORKDIR /app COPY ./core . RUN pip3 install pip --upgrade RUN pip3 install -r requirements.txt CMD yes yes | python3 manage.py makemigrations && \ python3 manage.py migrate && \ yes yes | python3 manage.py collectstatic && \ python3 manage.py create_superuser && \ python3 manage.py runserver 0.0.0.0:${SCRAPER_OUTER_PORT} it is so amazing that I can run this thread as a request in an endpoint of a rest api in this server without any problem. But I want to run this auotomaticaly , immediately after runserver I think problem is from Dockerfile configs. thanks for your responses and solutions before I tried this methods: python:3.8-slim-buster image ubuntu:20.04 image run server with gunicorn run server with asgi application run all CMD as an init.sh file and make executable it(chmod +x) before all of them not solved … -
How to save vue3openlayer coords to Django SRID4326
I am trying to make markers in my OpenStreetMap. Currently one building in the Bangkok when I use Django coordinate it shows. "SRID=4326;MULTIPOINT (100.53007692708017 13.721325314629256)" Then I make my own Vue3 to be a marker. My function to get the coordinates is template <ol-map :loadTilesWhileAnimating="true" :loadTilesWhileInteracting="true" style="height: 400px" @click="handleMapClick" > <ol-view ref="view" :center="center" :rotation="rotation" :zoom="zoom" :projection="projection" /> <ol-tile-layer> <ol-source-osm/> </ol-tile-layer> </ol-map> script import { fromLonLat, toLonLat } from 'ol/proj'; // Import fromLonLat and toLonLat const convertToSRID4326 = (coordinates) => { const latitude = coordinates[0]; const longitude = coordinates[1]; const latitudeInDegrees = latitude * (180 / Math.PI); const longitudeInDegrees = longitude * (180 / Math.PI); return { latitude: latitudeInDegrees, longitude: longitudeInDegrees }; } const handleMapClick = (event) => { const clickedCoords = toLonLat(event.coordinate); markers.value.push(clickedCoords) markers.value.forEach(element => { console.log(element) console.log(convertToSRID4326(element)) }) } My widget: {0: 0.0009030769278815491, 1: 0.00012325954951108997} My conversion: latitude: 0.05174249654325298 longitude: 0.007062251971669265 But Django is: "SRID=4326;MULTIPOINT (100.53007692708017 13.721325314629256)" Goal: Vue3 be able to use same SRID:4326 as Django. -
Django linking to generic.DetailView page but page contents is the same as the generic.ListView page
I've encountered an issue where I've created a list view and each item in it has a detail view. When I click the item in the list view, the link in the searchbar changes from http://127.0.0.1:8000/catalog/articles/ to http://127.0.0.1:8000/catalog/articles/[UUID], but the actual page contents does not change. Even though I am supposedly in the detail view and I have a detail view html file, the displayed contents is still the list view. articles.html: {% extends 'head.html' %} {% load static %} {% block content %} <h1 class="flex items-center justify-center text-6xl">Articles</h1> <br> {% if articles %} <div class="flex items-center justify-center"> <div class="posts"> {% for article in articles reversed %} <a href="{{ article.get_absolute_url }}"> <div class="article_box"> <img src="{{ article.article_cover_image.url }}" alt="img"> <div class="article_box_sub"> <div>{{ article.article_title }}</div> <div class="text-xs">{{ article.article_date_and_time }} UTC</div> <div class="text-xs"> Written by {% for author in article.article_author.all %} {% if not forloop.last and forloop.revcounter0 > 1 %} <span class="link_light">{{author}}</span>, {% elif forloop.revcounter0 == 0 and forloop.counter0 > 0 %} and <span class="link_light">{{author}}</span> {% elif forloop.revcounter0 == 1 and forloop.counter0 > 1 %} <span class="link_light">{{author}}</span>, {% else %} <span class="link_light">{{author}}</span> {% endif %} {% endfor %} </div> <div> {% for tag in article.article_tags.all %} <div class="tag text-xs">{{tag}}</div> {% endfor %} <div … -
Django ModelFormSets: display each model object along with a field value in a form
This is something that I thought would be easy, but I haven't figured it out yet. I have a simple model called Channel. Here it is: class Channel(models.Model): id = models.PositiveBigIntegerField(primary_key=True) name = models.CharField(max_length=100) disabled = models.BooleanField(default=False) I want the user to be able to see all of the channels, displayed by name, and select which ones to disable or enable. I've gotten close, here's my view (simplified): def channel_setup(request): ChannelFormSet = modelformset_factory( models.Channel, fields=['disabled'], edit_only=True ) formset = ChannelFormSet() context = { 'formset': formset } return render(request, "channel_setup.html", context) What it does is display a checkbox for every single channel in the database. Perfect! The problem is that all of them are labeled "Disabled:", so there's no way to discern which channel is which. I'd like to display each channel by name next to each checkbox. I know there's a way to change the label, but I haven't figured out how to set the label equal to the Channel's name field value. I could probably do some hacky magic with javascript to make it happen but there has got to be a way to just do this with Django, right? -
Django script can't save to database
I'm working on a Django project that has 3 models: class Player(models.Model): nickname = models.CharField(max_length=255) profile_image = models.URLField(null=True, blank=True) class Game(models.Model): players = models.ManyToManyField(Player, related_name='players') winner = models.ForeignKey(Player, on_delete=models.SET_NULL, null=True, blank=True) class Stat(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) score = models.PositiveIntegerField(null=True, blank=True) game = models.ForeignKey(Game, on_delete=models.CASCADE, null=True, blank=True) I've added a generate_data.py script to my app's management/commands/ folder to automatically create random data and add populate the database. The relevant part is this: class Command(BaseCommand): def handle(self, *args, **options): try: print(self.style.SUCCESS('Creating random data')) # generate Player data players = self.generate_random_players() for player in players: player_data = self.generate_random_player_data() player.nickname = player_data['nickname'] player.profile_image = player_data['profile_image'] player.save() # generate Game data game = Game() game.save() for player in players: game.players.add(player) winner = random.choice(players) game.winner = winner game.save() # generate Stat data for player in players: Stat.objects.create(player=player, creation_date=timezone.now(), score=random.randint(0, 100), game=game) print(self.style.SUCCESS('Successfully added')) except Exception as e: print(self.style.ERROR(f'An error occurred: {str(e)}')) There are also some methods to randomly create Players, but those seem to be working as expected. The thing is, when I run the script I always get An error occurred: "<Game: (ID: None). WINNER: No winner.>" needs to have a value for field "id" before this many-to-many relationship can be … -
How to use distinct in django? And help me Find the average of subjects so I can list the top 10 students per School year
marccamba Filipino 07 78.0 78.0 90.0 90.0 SY: 2021 to 2022 alasterpalacio Filipino 07 78.0 79.0 80.0 85.0 SY: 2021 to 2022 alasterpalacio English 07 78.0 78.0 78.0 78.0 SY: 2021 to 2022 marccamba English 07 78.0 79.0 79.0 76.0 SY: 2021 to 2022 denniscabahug Filipino 07 76.0 78.0 76.0 76.0 SY: 2021 to 2022 denniscabahug English 07 75.0 75.0 75.0 75.0 SY: 2021 to 2022 albertbroqueza English 07 75.0 75.0 75.0 75.0 SY: 2021 to 2022 marccamba Filipino 08 90.0 90.0 90.0 90.0 SY: 2022 to 2023 alasterpalacio Filipino 08 90.0 90.0 90.0 90.0 SY: 2022 to 2023 denniscabahug Filipino 08 89.0 89.0 89.0 89.0 SY: 2022 to 2023 marccamba English 08 89.0 89.0 89.0 89.0 SY: 2022 to 2023 I would like to get the average of the scores of english7, filipino7, of a all the students average_session1 = (subject1_session1, subject2_session1,...subjectN_session1)/N average_session2 = (subject1_session2, subject2_session2,...subjectN_session2)/N . . . average_sessionN = (subject1_sessionN, subject2_sessionN,...subjectN_sessionN/N -
Dockerized Mysql: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I'm working on a Django project locally (on a virtual environment) where I have a Django folder (the one automatically by "startproject") called django-test. Within this folder I have a secrets.py file where I store sensitive data. So this file contains the following variables: mysql_root_password = 'my_root_password' mysql_database = 'my_db' mysql_user = 'my_user' mysql_password = 'my_password' I also have a docker-compose.yml file to bring up a mysql database: services: db: image: mysql:latest restart: always environment: MYSQL_DATABASE: /run/secrets/mysql_database MYSQL_USER: /run/secrets/mysql_user MYSQL_PASSWORD: /run/secrets/mysql_password MYSQL_ROOT_PASSWORD: /run/secrets/mysql_root_password secrets: - mysql_root_password - mysql_database - mysql_user - mysql_password ports: - '3306:3306' expose: - '3306' volumes: - my-db:/var/lib/mysql secrets: mysql_root_password: file: ./django-test/secrets.py mysql_database: file: ./django-test/secrets.py mysql_user: file: ./django-test/secrets.py mysql_password: file: ./django-test/secrets.py volumes: my-db: I was initially able to bring up the container (docker-compose up -d --build) and go into to mysql shell to create the database, the user and grant privileges, using docker exec -it mysql_container mysql -u root -p. However, I had to make some major modifications to my django model, which required to recreate the database. So I did: docker-compose down docker volume ls docker volume rm <my_volume_name> From that moment on I wasn't able to use my db again. I recreated my container (docker-compose … -
Django ManytoMany form with checkboxes: how to keep "checked" and "unchecked" values?
I'm trying to display and use a form that uses a manytomany field, widgetized as checkboxes The problem I'm having is when I view the page, the state of the checkboxes isn't visible (all the checkboxes show as unchecked, but there are related rows in the database for the manytomany relations). What I'd like to do is display an "edit" form with all the correct statuses for the checkboxes (i.e. checked checkboxes for existing manytomany values in the database, unchecked checkboxes for missing values) here's the form declaration: class EditPatientForm(forms.ModelForm): flags = forms.ModelMultipleChoiceField( queryset=PatientFlag.objects.filter(visible_on_edit=True), widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Patient exclude = ('profile_picture','registered_on') fields = "__all__" helper = FormHelper() Every "patient" has some associated "flags" such as "has diabetes" or "has heart problems". I want to display a form with a list of checkboxes so the user can select "has diabetes" as a checkbox, which then gets saved in the database. Here are the two models: class PatientFlag(models.Model): name = models.CharField(max_length=255, null=True) question = models.CharField(max_length=255, null=True) description = models.TextField(null=True) visible_on_create = models.BooleanField( default=True) visible_on_edit = models.BooleanField(default=True) class Patient(models.Model): """Represents a patient""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) flags = models.ManyToManyField(PatientFlag, db_index=True, related_name='patient') Now, when I go and edit the … -
I cant install and use pipenv to create a virtual environment
pip install pipenv Requirement already satisfied: pipenv in c:\users\user\appdata\roaming\python\python312\site-packages (2023.11.15) Requirement already satisfied: certifi in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (2023.11.17) Requirement already satisfied: setuptools>=67 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (69.0.2) Requirement already satisfied: virtualenv>=20.24.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (20.25.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.7) Requirement already satisfied: filelock<4,>=3.12.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.1) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (4.1.0) when I'm trying to install a got this answer pip install pipenv Requirement already satisfied: pipenv in c:\users\user\appdata\roaming\python\python312\site-packages (2023.11.15) Requirement already satisfied: certifi in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (2023.11.17) Requirement already satisfied: setuptools>=67 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (69.0.2) Requirement already satisfied: virtualenv>=20.24.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (20.25.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.7) Requirement already satisfied: filelock<4,>=3.12.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.1) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (4.1.0) I'm trying to get my path but nothing is working like these two tries PS C:\Users\USER> pipenv --venv Fatal error in launcher: Unable to create process using '"C:\Program Files\python.exe" "C:\Users\USER\AppData\Roaming\Python\Python312\Scripts\pipenv.exe" --venv': The system cannot find the file specified. PS C:\Users\USER> pipenv --where Fatal error in launcher: Unable to create process using '"C:\Program Files\python.exe" "C:\Users\USER\AppData\Roaming\Python\Python312\Scripts\pipenv.exe" --where': The system cannot find the file specified. -
Issue when migrating from SQLite to PostgreSQL in Django
I'm trying to migrate from SQLite to PostgreSQL. "makemigrations" works fine, but when I run the "migrate" command, everything gets complicated. Hello, I'm new to using Django, and I'm encountering the following error when trying to migrate from SQLite to PostgreSQL with an new database image 1 When I started the development of the project, I used fields like TimeField in my model. I'm attaching a snippet from my 0001_initial.py. image 2 Later, I realized that I should use time values differently and decided to modify the model to make them of type FloatField. Snippet from my migrations file 0004_alter_test_time_human_and_more.py image 3 I believe I understand that the issue is when I run the 'migrate' command, Django goes through all migration files, and that's where the conflict with PostgreSQL arises. Has anyone faced the same issue? Any help would be greatly appreciated. -
In select2, the values always is a empty string
I have a Python/Django project where I'm trying to add 'select2' to facilitate user search from a list of banks: class BuyerNaturalPersonBankAccountForm(forms.ModelForm): select_bank = MajorBankList( label='Banco', required=False, ) class Meta: model = BuyerBankAccount fields = ( 'name', 'cpf', 'cnpj', 'select_bank', 'bank', 'bank_code', 'agency', 'account', 'account_type', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bank'].required = False self.fields['bank_code'].required = False self.fields['bank'].widget.attrs.update( { 'v-model': 'bank', ':disabled': 'isBankDisabled', } ) self.fields['bank_code'].widget.attrs.update( { 'v-model': 'bank_code', ':disabled': 'isBankDisabled', } ) self.fields['select_bank'].widget = forms.Select( choices=self.fields['select_bank'].choices, attrs={ 'v-model': 'selectedBank', '@change': 'onBankChange', 'data-select2-enabled': True, } ) In my base.html, i have added the select2: var app = new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { street: '', district: '', city: '', state: '', country: '', cpf: '', name: '', mother_name: '', father_name: '', nationality: '', selectedBank: '', bank: '', bank_code: '', bankAccountOwnerName: '', bankAccountCPF: '', birth_date: '', public_person: false, isLoading: false, isPostalCodeFound: true, isCPFFound: true, display_form_address: false, display_form_bank: false, hasError: '{{ error }}', }, beforeMount: function () { this.bank = this.$el.querySelector('#id_form-0-bank').value this.bank_code= this.$el.querySelector('#id_form-0-bank_code').value this.postal_code = this.$el.querySelector('#id_form-0-postal_code').value <script> $(document).ready(function() { $('[data-select2-enabled]').select2({ closeOnSelect: true, theme: "bootstrap" }); }); </script> In the HTML template, I perform these check: computed: { isBankDisabled: function() { return this.selectedBank ==! ''; } }, If I … -
Understanding TTFB Latency in DJango - Seems absurdly slow after DB optimizations even locally
Our team has been undergoing optimizing our Django DRF / Graphene stack for latency we can't quite understand the source of our slowdowns Our Stack: Python 3.11 Django 4.2.8 DRF 3.14.0 Django Graphene 3.1.5 We've done the 'basic' optimizations of implementing prefetch / select related removed all n+1 generated SQL queries And of course, scrounged the internet looking for answers, and saw the ModelSerializer issue posted here: https://hakibenita.com/django-rest-framework-slow Which as I understand it is 'mostly' fixed in the latest Django? We've manually optimized our QuerySets . SQL, and got our worst case SQL latency is around 200ms, most in the 10-100 range. However, our TTFB, is anywhere from 1 to 3 seconds as measured in dev tools on a browser performing a graphiQL query, as well as in our test suites Here are some numbers from GraphiQL Console: One GQL QUery generates 6 optimzied SQL Queries resulting in a response of a 1.4 MB JSon file which has a heavy amount of nested of elements (necessary for our workload) Django Debug Toolbar numbers: 101.9ms for SQL access Chrome Dev Tools 6 SQL Querues 56.44 ms (not sure how it knows this?) 44us to send request 937 ms waiting for server … -
Django Authentication error when connecting to local postgresql
I keep getting this error "password authentication failed for user postgres". I am trying to launch a django server on my computer using WSL (ubuntu 20.04) to my local laptop postgres database. I have my settings set correctly , i am able to connect to the psql from my ubuntu using, so the connection is fine. I set the pg_hba to trust postgres. But when i try to run my django i get the same password authentication error. Please help ,my pg_hba,wsl can connect using psql -U postgres,django settings,error,pg_ident tried this didnt help psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "postgres" (Ubuntu) -
The test database of django return error collation case_insensitive for encoding "UTF8"
I am using django 4.2 and the CICharField was depreciated. And we need to use db_collation in CharField. I create a migration bellow to create collation case_insensitive # Generated by Django 4.2.8 on 2023-12-08 17:11 from django.db import migrations from django.contrib.postgres.operations import CreateCollation def create_collaction(apps, schema_editor): try: CreateCollation( 'case_insensitive', provider='icu', locale='und-u-ks-level2', deterministic=False ) except Exception: pass class Migration(migrations.Migration): dependencies = [ ('module', ''), ] operations = [ migrations.RunPython(create_collaction), ] In the normal database, all things run normal, but when I run python manage.py test, I receive the error: Creating test database for alias 'default'... Got an error creating the test database: database "test_database" already exists Type 'yes' if you would like to try deleting the test database 'test_database', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedObject: collation "case_insensitive" for encoding "UTF8" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/epitacio/workspace/smart-one/manage.py", line 41, in <module> main() File "/home/epitacio/workspace/smart-one/manage.py", line 37, in main execute_from_command_line(sys.argv) File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, … -
Django Custom User model not updating
I have a custom user model with subclassing AbstractUser I want to update it with an Update view models.py: class UserManager(models.Manager): def New_Requests(self): return super.get_queryset().filter(is_seller="I") class User(AbstractUser): nickname = models.CharField(max_length=50,verbose_name="Nick Name",default='User') is_seller_status = ( ('N','Not accepted'), ('I','Investigate'), ('A','Accepted') ) is_seller = models.CharField(default='N',max_length=1,choices=is_seller_status,verbose_name='seller') user_id = models.UUIDField(default = uuid.uuid4,editable = False,unique=True) profile = models.ImageField(upload_to="user_profile",blank=True,null=True) admin_reject_reason = models.TextField(default='Not reviewed yet') views.py: class AccountView(LoginRequiredMixin,UpdateView): model = User form_class = UserProfileForm template_name = "user/profile.html" success_url = reverse_lazy("user:profile") def get_object(self): return User.objects.get(pk = self.request.user.pk) def get_form_kwargs(self): kwargs = super(AccountView, self).get_form_kwargs() kwargs['user'] = self.request.user # Pass 'user' directly to the form return kwargs urls.py: app_name = "user" urlpatterns = [ ... path('profile/',AccountView.as_view(),name='profile'), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` profile.html: {% extends 'user/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">Profile</h1> </div> <div class="col-md-12"> <div class = "card card-primary"> <div class="card-header"> <h3 class = "card-title mb-0 float-left">User Update</h3> </div> <div class="card-body"> <form method="post" action="{% url 'user:profile' %}" enctype="multipart/form-data">{% csrf_token %} <div class="row"> <div class="col-6"> {{ form.username|as_crispy_field }} </div> <div class="col-6"> {{ form.email|as_crispy_field }} </div> <div class="col-6"> {{ form.first_name|as_crispy_field }} </div> <div class="col-6"> {{ … -
Problems with CSRF token in django REST Framework integration with React
I'm doing a website using Django REST Framework as a backend with session authentication, React in the frontend and django-cors-headers to comunicate between the two. Each is served in the same IP adress but in different ports. I've implemented an authentication system using SessionAuthentication and the User model from django. The problem is that when I do post requests to the backend it always returns error 403 although the cors headers config seems to be correct and the csrftoken and X-CSRFToken are included in the headers. Here a part of the frontend responsible for the api calls: import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'x-csrftoken'; axios.defaults.withCredentials = true; export const client = axios.create({ baseURL: "http://127.0.0.1:8000" }); export const Register = (credentials) => { return client.post('/api/register', credentials) } export const Login = (credentials) => { return client.post('/api/login', credentials, {'withCredentials': true}) } And the views.py: @method_decorator(csrf_protect, name='dispatch') class UserRegister(APIView): permission_classes = (permissions.AllowAny,) #authentication_classes = (SessionAuthentication,) def post(self, request): clean_data = custom_validation(request.data) serializer = UserRegistrationSerializer(data=clean_data) if serializer.is_valid(raise_exception=True): user = serializer.create(clean_data) if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) @method_decorator(csrf_protect, name='dispatch') class UserLogin(APIView): permission_classes = (permissions.AllowAny,) #authentication_classes = (SessionAuthentication,) def post(self, request): data = request.data assert validate_username(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if … -
AttributeError 'NoneType' has no attribute 'name' on Django Project
I'll be very gratefull if someone could help me! I'm having some problems when try to access my dashboard page on my django project. The error is saying: AttributeError at /dashboard/ 'NoneType' object has no attribute 'name' Request Method: GET Request URL: http://localhost:8000/dashboard/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'name' ............ My view.py file contains the function "dashboard_view": def dashboard_view(request): ........ plano_atual_usuario, preco_atual, conversas_a_pagar = user.current_user_plan_price_and_conversas_a_pagar(STANDART_PERIOD) numero_de_pedidos = pedidos.count() numero_de_conversas = conversas.count() numero_de_conversas_do_periodo = conversas_do_periodo.count() if numero_de_conversas > 0: taxa_conversao = round((numero_de_pedidos / numero_de_conversas) * 100, 2) else: taxa_conversao = 0.0 dias_para_pagamento = user.days_to_next_payment(STANDART_PERIOD) data_proximo_pagamento = today + timedelta(days=dias_para_pagamento) nome_do_plano = plano_atual_usuario.name -----> Problem is here!!! minimo_conversas_plano_atual = plano_atual_usuario.minimo_conversas limite_conversas_plano_atual = plano_atual_usuario.maximo_conversas valor_por_conversa_do_plano_atual = preco_atual gasto_atual_do_periodo = conversas_a_pagar * valor_por_conversa_do_plano_atual limite_atual_conversas = int(user.conversation_limit_set_by_user) ......... context = { 'user' : user, 'conversas': conversas, 'pedidos' : pedidos, 'dados_clientes' : dados_clientes, 'numero_de_pedidos' : numero_de_pedidos, 'numero_de_conversas' : numero_de_conversas, 'numero_de_conversas_do_periodo' : numero_de_conversas_do_periodo, 'taxa_conversao' : taxa_conversao, 'dias_para_pagamento' : dias_para_pagamento, 'nome_do_plano' : nome_do_plano, 'gasto_atual_do_periodo' : gasto_atual_do_periodo, 'valor_por_conversa_do_plano_atual' : valor_por_conversa_do_plano_atual, 'minimo_conversas_plano_atual' : minimo_conversas_plano_atual, 'limite_conversas_plano_atual' : limite_conversas_plano_atual, 'data_proximo_pagamento' : data_proximo_pagamento, 'conversas_a_pagar' : conversas_a_pagar, 'userIsPremium' : user.userIsPremium(), 'limite_atual_conversas': limite_atual_conversas, 'conversas_per_months': json.dumps(conversas_per_months), 'conversas_per_days': json.dumps(conversas_per_days), } return render(request, 'dashboard.html', context) I already make all migrations … -
Django - 'NoneType' object is not iterable
I have reviewed my code quite a bit and can't understand why this isn't working. My Products have a Category Model to put products in a specific category. I have sorting on the website to link to specific categories. I created a similar model for Special Offers so I can apply a sub category (special offers) and have a product appear either under the original category and the special offer category. Yet even with an identical configuration, just different variable names, I keep getting 'NoneType' object is not iterable. Any ideas what I'm doing wrong? views.py def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None special_offers = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if sortkey == 'special_offers': sortkey = 'special_offers__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'special_offers' in request.GET: speical_offers … -
configuring supervisor Django on Centos/RedHat/Fedora
My django project is (using pwd) at: /usr/share/nginx/myweb.com/here I have cloned my repository name (alvar) I have got the gunicorn file like this GNU nano 7.2 gunicorn_start /bin/bash NAME="estate" DIR=/usr/share/nginx/myweb.com/alvar/ USER=boardsalvaro GROUP=boardsalvaro WORKERS=13 BIND=unix:/usr/share/nginx/myweb.com/alvar/run/gunicorn.sock DJANGO_SETTINGS_MODULE=estate.settings DJANGO_WSGI_MODULE=estate.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- and the added block to the supervisord file like this [program:boards] command=/usr/share/ngingx/myweb.com/gunicorn_start user=boardsalvaro autostart=true autorestart=true redirect_stderr=true stdout_logfile=/usr/share/nginx/myweb.com/logs/gunicorn.log but when I try to reread the supervisord file I get error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/lib/python3.11/site-packages/supervisor/xmlrpc.py line: 560 -
403 Error while uploading file to Azure Blob via Django app, retrieving html output
I'm a student. This is my first time working with Azure or Django in this capacity, so please bear with me. This is for a final project due in a few days. I did not expect app deployment to be so incredibly complicated! I have written a series of Python files that accept an xlsx file via a form, compare the data of that xlsx file to an API, and then generate an html report of the results. The html is stored on an Azure blob and the link is then provided to the user for download. All of this works when I run the app locally (including the Azure blob connection). When I deploy to Azure, the app runs, but blocks the upload of the xlsx file and a nondescript 403 error is returned. I am not really sure what to try next. Sorry if I'm not providing the correct amount of detail, but happy to discuss further. I'll include more details about packages, etc. below Python Packages: Django pandas azure-storage-blob jinja2 requests Other standard Django dependencies I have tried the following to remedy this so far (I am going insane.): -Environment Variables: Configured necessary environment variables in Azure … -
How can I retrieve the Aerodrone model name and code field values correctly?
I'm working on a Django project with two models, Aerodrone and Meteo. I defined a foreign key in the Meteo model to reference the Aerodrone model. However, the foreign key fields in the database are named aerodrone_id and code_aerodrone_id. I want to retrieve the values of the name and aerodrone_code fields from the Aerodrone model in the Meteo model. I wrote the admin part but the code_aerodrone field always retrieves the values of the name field instead of code. Help me solve this problem. Here is the code: class Aerodrone(models.Model): nom = models.CharField(verbose_name="Nom de l'aérodrone", max_length = 150, unique=True) code = models.CharField(verbose_name="Code de l'aérodrone", max_length = 50, unique=True) class Meta: verbose_name_plural = "Aérodromes" def str(self): return self.nom class Meteo(models.Model): id_message = models.ForeignKey(Idmessage,verbose_name="Id du message", on_delete=models.CASCADE) aerodrone = models.ForeignKey(Aerodrone,verbose_name="Nom de l'aérodromes", on_delete=models.CASCADE, to_field="nom", related_name = "meteo_aerodrone_nom") code_aerodrone = models.ForeignKey(Aerodrone,verbose_name="Code de l’aérodromes", on_delete=models.CASCADE, to_field="code", related_name = "meteo_aerodrone_code") id_station = models.CharField(verbose_name="Code de la station", max_length = 50) date_heure = models.DateTimeField(auto_now_add=True, verbose_name="Date et heure") direction_vent = models.CharField(verbose_name="Direction et la force du vent", max_length = 150) visibilite = models.CharField(verbose_name="Visibilité horizontale", max_length = 150) temps_significat = models.CharField(verbose_name="Temps significatif", max_length = 150) nuages_significatif = models.CharField(verbose_name="Nuages significatif", max_length = 150) temperature = models.CharField(verbose_name="Température de l’air sec et du …