Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show comment on blogpost with slug instead of pk
I want to show the comment underneath an article, but I use a slug instead of a pk. I got the following error: IntegrityError at /blogpost-2/comment/ NOT NULL constraint failed: blog_comment.post_id This is my code: #models.py `class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name)` #views.py `class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = "add_comment.html" #fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('blog')` #urls.py `from django.urls import path from . import views from .views import BlogView, ArticleView, CategoryView, AddCommentView urlpatterns = [ path('<slug:slug>', ArticleView.as_view(), name='blogpost'), path('blog/', BlogView.as_view(), name='blog'), path('categorie/<str:cats>/', CategoryView, name='category'), path('<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'), ]` #template add_comment.html `{% extends 'base.html' %} {% load static %} {% block content %} <h1>Voeg een reactie toe..</h1> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary">Voeg toe</button> </form> </div> {% endblock %}` I tried this code, but doesn't work... def form_valid(self, form): form.instance.post_slug = self.kwargs['slug'] return super().form_valid(form) -
Azure webapp doesn't start and logs not showing
i Just deployed a Django app from Azure Devops Pipeline to an Azure webapp, the Pipeline runs fine, but it shows an error when try access using web browse: "Application Error" . The logs from bash shell don't tell much neither. [![enter image description here][2]][2] The Stream logs shows that the app tries to start but then stops. 2023-10-11T19:18:15.793Z INFO - 3.10_20230810.1.tuxprod Pulling from appsvc/python 2023-10-11T19:18:16.054Z INFO - Digest: sha256:6e7907b272357dfda9a8c141b01fc30851ffc4448c6c41b81d6d6d63d2de0472 2023-10-11T19:18:16.064Z INFO - Status: Image is up to date for mcr.microsoft.com/appsvc/python:3.10_20230810.1.tuxprod 2023-10-11T19:18:16.150Z INFO - Pull Image successful, Time taken: 0 Minutes and 1 Seconds 2023-10-11T19:18:16.450Z INFO - Starting container for site 2023-10-11T19:18:16.451Z INFO - docker run -d --expose=8000 --name webapp-firma-backend_1_9d3d260f -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=webapp-firma-backend -e WEBSITE_AUTH_ENABLED=False -e PORT=8000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=webapp-firma-backend.azurewebsites.net -e WEBSITE_INSTANCE_ID=0a01d13b0c74e2087a0a20c4078e93f91439134653f92861a8deef4a0aa726ab -e HTTP_LOGGING_ENABLED=1 -e WEBSITE_USE_DIAGNOSTIC_SERVER=False appsvc/python:3.10_20230810.1.tuxprod sh start.sh 2023-10-11T19:18:20.351Z INFO - Initiating warmup request to container webapp-firma-backend_1_9d3d260f for site webapp-firma-backend 2023-10-11T19:18:19.698796823Z _____ 2023-10-11T19:18:19.698834524Z / _ \ __________ _________ ____ 2023-10-11T19:18:19.698839824Z / /_\ \\___ / | \_ __ \_/ __ \ 2023-10-11T19:18:19.698843324Z / | \/ /| | /| | \/\ ___/ 2023-10-11T19:18:19.698846424Z \____|__ /_____ \____/ |__| \___ > 2023-10-11T19:18:19.698849924Z \/ \/ \/ 2023-10-11T19:18:19.698853024Z A P P S E R V I C E O N L I N … -
Django form bringing unselected data
Am creating a django form that enables me enter student marks but it works best for the start and it then brings students I didn't select . The project that collects student marks but am trying to make a form that inputs marks after selecting the students on one form but this works well before I enter any marks but it then brings all the students whose marks I've already entered plus those I select for new entries. In my views.py I have that @login_required def create_result(request): students = Student.objects.all() if request.method == "POST": # after visiting the second page if "finish" in request.POST: form = CreateResults(request.POST) if form.is_valid(): subjects = form.cleaned_data["subjects"] session = form.cleaned_data["session"] term = form.cleaned_data["term"] students = request.POST["students"] results = [] for student in students.split(","): stu = Student.objects.get(pk=student) if stu.current_class: for subject in subjects: check = Result.objects.filter( session=session, term=term, current_class=stu.current_class, subject=subject, student=stu, ).first() if not check: results.append( Result( session=session, term=term, current_class=stu.current_class, subject=subject, student=stu, ) ) Result.objects.bulk_create(results) return redirect("Results:new-results") # after choosing students id_list = request.POST.getlist("students") if id_list: form = CreateResults( initial={ "session": request.current_session, "term": request.current_term, } ) studentlist = ",".join(id_list) return render( request, "Results/resultsentry1.html", {"students": studentlist, "form": form, "count": len(id_list)}, ) else: messages.warning(request, "You didnt select any … -
Django channels with react axios runs twice
I use django channels and react to create a chat app. I have two models. Message and chat. Message just contains each message users have send, and chat contains more information about the chat of 2 users. When a new message is created I display it on screen and then create a new model of message with axios. After that I also create a chat one. My problem is that sometimes 2 messages are created at one time even if only one is displayed on the screen. I have noticed that react doesn't re-render so I don't know what causes this. Also it is inconsistent, some times only one is made and when the other user writes a message they start doubling. useEffect(()=> { let ran = true; chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <div id={data.sendby.username == currentUser[0]?.username ? 'ownUser' : 'elseUser'}><p ref={oneRef} data-username={data.sendby == currentUser[0]?.username ? 'ownUser' : 'elseUser'}>{data.message}</p></div>]) axios.post('http://127.0.0.1:8000/create_message/', { headers: { 'Content-type': 'application/json' }, message:data.message }).then(res=>{ const formData = new FormData() formData.append('chat_room',roomName) formData.append('sender',JSON.stringify(data.sendby)) console.log(formData.forEach(el => console.log(el))) axios.post('http://127.0.0.1:8000/create_chat/', formData, { headers: { 'Content-type': 'multipart/form-data' } }).then(res=>console.log(res)) }) } } return () => { ran = false; }; },[currentUser]) … -
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 …