Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - setting a model pk to None and saving returns "ValueError: Cannot force an update in save() with no primary key."
I have already figured this out but I could not find an answer to this and will post because somebody might find it helpful. Here is the code that was causing problems: models.py class SModelQuerySet(models.QuerySet): def stubbed_outputs(self): return self.defer("outputs").annotate( has_outputs=models.Case( models.When( models.Q(~models.Q(outputs={}) & models.Q(outputs__isnull=False)), then=True, ), default=False, output_field=models.BooleanField(), ) ) def for_user(self, user): return self.filter(user=user) class SModelManager(models.Manager): def get_queryset(self): return SModelsQuerySet(self.model, using=self._db).stubbed_outputs() def for_user(self, user): return self.get_queryset().for_user(user) class OutputsManager(models.Manager): def get_queryset(self): return super().get_queryset().only("outputs") def for_user(self, user): return self.get_queryset().filter(user=user) class SModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) name = models.CharField(max_length=50) description = models.CharField(max_length=500, null=True, blank=True) inputs = models.JSONField(default=dict) outputs = models.JSONField(default=dict) objects = SModelManager() outputs_objects = OutputsManager() class Meta: verbose_name_plural = "scientific models" db_table = "smodels" managed = False def __str__(self): return self.name views.py class SharedModelViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.SharedModelSerializer @action(detail=True, methods=["post"]) def save(self, request, pk=None): shared_model = self.get_object() model = get_object_or_404( models.SModel.objects.filter(user=shared_model.share_from), pk=shared_model.model_to_share_id, ) model.pk = None model.user_id = shared_model.share_to.id model.save() shared_model.delete() return Response( serializers.SModelSerializer(model).data, status=status.HTTP_200_OK ) When this view was trying to save, I was getting an error like this: "ValueError: Cannot force an update in save() with no primary key." I could not figure this out and it was working a few weeks ago. -
Django, DRF + React, Axios. Error 403 Forbidden
Sorry for my english speaking skills. I have such a problem, I make a website using django, drf and react with axios. So i have this code: models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class AppUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('An email is required.') if not password: raise ValueError('A password is required.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password=None): if not email: raise ValueError('An email is required.') if not password: raise ValueError('A password is required.') user = self.create_user(email, password) user.is_superuser = True user.save() return user class AppUser(AbstractBaseUser, PermissionsMixin): user_id = models.AutoField(primary_key=True) email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=50) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AppUserManager() def __str__(self): return self.username serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model, authenticate from django.core.exceptions import ValidationError UserModel = get_user_model() class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = '__all__' def create(self, clean_data): user_obj = UserModel.objects.create_user(email=clean_data['email'], password=clean_data['password']) user_obj.username = clean_data['username'] user_obj.save() return user_obj class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() ## def check_user(self, clean_data): user = authenticate(username=clean_data['email'], password=clean_data['password']) if not user: raise ValidationError('пользователь не найден') return user class UserSerializer(serializers.ModelSerializer): class Meta: model = … -
recursive dependency involving fixture (django, pytest)
Just got started with pytest, can't figure out what seems to be the problem here. Fixtures work fine in other test files. Can't figure out what dependancies are triggered partial error msg: E recursive dependency involving fixture 'author_client' detected > available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _template_string_if_invalid_marker, admin_client, admin_user, async_client, async_rf, author, author_client, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, comment, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, form_data, homepage_news, live_server, mailoutbox, monkeypatch, news, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, second_comment, settings, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db > use 'pytest --fixtures [testpath]' for help on them. D:\Dev\django_testing\venv\lib\site-packages\_pytest\fixtures.py:353 ========================================================================================================= short test summary info ========================================================================================================== ERROR news/pytest_tests/test_routes.py::test_pages_availability[/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/login/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/signup/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/logout/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/news/1/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/edit_comment/1/-author_client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/delete_comment/1/-author_client-HTTPStatus.OK] test outtake: COMM_ID = 1 NEWS_ID = 1 HOME_URL = reverse('news:home') LOGIN_URL = reverse("users:login") SIGNUP_URL = reverse('users:signup') LOGOUT_URL = reverse('users:logout') NEWS_URL = reverse('news:detail', args=(NEWS_ID,)) COMM_EDIT_URL = reverse('news:edit', args=(COMM_ID,)) COMM_DELETE_URL = reverse('news:delete', args=(COMM_ID,)) ANONIMOUS_USER = pytest.lazy_fixture('client') AUTH_USER = pytest.lazy_fixture('admin_client') AUTHOR_USER = pytest.lazy_fixture('author_client') @pytest.mark.django_db @pytest.mark.parametrize( 'url, client, response_status', ( (HOME_URL, ANONIMOUS_USER, HTTPStatus.OK), (LOGIN_URL, ANONIMOUS_USER, HTTPStatus.OK), (SIGNUP_URL, ANONIMOUS_USER, HTTPStatus.OK), (LOGOUT_URL, ANONIMOUS_USER, HTTPStatus.OK), (NEWS_URL, ANONIMOUS_USER, HTTPStatus.OK), (COMM_EDIT_URL, AUTHOR_USER, … -
Datepicker not highlighting specified dates
I am trying to highlight an array of dates in a date picker, however i cannot seem to get it working. I know my jQuery is loading in the browser. Any and all help appreciated. class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('booking_date', 'booking_time', 'number_attending') widgets = { 'booking_date': DateInput(attrs={'type': 'date', 'id': 'datepicker'}) } script.js var dates = ['14-10-2023', '15-10-2023', '16-10-2023']; $('#datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('dd-mm-yyyy', date); if ($.inArray(string, dates) == -1) { return [true, 'highlighted-date']; } else { return [true, '']; } }, }); css .highlighted-date { color: red; } script tags <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous" ></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js" integrity="sha256-6XMVI0zB8cRzfZjqKcD01PBsAy3FlDASrlC8SxCpInY=" crossorigin="anonymous" ></script> -
Django | How to query foreignkey and return only one object on a specific key (prefetch)
I am having a headache writing a query :slight_smile: That’s my models: `class Mission(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE, related_name="missions") start_dt = models.DateTimeField(null=False) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) @cached_property def timezone(self) -> datetime.tzinfo: timezone_str = get_tz(float(self.longitude), float(self.latitude)) return pytz.timezone(timezone_str)` and `class Machine(models.Model): name = models.CharField(max_length=12, null=False, unique=True) created_at = models.DateTimeField(_("created at"), auto_now_add=True) updated_at = models.DateTimeField(_("updated at"), auto_now=True)` I want to make a query with all the machines and for each machine a last_mission field where I have my last mission. like: machine.last_mission.timezone ... .I am completely stuck doing it with the django ORM. that’s my postgres query that doesn’t do exactly what I want as there is no last_mission key and not the model property. Thanks a lot for you help :slight_smile: select * from machines_machine machine, missions_mission mission where (mission.machine_id, mission.start_dt) in (select mission.machine_id as machine_id, Max(mission.start_dt) as start_dt from missions_mission mission group by mission.machine_id order by mission.machine_id) -
django, how to delete all the sessions per user
I have the below config in settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" So, we are using cache for session management, but not database. There is already existing solution for delete from DB Most optimized way to delete all sessions for a specific user in Django? but if session is cache, do we have a good way to delete user sessions by user name? Thanks in advance. I did not find a proper way to find the session details based on user name, from django code, I see cache key is created based on some random key, so not keyed to user name, so not sure how to achieve this? -
learning Django+Vite+Vue
Today, I have some reflections on learning Django+Vite+Vue. At first, I didn't understand why there were templates in Django but they weren't needed. Later on, I gradually understood that it was possible to simply use view and route as the backend and use Ajax and other technologies to obtain data. However, I didn't understand why I needed to use the django-vite package to merge the Vue project with Django. What were the advantages of this approach. Can't we directly obtain the data in the Vue project by visiting the website -
Merge multiple database table lines into one
Note: I am currently developing an application in Django using SQLite as my database, but I'm planning to migrate to IBM DB2 later, so a generic solution is preferred. Problem statement: I would like to merge rows in a parent table, that will update foreign values in children tables. I am looking for a generic solution that has the best DB practices. If a solution specific to Django models is achievable, it is also valid for solving the problem. Example: Suppose I have two artists in table artist, each one with one song each: PRAGMA foreign_keys = ON; CREATE TABLE artist( artistid INTEGER PRIMARY KEY, artistname TEXT ); CREATE TABLE track( trackid INTEGER PRIMARY KEY, trackname TEXT, trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE ); insert into artist(artistid, artistname) values (1, 'Prince'); insert into artist(artistid, artistname) values (2, 'The Artist (Formerly Known as Prince)'); insert into track(trackid, trackname, trackartist) values (1, 'Purple Rain', 1); insert into track(trackid, trackname, trackartist) values (2, 'Dolphin', 2); artist | artistid | artistname | |:-------- |:------------------------------------- | | 1 | Prince | | 2 | The Artist (Formerly Known as Prince) | track | trackid | trackname | trackartist | |:------- |:----------- |:------------ | | … -
Python Django + postgresSQGl problem with login function
my problem it's problem with authenticate login. My code: class UsersPass(models.Model): id_user = models.IntegerField(null=False,primary_key=True) username = models.CharField(max_length=50) password = models.CharField(max_length=50)` views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) print('haslo',password) if user: login(request, user) return redirect('main_view') else: return HttpResponse("Account not active or invalid login details") else: return render(request, 'main.html', {})` and urls.py path("",views.index,name='index'), path("main/",views.main_view, name='main_view'), path('login/', views.user_login, name='user_login'), Password and login are correct get from database. Print showing correct password. I don't have warning in console, but login function not working. Every time login ending incorrect with message "Account not active or invalid login details". I don;t know where is problem... I checked the connection to the database many times, changed passwords and logins, regardless of whether I entered the correct data or not, I could not log in. -
django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist or multiple primary key for table is not allowed
Django4 on Postgres14. Newest version 2023 nov. this bug has been troubling me all day, I scanned though django GitHub issues on django projects research whole lot on SO and other FQA platforms asked gpt did not find a helpful solution. Hence write a guild that may facilitate visitor in future. -
Django application can access DB models but Pytest can't (invalid object name)
I'm using Pytest to write unit tests for a Django application. The application itself has no issue working with its databases, and it can read and write data completely fine with any method. When testing, database access using a cursor object works totally fine as well. However, whenever I try to access one of the databases in a test via a model object, I get this error: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name '<table I'm trying to access>'. (208) (SQLExecDirectW)") Here's a minimal test that causes this issue - it produces the error above, using the table name Students_with_Holds: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access(self): testobj = StudentsWithHolds.objects.using('Coursematch').create( person_id_number = 'testPIDnum', hold_type_code = 'test' ) assert testobj.person_id_number == 'testPIDnum' assert testobj.hold_type_code == 'test' Attempting to perform the exact same procedure using a cursor object, as shown below, does not cause the issue: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access_cursor(self): with connections['Coursematch'].cursor() as cursor: insert_query = """ INSERT INTO Coursematch.dbo.Students_with_Holds (person_id_number,hold_type_code) VALUES ('testPIDnum','test') """ cursor.execute(insert_query) check_query = """ SELECT person_id_number,hold_type_code FROM Coursematch.dbo.Students_with_Holds WHERE person_id_number = 'testPIDnum' """ cursor.execute(check_query) assert cursor.fetchone() == ('testPIDnum','test') Any suggestions on how to stop this from happening? I've made sure that my models are all migrated, and that … -
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed when i want to connect to django database container from celery task
I'm working on a django application with docker. I have a celery container which uses another redis container as brocker and backend. My postgres database is also in another container. Everything works well. But when I try to perform database operations in tasks, celery returns me: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed here is my docker-compose version: '3' services: app: container_name: ozangue build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./electron:/electron - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=xxxxx - DB_USER=xxxxxx - DB_PASS=ozanguedb@2022 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db - redis celery: container_name: celery-worker restart: always build: context: ./celery command: celery -A electron worker -l info -E depends_on: - app - redis redis: image: redis:7.0.5-alpine container_name: redis expose: - 6379 db: image: postgres:13-alpine container_name: database environment: - POSTGRES_DB=xxxxxxxx - POSTGRES_USER=xxxxxxx - POSTGRES_PASSWORD=xxxxxxxx celery.py os.environ.setdefault("DJANGO_SETTINGS_MODULE","electron.settings") app = Celery('electron', broker='redis://redis:6379/0',backend='redis://redis:6379/0') app.config_from_object("django.conf:settings",namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings CELERY_BROKER_URL = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Libreville' How to solve this problem please? -
How do I filter requests objects by date range in Django?
I've got a function for looping like this: saved_date = request.GET.get('date') start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') if saved_date is not None: queryset = Contact.objects.filter( createdAt__istartswith=saved_date).values_list('phone', flat=True) elif start_date and end_date is not None: queryset = Contact.objects.filter( createdAt__range=[start_date, end_date]).values_list('phone', flat=True) So, I need to filter the objects by a date range, including the end date. How do I filter all the objects that have a date between start_date and end_date? -
Postman CLI collection run not using cookieJar correctly
I'm trying to use postman with a Django API and I'm writing some tests for the API. However I'm encountering an issue with postman when run through the console using postman collection run <collection_id>. I'm using Postman's cookieJar to set and get cookies between requests but I have two of them and it is only adding one when running using the command. This behaviour doesn't happen when run through postman itself. Here's the test script that runs the code for adding the cookies: console.log(pm.request) if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "GET"){ const cookieJar = pm.cookies.jar() let temp = pm.response.headers; let temp2 = temp.filter(item => item["key"]=== "Set-Cookie") let temp3 = temp2[0].value let temp4 = temp3.slice(10,42) cookieJar.set("localhost", "csrftoken", temp4); console.log("Ran tests script") } if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "POST"){ const cookieJar = pm.cookies.jar() pm.response.forEachParent(console.log(pm.response)) let temp5 = pm.response.headers; let temp6 = temp5.filter(item => item["key"]=== "Set-Cookie") let temp7 = temp6[0].value let temp8 = temp6[1].value let temp9 = temp7.slice(10,42) let temp10 = temp8.slice(10,42) console.log(temp9) console.log(temp10) cookieJar.set("CLI1", "csrftoken", temp9); cookieJar.set("CLI2", "sessionid", temp10); } The output for the console.logs near the bottom do show that there are values, even when run through the CLI but for some reason the second cookie isn't set … -
Implement of dependent dropdown of district and branches in an application form created using django models and forms
I created a model of district and branch and application form .In this I used FOreignkey for branch and district in application form model.I want dependent dropdown of district and branch in which if we select one district it's dependent branch would be shown in the branch field.how it is possible I added 5 district to admin.but when I add branches to admin nothing happen in display html page.please give the way to implement dependent dropdown using foreign key and in forms what can I do.please give the urls and views also -
django migration with multiple languages
It seems makemigrations command is affected by django language (django.mo, django.po etc). I have two projects. One is upstream and the other origin is forked version of upstream. Upstream's LANGUAGE_CODE is ko-kr and that of origin is en. In upstream when I run makemigrations, provided that I have django.mo file under locale/ko/LC_MESSAGES no changed detected. Now I head to origin whose language is en. I have locale/en/LC_MESSAGES/django.mo file. When I run makemigrations I see a long list of migration files. But with a close look, all of them are about changes of verbose_name, choices label etc. When one has django project that supports more than one languages, how does one make it recognise its language and prevent it from making unnecessary migration files? -
'RecursionError: maximum recursion depth exceeded' when I try to run a server
I'm fairly new to django and webdev and I've run different servers before, but for some reason, whenever I try to run a server for this project, I get this: File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\urls\resolvers.py", line 496, in check messages.extend(self._check_custom_error_handlers()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\urls\resolvers.py", line 514, in _check_custom_error_handlers signature = inspect.signature(handler) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 3327, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 3071, in from_callable return _signature_from_callable(obj, sigcls=cls, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 2500, in _signature_from_callable obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 774, in unwrap while _is_wrapper(func): ^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 768, in _is_wrapper return hasattr(f, '__wrapped__') and not stop(f) ^^^^^^^ RecursionError: maximum recursion depth exceeded there's a lot more text before this, but I figured that'd be too much to post here. I should point out that i recently did a system reset on my pc and this is my first django code since then. Any help at all would be appreciated tried to run a server, expected a server to run like it normally would, but got a recursion error instead -
Is it possible to send file and data in same POST request using python request library?
I want to send file as well as data in same POST request. is it possible? I tried with python request library but ended up receiving either file or data but not both at the same time. import requests files = { 'upload_file': open('creds.txt','rb') } values = { "collection_name": "detete-test-1", "source": { "data": { "data1": "some random string" } } } url = 'http://localhost:8000/v1/source/test' r = requests.post(url, json=values, files=files) print(r) Tried above code but i was just receiving ImMemoryUploadedFile object in django not the data. -
UnboundLocalError at /create-assignment/ATMser cannot access local variable 'context' where it is not associated with a value
I have the blow view def assign_item_view(request, pk): item = Item.objects.get(Serial_no=pk) if request.method == "POST": form = AssignmentForm(request.POST, instance=item) if form.is_valid(): form.save() return HttpResponseRedirect('/user') else: form = AssignmentForm(instance=item) context = {"item": item,"form": form} # move this line here return render(request, "workshop/Add_assignment.html", context) `def assign_item_view(request, pk): item = Item.objects.get(Serial_no=pk) if request.method == "POST": form = AssignmentForm(request.POST, instance=item) if form.is_valid(): form.save() return HttpResponseRedirect('/user') else: form = AssignmentForm(instance=item) context = {"item": item,"form": form} # move this line here return render(request, "workshop/Add_assignment.html", context)` I got the below Erro UnboundLocalError at /create-assignment/ATMser cannot access local variable 'context' where it is not associated with a value -
Intermittent Character Encoding Issue with Django, Celery, and SendGrid
I've been working with a setup that uses Django alongside Celery for dispatching emails, and we've integrated SendGrid for this purpose. However, I've come across a peculiar issue that I hope someone might shed some light on. Sometimes, when sending out emails, characters with diacritics, specifically "ì", are being displayed as another character, in this case, "ě". I've double-checked and ensured that all software configurations are set to utf-8 encoding, but this inconsistency persists. Has anyone encountered a similar issue or have any suggestions on how to debug or fix this? Example: "Martedě" instead of "Martedì" Martedě" instead of "Martedì The templates are saved in utf-8 encoding html files. This is the code used to send emails: message = render_to_string( "emails/booking_canceled/cliente_to_client.html", { "first_name": booking.customer_first_name, # ... }, ) email = EmailMessage( subject=subject, body=message, from_email=DEFAULT_FROM_EMAIL, to=[booking.customer_email], headers={"Content-Type": "text/html; charset=UTF-8"}, ) email.content_subtype = "html" email.send() logger.info( "[booking_code: %s][customer_email: %s] Sent.", booking.code, booking.customer_email, ) Thank you in advance for any assistance! -
Django - NoReverseMatch (admin panel)
I wrote a function to display a button in the admin panel to parse a file and save questions to the database. Here's a part of the views.py: def upload_questions_view(request): blocks = Blocks.objects.all() if request.method == 'POST': file = request.FILES.get('questions_file') block_id = request.POST.get('block') block = Blocks.objects.get(id=block_id) if file: try: parsed_data = parse_excel_survey(file.temporary_file_path()) for data in parsed_data: if data.type == "ask": ask = Asks( position=data.cl1, block=block, ask=data.question, important=data.cl3, answerable=data.answerable, multiplier=data.cl5, ) ask.save() messages.success(request, 'Data uploaded!') except Exception as e: messages.error(request, f'Error: {e}') else: messages.error(request, 'File error.') return redirect('admin:main_asks_changelist') context = { 'blocks': blocks } return render(request, 'admin/upload_questions.html', context) Here's the change_list_template.html: {% extends "admin/change_list.html" %} {% load i18n %} {% block object-tools-items %} <li> <a href="{% url 'admin:upload_questions' %}" class="addlink"> {% trans "Upload Excel" %} </a> </li> {{ block.super }} {% endblock %} Here's a part of admin.py: class AsksAdmin(admin.ModelAdmin): inlines = [CriteriesInline] list_filter = ('block', 'ask', 'position', 'important', 'multiplier') list_display = ('block', 'ask', 'position', 'important', 'multiplier') change_list_template = 'admin/change_list_with_upload.html' def get_urls(self): urls = super().get_urls() custom_urls = [ path('upload_questions/', self.admin_site.admin_view(upload_questions_view), name='upload_questions'), ] return custom_urls + urls def upload_questions(self, request): return redirect('admin:upload_questions') upload_questions.short_description = "Download Excel" actions = [upload_questions] A button to upload files appeared in the admin panel, but there's an … -
Django channels using RedisPubSubChannelLayer fails to receive
I was testing RedisPubSubChannelLayer for a simple send/receive, but the test fails using pytest. (it passes with RedisChannelLayer) Test class class TestRedis(TestCase): # test if RedisChannelLayer communicates async def test_channels_send_receive(self): channel_name = '45jfngoegnolkmlrmbhrfmh' channel_layer = channels.layers.get_channel_layer() payload = {'type': 'hello'} await channel_layer.send(channel_name, payload) print(f"channel_layer.send done") result = await channel_layer.receive(channel_name) print(f"channel_layer.receive done") self.assertEqual(payload, result) Would you help me understand what I'm doing wrong? If I simply change "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer" to "BACKEND": "channels_redis.core.RedisChannelLayer" the test passes, but otherwise, only "channel_layer.send done" prints and hangs on receive I'm using Ubuntu 22.04.3 LTS python 3.10.12, redis_version:6.0.16 channels-redis==4.1.0 Django==4.2.4 channels==4.0.0 pytest==7.4.2 pytest-asyncio==0.21.1 pytest-django==4.5.2 -
build API for support pagination and non-paginate on django rest framework
As I work on Django-rest-framework. I want the API to support dynamic pagination. For example, if user need pagination they can use an endpoint /api_url?offset=0&limit=10(should return with the format that can let the user know the current page and have the next page or not) and if they don't want pagination they just request without params /api_url. I need it to work with django_filters so it won't make many requests to SQL. I expect to get solition or sample code to about this problem. -
Check_password doesn't work in my Django login system
I am trying create login system when user signup it register successfully users data in database when user signin, the check_password method not work it wil give the else statement meassage Like 'password mismatch'. Can anyone help me to find the answer thankyou in advance I am also used built-in authenticate funtion to authenticate the use but it is also not work from django.http import HttpResponse from django.contrib import messages from django.shortcuts import render from.forms import loginform from.models import Logindata import re import mysql.connector from django.contrib.auth.hashers import make_password,check_password def signin(request): if request.method=='POST': username=request.POST.get('Username') password=request.POST.get('Password') try: user=Logindata.objects.get(Username__contains=username) except Logindata.DoesNotExist: return HttpResponse(f" login failed") if user.check_password(password) : return HttpResponse('login successful') else: return HttpResponse("password mismatch") return render(request,'Signin.html') def signup(request): if request.method=='POST': user=loginform(request.POST) if user.is_valid(): username=user.cleaned_data['User'] password=user.cleaned_data['Password'] Repassword=user.cleaned_data['ConfirmPassword'] mydb=mysql.connector.connect(host='localhost',user='root', password='',database='loginststem') cursordb=mydb.cursor() sql='select*from loginapp_logindata where BINARY Username=%s' cursordb.execute(sql,[(username)]) Result=cursordb.fetchone() if Result: messages.error(request,"Username already exists") return render(request,'Signup.html',{'form':user}) if len(password)==8: if re.search('[A-Z]',password): if re.search('[a-z]',password): if re.search('[0-1]',password): if password==Repassword: Logindata.objects.create(Username=username, Password=make_password(password)) messages.success(request,'your are Register succesfully') return render(request,'Signin.html',{'form':user}) else: messages.error(request,'Pasword Must be Same') return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one Numeric value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one lowercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one uppercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request," password must be 8 characters") return render(request,'Signin.html',{'form':user}) else: user=loginform() return render(request,"Signup.html",{'form':user}) … -
pylint_django "Instance of 'ForeignKey' has no ... member"
I'm working on a project in python with django and recently I decided to modify the way the models were stored in one of the apps. With the help of django documentation, I deleted the models.py file and created a models folder in which I put all my models in files and created a _init_.py file in which I import all my models. This solution works but now pylint no longer seems to understand ForeignKeys. this is my app tree: apps myapp models _init_.py mymodel.py mymodel2.py if i run pylint i can see some E1101. let's take an example: i have a model subnet in subnet.py: class Subnet(models.Model): def __str__(self): return self.nom + "(" + self.cidr + ")" net = models.ForeignKey("Network", on_delete=models.CASCADE, related_name="subnets") def get_parent_cidr(self): return self.net.cidr this model have a reference to the network models in network.py: class Network(models.Model): def __str__(self): return self.company.name + " - " + self.nom + " - " + str(self.cidr) cidr = models.CharField(max_length=18) this network object have a cidr field, all seems to be fine but when i run pylint with the pylint_django plugin, this one send me an error: project/apps/myapp/models/subnet.py:74:15: E1101: Instance of 'ForeignKey' has no 'cidr' member (no-member) What did I do …