Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
module 'django.db.backends.utils' has no attribute 'typecast_decimal'
When I run python manage.py inspectdb --database=sybase_database it ends with error message: Database.register_converter(Database.DT_DECIMAL, util.typecast_decimal) AttributeError: module 'django.db.backends.utils' has no attribute 'typecast_decimal' $ pip freeze certifi==2021.10.8 chardet==3.0.4 defusedxml==0.7.1 Django==2.2.4 django-allauth==0.40.0 django-bootstrap-form==3.4 django-bootstrap3==15.0.0 django-crispy-forms==1.7.2 django-crudbuilder==0.2.7 django-debug-toolbar==1.10.1 django-filter==2.2.0 django-mssql-backend==2.8.1 django-tables2==2.4.1 idna==2.8 importlib-metadata==2.1.1 oauthlib==3.1.1 pyodbc==4.0.32 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2021.3 requests==2.21.0 requests-oauthlib==1.3.0 six==1.16.0 sqlany-django==1.13 sqlanydb==1.0.11 sqlparse==0.4.2 urllib3==1.24.3 zipp==3.6.0 Ubuntu 18.04 -
django's validate_no_broken_transaction fails for query that works fine in console
I use django 2.2.25 with mysql 8.0.27. From time to time I have such error in my logs: Traceback (most recent call last): File "/home/v/django/django_projects/v/tele/bot.py", line 139, in tmp res = f(bot, update, *args, **kwargs) File "/home/v/django/django_projects/v/tele/bot.py", line 401, in answer_action finalize_game(bot, update, prize, prefix=text) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "<string>", line 2, in finalize_game File "/home/v/.local/lib/python3.8/site-packages/retry/api.py", line 73, in retry_decorator return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter, File "/home/v/.local/lib/python3.8/site-packages/retry/api.py", line 33, in __retry_internal return f() File "/home/v/django/django_projects/v/tele/bot.py", line 341, in finalize_game if len(users) == 0: File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __len__ self._fetch_all() File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/v/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. My code is: @atomic @retry(tries=3, delay=1) def finalize_game(bot, update, prize, prefix=None): state = game_states.get(update.message.chat.id, None) uid … -
Frontend and backend separation **settings** using django rest framework and sveltekit
I am building an app using django rest framework and sveltekit. What should I do so that the frontend can fetch backend api properly? More details: I can 'GET, POST' api properly using PostMan. I can 'GET' api properly using fetch. I Can not 'POST' api properly using fetch: Here is my attempt (More code details in the last.): the very beginning: frontend: fetch('http://127.0.0.1:8000/blogs/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, about, cover, }), }) backend: ALLOWED_HOSTS = [] I the this error in my browser console: Access to fetch at 'http://127.0.0.1:8000/blogs/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. And this log of django: [14/Jan/2022 17:11:46] "OPTIONS /courses/ HTTP/1.1" 200 0 Setting up cors: frontend: fetch('http://127.0.0.1:8000/blogs/', { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, about, cover, }), }) I get this error in my browser: POST http://127.0.0.1:8000/blogs/ net::ERR_ABORTED 415 (Unsupported Media Type) change media Type: frontend const data = new FormData(); … -
Using autocomplete feature in Django admin without showing related model in the left sidebar
My main model ObjetArchi has several related models, connected through foreign keys. To avoid loading a long list of values and scrolling infinitely through it, I'm using the autocomplete feature in the ObjetArchi admin interface. Related models have to be registered for the autocomplete to work, but I'd like them not to be shown in the left sidebar. Is there a way to hide them while still being able to edit them through the main model if needed? -
How to get another data from MS AD by attributes - django
I use modul django-python3-ldap for authentication user from Microsoft Active Directory. I need to parse another data from attributes in AD except mail, sAMAccountname, givenName, sm. Do you know how to do this? LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", "telephone": "mobile", # for example this } Thanks. -
webbrowser does not open links in the same window if it's incognito
I'm using Django to open some links in the same window, using webbrowser. I wrote a custom action like this : @admin.action(description='Open') def open(modeladmin, request, queryset): for app in queryset.filter(auto_open=True).reverse(): webbrowser.open(app.link, new=0, autoraise=True) This is what happens when I check which links to open and click on Go : Non Incognito Window : Works fine, links are opened in the same window Incognito Window : Does not work, links are opened in a non incognito window Is this browser specific ? Because I'm using Chrome and I don't know if I have to override settings or not -
how to collect data back to request class in celery Django
i have create function in views.py and in function serializing objects to json after that passing this data to celery task but i have problems with collect data back to request class. That is, I can't collect the data back in json to request class, Because I have to pass this request class to another function by celery task views.py def create(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) request_data = { "crm_id": request.JWT.crm_id, "crm": None, "crmuser": request.JWT.crmuser.id, "crm_users": None } matching_fields = serializer.validated_data['matching_fields'] import_data.delay(request_data, instance.id, matching_fields) task.py @shared_task def import_data(request_data, instance_id, matching_fields): instance = ImportRecord.objects.get(id=instance_id) request_data['crm'] = Crm.objects.get(id=request_data['crm_id']) request_data['crmuser'] = CrmUser.objects.get(id=request_data['crmuser']) request_data['crm_users'] = CrmUser.objects.all().filter(crm_id=request_data['crm_id']) helper = ImportData(matching_fields, instance, request) helper.import_data() how can i back to collect json request_data to request class -
I'm getting Application Error while hosting Django project on Heroku
I get the 'Application Error' After the successfully deployed my project. I don't know why plz help me. It's the first time that I'm hosting my project on Heroku I've never done that before. these are logs details: » Warning: heroku update available from 7.53.0 to 7.59.2. 2022-01-13T19:10:37.632487+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:37.661207+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=9c5a41e9-725b-4b83-8bf9-81c074c9dc03 fwd="103.69.113.112" dyno=web.1 connect=0ms service=49ms status=400 bytes=372 protocol=https 2022-01-13T19:10:38.425281+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:38.425627+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:38.427129+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=f3370395-81fe-4094-83b6-599e92fb48a1 fwd="103.69.113.112" dyno=web.1 connect=0ms service=10ms status=400 bytes=372 protocol=https 2022-01-13T19:10:39.113258+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:39.113745+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:39.115496+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=f15ce14d-9758-4dd6-83ec-6cb9f23adf13 fwd="103.69.113.112" dyno=web.1 connect=0ms service=15ms status=400 bytes=372 protocol=https 2022-01-13T19:10:41.921449+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:41.921960+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:41.934548+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=b4c7c6da-8cdc-4c83-abf6-ec654b6c4116 fwd="103.69.113.112" dyno=web.1 connect=0ms service=22ms status=400 bytes=372 protocol=https 2022-01-13T19:26:17.883688+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:26:17.883955+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:26:17.885404+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=915ef507-e5cd-41bd-980c-2d1fd73237bb fwd="103.69.113.112" dyno=web.1 connect=0ms service=27ms status=400 bytes=372 protocol=https 2022-01-13T19:26:20.551449+00:00 app[web.1]: … -
AWS UnicodeDecodeError 'utf-8' codec can't decode in position 0: invalid start byte
I have my backend running on an AWS EC2 instance and my storages on S3, wherever there is a ImageFileField the API errors out with the below error. My database is a postgres 12 instance running on RDS. I just migrated from heroku to RDS, but restored data from the dump created on my local machine. It all works fine on heroku and local system, local system is running postgres 13, heroku as well. Any help would be appreciated, thanks! -
Django Rest Frame give 404 not found
When I hit the URL doctor/56b63b2d-11c4-4f0c-be7c-0b0348c487fd/ I get the detail not found I tried every solution but still it' not work error : - "GET /doctor/56b63b2d-11c4-4f0c-be7c-0b0348c487fd/ HTTP/1.1" 404 11332 class DoctorViewSet(ListModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = DoctorDeshboardSerializer def get_queryset(self, *args, **kwargs): doctor = self.kwargs["pk"] queryset = PatientDetails.objects.filter(doctor=doctor) print(queryset) return queryset And I look the get_queryset this has printed the all patient-related to doctor So means My logic is fine and data also exist but router = DefaultRouter() router.register('patient', views.PatientDashboardViewSet, basename='patients') router.register('doctor', views.DoctorViewSet, basename='doctors') urlpatterns = router.urls I also show serializer.py class DoctorDeshboardSerializer(serializers.ModelSerializer): problem_patient = SimpleProblemPatient(many=True) class Meta: model = PatientDetails fields = ['id', 'name', 'problem_patient'] Please Help On urgent basis -
Cannot assign requested address for Django-Docker project
I'm building my first project with Docker. I've created a simple Hello World with Django and PostgreSQL. Below the structure of the project without and with Docker: No Docker With Docker PostgreSQL --> PostgreSQL Django --> Container(Django) Therefore PostgreSQL will not use Docker; in development PostgreSQL runs in localhost and in production will be runs in a dedicated server. When I start Django without Docker I can see the Hello World page, but when I run it inside a container I see this error: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
How to use Django Nginx Application with both HTTP and HTTPS requests?
I have a Web Application that uses Django as backend and Nginx along with Gunicorn for the reverse proxy. I have already set up the Nginx configuration and it works perfectly when requests are sent over HTTPS. But it fails when HTTP requests are made. I want the application to work for both HTTP and HTTPS requests. Some of my Django Views contain internal requests that are made over HTTP as they have to be compatible with the Development as well as Production Server class LoginView(APIView): ... http_host = request.META["HTTP_HOST"] url = f"http://{http_host}/o/token/" headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'username': req_data['username'], 'password': req_data['password'], } response = requests.post(url, headers=headers, data=data) ... My nginx configuration is as follows server { listen 8000 ssl; server_name backend.test.com www.backend.test.com; access_log /var/log/nginx/app_backend.access.log; error_log /var/log/nginx/app_backend.error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/testuser/app_backend/app_backend; } location /media/ { root /home/testuser/app_backend/app_backend; } location / { include proxy_params; proxy_pass http://unix:/home/testuser/app_backend/app_backend/app_backend.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/backend.test.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/backend.test.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } I have hosted the VPS on digital ocean. How do … -
DjangoRestFramework ModelSerializer ignores required extra data
I have some ModelSerializer like: class MySerializer(serializers.ModelSerializer): x = serializer.IntegerField(required=True, write_only=True) class Meta: model = MyModel fields = (...some MyModel fields..., 'x') x is not a MyModel field. Problem: when I send request without x in form_data, drf doesn't raise "required" error. Expected: 400 response with message of missed 'x' is required. I am able to write it by myself, but it looks like undefined behavior or I missed something in docs. -
Creating name based user access to certain pages in the nav-bar
I need to create user based access to certain features of my Django web-app . I have figured out how to restrict access to users that are not super users like so : {% if user.is_staff %} <a href="{% url 'creditControlHome' %}">Credit Control</a> {% endif %} Is there a way to do this based on names? For example , " if user.name = George and Bill and Clint " then they can see that part of the nav bar ? -
Login ,Signup in same page django(multiple forms authentication)?I'am able to signup ... Why is it showing invalid credential in meassage while log in
*** VEIWS.PY This is views.py I am able to signin but not able to log in it shows invalid credentials `def login_user(request): if request.method=='POST': if request.POST.get('submit')=='sign_up': username=request.POST.get('name') email=request.POST.get('email') password=request.POST.get('password') if User.objects.filter(email=email).exists(): # Condition for same email id if already exists messages.warning(request,'Email already exists') else: user =User(email=email,password=password,username=username) user.set_password(password) #since raw passwords are not saved therefore needs to set in this method user.save() messages.success(request,'User has been registered successfully') #Dispalys message that user has been registerd return redirect('login') elif request.POST.get('loginsubmit')=='sign_in': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect ('/') else: messages.warning(request,'Invalid credentials') # print(email,password,username) return render (request,'login.html')` LOGIN.html ======= `//<section id="form"><!--form--> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-1"> <div class="login-form"><!--login form--> <h2>Login to your account</h2> <form method="POST" action="login"> {% csrf_token %} <input type="email" placeholder="Email Address" id="validationDefault01" name="email" required> <input type="password" placeholder="Password" id="validationDefault02" name="password" required> <span> <input type="checkbox" class="checkbox"> Keep me signed in </span> <button type="submit" name='loginsubmit' value='sign_in' class="btn btn-default">Login</button> </form> </div><!--/login form--> </div> <div class="col-sm-1"> <h2 class="or">OR</h2> </div> <div class="col-sm-4"> {% block body %} <body> {% for message in messages %} <section> <div class=" container alert alert-{{message.tags}} alert-dismissible" role="alert"> <strong>Message!</strong> {{message}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </div> </section> {% … -
Is there a free hosting site for django apps with 800mb+ size?
I have browsed through the net and tried pythonanywhere and heroku to deploy my web app which is a ml prediction model with site predicting the target. Everything is working fine but when I tried pythonanywhere I couldn't deploy it there cause of a size limit of 500. Same goes with heroku there I am getting the following error. Warning: Your slug size (346 MB) exceeds our soft limit (300 MB) which may affect boot time. So my question is, is there a good web hosting site which can deploy my project which is 782 mb large for free? -
Where is the logging in my Django application started by uwsgi?
I use supervisor and uwsgi to start my Django. Here is the conf in supervisor. [program:myapp] directory=/home/users command=uwsgi --ini uwsgi.ini stdout_logfile_maxbytes=50MB stdout_logfile_backups=30 stderr_logfile=/var/log/supervisor/supervisor.log stdout_logfile=/var/log/supervisor/supervisor.log And this is the ini file of uwsgi [uwsgi] http-socket=0.0.0.0:8080 wsgi-file=myapp/wsgi.py logformat=%(ltime) "%(method) %(uri) %(proto)" status=%(status) res-time=%(msecs)ms logto=/var/log/supervisor/uwsgi.log In this way, only method, status and time to reponse etc is listed as follow 14/Jan/2022:13:19:46 +0800 "GET /model/task/?taskid=e69a757974f811ec93e1f58ac6e34980&current=1&pageSize=10000&total=0&model_id=1 HTTP/1.1" status=200 res-time=107ms 14/Jan/2022:13:19:45 +0800 "POST /model/runmodel/ HTTP/1.1" status=200 res-time=3508ms What I want is if I add a logging.info or logging.debug in my application, it can also writes to the log file. From the doc of uwsgi, it seems I cannot accomplish that by the logformat parameter. Anyone knows if it's possible to do it? -
Add new entries to the model incrementing the latest value with three digits
I have a model, with a column named reference. Each reference has values like this: 106739D/4115110 106739D/4115111 106739D/4115112 and so on... From my view, I send a count of previous projects to the template, like this (truncated): def add_new_project(request, pk): context = {} projects = Project.objects.all().filter(project_id=pk).count() context['projects'] = projects Then in my template, I retrieve some value like 106739D/41151 + 1 (from count) = 106739D/411511 Template: <div class="col-sm"> <input type="text" name="reference" class="form-control" value="{{ some_given_value }}{{ projects }}" required> </div> It actually does the job, it increments the value one by one each time I create a new project, but I've been requested to do it with this format 00X: 106739D/4115110 --> 106739D/411511000 106739D/4115111 --> 106739D/411511001 106739D/4115112 --> 106739D/411511002 So basically I need to add 00X instead of X. Is there any efficient - pythonic way to do that? -
SMTPServerDisconnected at /users/password_reset/ Connection unexpectedly closed, why am I getting this error in 2022?
I am trying to send emails using sendgrids SMTP relay. I created a apikey, added this into my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'jajamensanson@gmail.com' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'mysendgridpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True When I try to send the email, I get this error: SMTPServerDisconnected at /users/password_reset/ Connection unexpectedly closed Anyone have an answer to this? Also, just for your info, I am using the django for beginners book. -
How to run Celery container without starting multiple Django servers
My docker-compose setup has several services. The ones I am concerned about are: celery, celery_beat, and backend (django). Every tutorial I have found online has the celery container using the same image as backend. The problem is that it is forcing 3 django containers to fire up (which can't be the optimal way of deploying my app). I currently use an ENTRYPOINT bash script at the end of my Dockerfile which waits for the database to be ready, then it handles migrations, then runs the development server: Dockerfile FROM python:3.9.5-alpine WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update RUN apk add gcc musl-dev python3-dev libffi-dev openssl-dev postgresql-dev COPY ./requirements.txt /requirements.txt RUN pip install --upgrade pip RUN pip install -r /requirements.txt COPY ./entrypoint.dev.sh /entrypoint.dev.sh COPY . /backend/ ENTRYPOINT [ "/entrypoint.dev.sh" ] entrypoint.dev.sh #!/bin/sh if [ "$POSTGRES_DB" = "digibrain_db" ] then echo "-------------- Waiting for postgres... -------------------" while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "-------------- Postgres database started! ----------------" fi python3 manage.py makemigrations python3 manage.py migrate python3 manage.py collectstatic --no-input --clear python3 manage.py runserver 0.0.0.0:8000 exec "$@" Since the ENTRYPOINT file/command is causing all 3 containers to run django I tried to change it to … -
How to get file ID from box.com by passing the file name in python
How to obtain file_id from "file name" in Box.com API Not sure which call will I make from this https://developer.box.com/reference/#searching-for-content. I want to pass filename and get file id of that filename. I am using python SDK -
Django/Heroku first deployment results in H10 error
When I try to access my app after deployment it results in an H10 error. It seems to reference favicon in the log and also says that Django isn't installed (I have run pip3 list in my venv and it appears to be there, it is also in requirements.txt). Here is the log: 2022-01-14T04:51:29.245939+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:42836` 2022-01-14T04:51:30.238629+00:00 app[web.1]: Traceback (most recent call last): 2022-01-14T04:51:30.238658+00:00 app[web.1]: File "manage.py", line 11, in main 2022-01-14T04:51:30.238659+00:00 app[web.1]: from django.core.management import execute_from_command_line 2022-01-14T04:51:30.238659+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2022-01-14T04:51:30.238660+00:00 app[web.1]: 2022-01-14T04:51:30.238660+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2022-01-14T04:51:30.238660+00:00 app[web.1]: 2022-01-14T04:51:30.238660+00:00 app[web.1]: Traceback (most recent call last): 2022-01-14T04:51:30.238661+00:00 app[web.1]: File "manage.py", line 22, in <module> 2022-01-14T04:51:30.238661+00:00 app[web.1]: main() 2022-01-14T04:51:30.238661+00:00 app[web.1]: File "manage.py", line 13, in main 2022-01-14T04:51:30.238662+00:00 app[web.1]: raise ImportError( 2022-01-14T04:51:30.238672+00:00 app[web.1]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2022-01-14T04:51:30.414522+00:00 heroku[web.1]: Process exited with status 1 2022-01-14T04:51:30.500903+00:00 heroku[web.1]: State changed from starting to crashed 2022-01-14T04:51:33.725668+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=vygrapp.herokuapp.com request_id=357ddcbf-e6fe-4c68-ba23-24777b56d20d fwd="61.68.159.52" dyno= connect= service= status=503 bytes= protocol=https 2022-01-14T04:51:34.113095+00:00 heroku[router]: at=error code=H10 … -
Django redirection errors
I currently have an issue using my button as I need to open a modal which is successful but when clicking from other pages it needs to redirect back to the page it was clicked on. <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfile">+</button> I have tried return redirect(request.META.get('HTTP_REFERER')) which does stay on url but I need to use context['is_post'] in case it fails to reopen up the modal which should be passed. So currently if I used mine it'll reopen on false data but won't hold the page url. context['nmenu'] is what is used to make sure the a tag is currently active. views.py: def index(request): context={} context['is_post']= False editProfileForm = UserProfileForm() if request.method == "POST": if 'editProfileForm' in request.POST: editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm() context['editProfileForm'] = editProfileForm return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) else: # Checks if user is logged out or in and passes to form if request.user.is_authenticated: Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by("-time", "read") context['Inbox'] = Inbox unreadMessagesCount = Messages.objects.filter(Q(receiver=request.user) & Q(read=False)).count() context['unreadMessagesCount']=unreadMessagesCount editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['nmenu']='home' return render(request, "home.html", context) html: {% block content %} <div class="col-md-3" … -
Why do I need to call (Django's)object before I link it to another object in Windows powershell?
I intuitively feel that, but I don't understand it step by step. Example: In Windows Powershell I open my main folder with manage.py and open the shell with: python manage.py shell. Then I need to write something like: Product.objects.get(id=1), so later I can link this to an object: obj = Product.objects.get(id=1). My question is, why does the shell need to have it in this fashion. Why I can't to type just obj = Product.objects.get(id=1)? Without this part before: Product.objects.get(id=1). I wonder about it, because the second part of this code points out to class and method. -
How to test a URL in Django?
I wrote this detail view: def blog_detail(request, pk): blog = get_object_or_404(Blog, pk=pk) comment = blog.comment_set.all() paginator = Paginator(comment, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'blog': blog, 'page_obj': page_obj, } return render(request, 'blog/blog_detail.html', context=context) Here's the url: urlpatterns = [ path('blog/<int:pk>/', views.blog_detail, name='blog-detail') ] Here my test for the view: class BlogDetailViewTest(TestCase): def setUp(self): user = User.objects.create(username='user01', password='123456') author = Author.objects.create( user=user, date_of_birth='1998-09-08', bio='I am user01') topic = Topic.objects.create(name='Testing') blog = Blog.objects.create(title='My blog', content="It's my blog") blog.author.add(author) blog.topic.add(topic) for c in range(3): Comment.objects.create(blog=blog, user=user, comment='I am testing') self.blog_instance = Blog.objects.get(id=1) def test_url(self): response = self.client.get(f'/blog/blog/{self.blog_instance.pk}') self.assertEqual(response.status_code, 200) def test_url_name(self): response = self.client.get(reverse('blog-detail', kwargs={'pk': self.blog_instance.pk})) self.assertEqual(response.status_code, 200) The test_url function are returning this assertion error: AssertionError: 301 != 200 Why the test_url function are returning the status code 301 if the test_url_name function are returing the status code 200? Both are the same url, I don't understand.