Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App fails to deploy on AWS ElasticBeanstalk with pywin32==306
I am stuck here since 2 days. Someone please help. Django App works fine locally but fails to deploy on AWS ElasticBeanstalk with pywin32==306. Platform: Python 3.11 running on 64bit Amazon Linux 2023/4.0.8. I am using windows 11. Python Version : 3.12.2. PIP version : 23.3.2. Please find below requirements.txt: asgiref==3.7.2 awsebcli==3.20.10 beautifulsoup4==4.12.3 botocore==1.31.85 cement==2.8.2 certifi==2024.2.2 charset-normalizer==3.3.2 colorama==0.4.3 distlib==0.3.8 Django==4.2.10 django-bootstrap-v5==1.0.11 filelock==3.13.1 idna==3.6 jmespath==1.0.1 pathspec==0.10.1 platformdirs==4.2.0 psycopg-binary==3.1.17 psycopg2-binary==2.9.9 pypiwin32==223 python-dateutil==2.8.2 pywin32==306 PyYAML==6.0.1 requests==2.31.0 semantic-version==2.8.5 setuptools==69.0.3 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 termcolor==1.1.0 tzdata==2023.3 urllib3==1.26.18 virtualenv==20.25.0 wcwidth==0.1.9 whitenoise==6.6.0 Getting the following error: 2024/02/15 13:12:10.274129 [ERROR] An error occurred during execution of command [self-startup] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr:ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 Complete AWS Log : https://drive.google.com/file/d/1ZbS3aVnHS2fg8-e9QDihnhzuHxB_CPDf/view?usp=sharing I upgraded the PIP and also tried pywin32==306;platform_system == "Windows" but in vain. -
How works super().get_queryset() in Django?
I am trying to get a queryset of questions that have publication date before today's date, but I am getting an error in get_queryset raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: IndexView is missing a QuerySet. Define IndexView.model, IndexView.queryset, or override IndexView.get_queryset(). My code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return super().get_queryset().filter(pub_date__lte=timezone.now()) But this code works: def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) What I am doing wrong? Thanks in advance -
django-tailwindcss integration image not displayed
I already have a Django project with template file index.html but my image is not displaying I try everything including {% load static %} but still it is not working may be because i used {% load tailwind_tags %} and {% tailwind_css %} and i also created file as mentioned in Django official website for static file but still it is not working. -
can't run cron file with docker -compose what i can do?
I use Django and postgres to them, I wrote a script that scrapes data and writes to the database and another that dumps. And these scripts should run at a certain time, as if in the logs I see that it is raised, but when I run it, it does not work PS C:\Users\komar\django-scraper-6> docker exec -it scrap bash root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:09:37 server EXITED Feb 15 10:26 AM root@0296ba2fb7f3:~/django_scraper# supervisorctl start server server: started root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:11:02 server EXITED Feb 15 10:37 AM dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # START CRON JOB LIST 0 12 * * * python /root/django_scraper/app/scrap_file.py >> /tmp/postgres_dump.log 2>&1 0 13 * * * python /root/django_scraper/app/db_dump.py # END CRON JOB LIST my repo https://github.com/yurakomarnitskyi/django-scraper dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # … -
Embedded link displays when hardcoded but not when passed as variable
I have the following problem in my django project when trying to display an embedded google maps link in my page. This works (renders the Google Maps iframe with a populated map) when I hardcode the src URL but not when I pass it in my context even though they result to the same text string. This is my html detailview.html: {% if maps_link is not None %} <iframe src="https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&amp;output=embed" loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} The src URL as it is shown above displays as I want it to, but when I do the following: {% if maps_link is not None %} <iframe src="{{ maps_link }}" <!-- This gets blocked --> loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} then my browser gives me the following warning: To protect your security, www.google.com will not allow Firefox to display the page if another site has embedded it. To see this page, you need to open it in a new window. This is my views.py where the context is generated. I tried to get around it by applying xframes exemptions but that made no difference: from django.views.decorators.clickjacking import xframe_options_exempt from django.http import Http404, HttpResponse @xframe_options_exempt def detail(request, database_reference): context = { "content" : … -
Is there a way to upload file in django database from reactjs form
I have a problem with the form data. It says the submitted data is not a file type when I want to post data from React to Django models. I try to upload file with form .I used multipart/form-data in react component and also tried append file, and post it with axios. -
Django-nested-admin has no classes
I installed django-nested-admin, but it doesn`t work. I did it correctly first of all i added to settings py to INSTALLED APPS. then i imported it to admin py. but it didn`t work. What I have to do to solve this problem. does anyone help me? -
Django DRF not releasing memory after large response data is send to the front end
I am using Django rest framework in our application's backend. In one of the api end points we have to send a large data as response. So the orm and serialization functionalities takes about 400mb to send the data to the front end. I am using memory_profiler and when we call another api or the same api it shows 400mb at start and then an additional 400mb is used if the same endpoint is called. So total 800mb. It keeps on adding whenever we call the api till it crashes. This is my code ---> **views.py ** @api_view(["GET"]) @hasValidToken def get_all_session_messages(request, user, identity_data, *args, **kwargs): try: return chat_services.get_all_session_messages( user.id, kwargs["session_id"], ) except Exception as exc: return error(message=str(exc)) **services.py ** def get_all_session_messages(user_id, chat_session_id): try: query_responses = chat_repository.get_all_query_response_given_chat_id( chat_session_id ) return ok( message="Successfully retrieved all chat session messages", response_data=query_responses, ) except Exception as exc: raise Exception( "Error retreiving chat session messages in repository " + str(exc) ) **repository.py** def get_all_query_response_given_chat_id( chat_id, limit=None, order_by_created_at=False ): if not order_by_created_at: if limit is not None: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id)[ :limit ] else: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id) else: if limit is not None: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at")[:limit] else: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at") return QueryResponseTrackingSerializer(query_responses, many=True).data **serializers.py** … -
ThreadPoolExecutor from concurrent.futures module of Python for DRF appliction
I have simple GET Project API, The following is my code approach ` class ProjectListCreateView(generics.ListCreateAPIView): queryset = Project.objects.filter(is_deleted=False) serializer_class = ProjectSerializer def convert_to_json(self, state): return State.convertProjectObjectToJSON(self, state=state) def get(self, request, *args, **kwargs): try: objects = self.get_queryset() with ThreadPoolExecutor(max_workers=8) as executor: json_response = list(executor.map(self.convert_to_json, objects)) response = response_body(status_code=status.HTTP_200_OK, data=json_response) return Response(response, status=status.HTTP_200_OK) except Exception as e: response = response_body(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, data={str(e)}) return Response(response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)` This APIs taking 970ms for 200 Projects. My question is Is this depends on the Threads so What should I need to deploy it on azure, do I have to make any changes regarding server configs or something else? -
react+django questions about https(SSL certificate)
I created a website using react and django. React was used as a front-end, Django was used as a back-end.(React uses S3, and Django uses EC2 server.) I was asked to adapt the website to HTTPS. I know I need to use SSL certificate. However, the front-page running on S3 can use and SSL certificate, so HTTPS is applicable, but the server running on EC2 can't use an SSL certificate. Because EC2 uses IP address, not useing Domain address. There are times when I need to make an API call to "http://my_ip_address/~" on the my website, but it keeps getting blocked. Please help me. How should I solve it? Do I need to add another Domain address to the EC2 server......? Or Is there a way to make a request from HTTPS to HTTP using CORS? I really need your help....! I applied SSL certificate to S3(front-page). But EC2 server is still HTTP. Django "settings.py" file : ... CORS_ALLOW_ALL_ORIGINS = True ... I also applied the above settings. -
How to run django celery tasks with persistent event loop and asyncio calls with proper DB reconnections?
I have a django and celery, postgresql with psycopg2 driver and an external dependency with heavy setup calls which is hard to modify and which saves and reuses asyncio event loop after first invocation. I also have an asyncio call which I need to run in the celery task. This method uses this external dependency internally. It seems that I can't use async_to_sync django call because it doesn't allow me to preserve the loop. Therefore, subsequent tasks executions raise Event loop is closed when I invoke dependency lib calls. I used the following way to handle that: class ExampleModel(models.Model) name = models.CharField() async def my_method(): example_entry = await ExampleModel.objects.aget(id=1) # external async dep call here return example_entry @shared_task(name="example_task", bind=True) def example_task(self): asyncio.get_event_loop().run_until_complete(my_method()) It has worked perfectly for a few months, until we had a restart of the database and connection was lost. All further tasks had django.db.utils.InterfaceError: connection already closed error. Digging in, I created a set of test tasks: @shared_task(name="debug_task_async_to_sync") def debug_task_async_to_sync(self): import asgiref.sync res = asgiref.sync.async_to_sync(my_method)() print("async_to_sync", res) @shared_task(name="debug_task_loop") def debug_task_loop(self): res = utils.get_event_loop().run_until_complete(my_method()) print("loop", res) @shared_task(name="debug_task") def debug_task(): res = models.ExampleModel.objects.get(id=1) print("sync", res) and restarted the database in the time of their execution. Both sync debug_task and … -
Why do Django custom validation messages not display on the HTML page?
I have the following custom username validation method. This method is executed when I submit the form, but it does not display the error message. However, other default field validations are working fine. def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("This username already taken. please choose another.") return username Here is the HTML code for the username input: <input type="text" name="username" class="form-control" id="username" required> <span class="invalid-feedback" role="alert"> {{ form.username.errors.0 }} </span> -
Django Integrity Error instead of Bad Request Error
So I have DRF project using a custom user that extend the AbstractUser, and I want to make the email unique. I tried to change the AbstractUser like this. class AbstractUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator], error_messages={ "unique": _("The username already exists."), }, ) first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) email = models.EmailField(_("email address"), unique=True, error_messages={ "unique": _("A user with that email already exists."), }) It verified the duplication of the email, but I got Integrity Error, but I want to get Bad Request for my frontend What's wrong, why fields in AbstractUser produce different error for unique constraint? Please help me, thanks in advance. -
Django redirect is not passing keyword parameters
I am redirecting from a view in one app, to a view in another. Its finding the view just fine but not passing the arguments. I've tried passing it as positional and keyword but cant get the thing to work. if request.method == 'POST': username = request.POST['username'] pass1 = request.POST['pass1'] user = authenticate(username=username, password=pass1) if user is not None: login(request, user) print(user.username, type(user.username), file=sys.stderr) return redirect(reverse('homepage'), user.username) else: messages.error(request, "Bad Credentials!") return redirect('index') @login_required() def homepage(request, username=None): print(username, file=sys.stderr) try: user = userAttribute.objects.get(username=username) except userAttribute.DoesNotExist: return redirect("index") [14/Feb/2024 18:15:18] "GET /signin HTTP/1.1" 200 824 Kane <class 'str'> [14/Feb/2024 18:15:23] "POST /signin HTTP/1.1" 302 0 None -
Using django test fixtures without signals
I am writing code for a web app in python/ django. In the app there is a User model and other models with a OneToOne key to the User model. I want entries in these other models to be created when the user signs up, so I have been using signals. The problem is I am using test fixtures. Some of these fixtures trigger the signal and mean other fixtures are overridden/ not used/ cause integrity errors in the database. How can I make it so that I do not clal signals for these tests, so the database is set up with only my fixtures? (I want to do separate tests while using signals later, but tests with fixtures are non negotiable in my case, so that takes priority). I need to upkeep code quality aswell. Do I change my approach? Error recieved: Integrity error for UNIQUE constraint I have tried Using post_save.disconnect and hten manually loading fixtures with loaddata Overriding the signals using 'with post_save' and then loading fixtures with loaddata -
Error while integrating google OAuth with superset
To integrate Google authentication into my Superset application, which is running on a specific IP address, I followed these steps: Created an OAuth client ID on the Google Cloud Platform. To create it, a JavaScript Authorized Origin is required, which is basically the application's URL. Since my Superset application does not have a domain, I masked the <superset-IP> with a random domain (http://localtesting.com) in my local etc/hosts file. I used this masked domain in the Google Console for creating the client ID. Updated the superset_config.py file with the client ID, client secret, and app domain. Here is the file for your reference: from flask_appbuilder.security.manager import AUTH_OAUTH ENABLE_PROXY_FIX = True AUTH_TYPE = AUTH_OAUTH OAUTH_PROVIDERS = [ { "name": "google", "icon": "fa-google", "token_key": "access_token", "remote_app": { "client_id": "<ClientId", "client_secret": "<ClientSecretKey>", "api_base_url": "https://www.googleapis.com/oauth2/v2/", "client_kwargs": {"scope": "email profile"}, "request_token_url": None, "access_token_url": "https://accounts.google.com/o/oauth2/token", "authorize_url": "https://accounts.google.com/o/oauth2/auth", "authorize_params": {"hd": "http://locatesting.com"} }, } ] AUTH_ROLE_ADMIN = 'Admin' AUTH_ROLE_PUBLIC = 'Public' Restarted the VM where superset is hosted. After completing these steps, I encountered a 502 Bad Gateway error. My Superset application is using an Nginx server. Is this issue somehow associated to nginx or anything wrong in masking of IP in my local machine -
fcm-django add badge to Aps for ios platform
I use fcm-django library def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more", } extra_data = {"type": "some information", "link": "https://google.com", "badge": str(10)} for device in devices: try: if device.type == "ios": device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data)) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) I need add badge value to Aps for ios. I've tried apns = { "badge": 10, } device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data, apns=Aps(apns))) But got error and no PN. How can I do it correctly? -
Django- getting the value of 'models.DateField(default=datetime.datetime.today)' in view
I have this model: models.py: class myModel(models.Model): a = models.ForeignKey(P,on_delete=models.CASCADE) ... **date = models.DateField(default=datetime.datetime.today)** In the views.py, I get the data of "date" field: views.py from appX.models import myModel from datetime import datetime ... def my_items(request): ... got_date = myModel.objects.get(id = 1).date got_date_2 = datetime.strptime(got_date, "%YYYY-%MM-%d") But python throws the following error: time data '"2024-02-14"' does not match format '%YYYY-%MM-%d' What "format" should I use ? Thanks. -
Different outputs between Django Server and PyCharm
I am facing an issue that I get different outputs running the same code throw PyCharm and throw the Django Server. PyCharm gives the output expected and needed, so it is an issue to fix. Because I only use PyCharm for testing. The input string: # HTML HTML is a markup language that can be used to define the structure of a web page. HTML elements include * headings * paragraphs * lists * links * and more! The most recent major version of HTML is HTML5. The Code is: # A list of simple markdown and there html aquvalents. # First element is the inner html/markdown second is the whole markdown, third is the starting html tag and fourth the closing html tag regex_hugging_html = [ [r"(?<=^#{1})[^#][^\n]*$", r"^#{1}[\s]*[^#][^\n]*$", "<h1>", "</h1>"], # heading first level (#) [r"(?<=^#{2})[^#][^\n]*$", r"^#{2}[\s]*[^#][^\n]*$", "<h2>", "</h2>"], # heading second level (##) [r"(?<=^#{3})[^#][^\n]*$", r"^#{3}[\s]*[^#][^\n]*$", "<h3>", "</h3>"], # heading third level (###) [r"(?s)\*\*(.*?)\*\*", r"(?s)\*\*.+?\*\*", "<b>", "</b>"], # boldface (** **) [r"(?s)__(.*?)__", r"(?s)__.+?__", "<b>", "</b>"], # boldface (__ __) [r"(?s)\n{2}(.+?)(?=\n{2}|\Z)", r"(?s)(\n{2}.+?)(?=\n{2}|\Z)", "<p>", "</p>"], # paragraphs (blank line) ] def markdown_to_html(markdown): html = markdown for replacer in regex_hugging_html: # Find all occurances of the markdown expression for substr in re.compile(replacer[0], … -
How to save data from CKEditor via Django Rest Framework using javascript (vanilla)
Im writing an application that has a function for adding a document. For this reason i needed some rich text editor for formatting the documents. so here is my views.py for rendering my html: def add_document_view(request): if request.user.is_authenticated: categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, "languages":languages} return render(request, "documents/add-document.html", context) return JsonResponse({"status":"500 Auth Error"}) add-document.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Document</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <h1>Add Document</h1> <hr> <form method="POST" action="#"> {% csrf_token %} <div class="form-group"> <label for="title">Header:</label> <input type="text" class="form-control" id="header" name="header" placeholder="Enter document header" required> </div> <div class="form-group"> <label for="category">Category:</label> <select class="form-control" id="category" name="category" required> <option value="" disabled selected>Select category</option> {% for category in allCategories %} <option value="{{ category.id }}">{{ category.title }}</option> {% endfor %} </select> </div> <div class="form-group"> {{form.media}} {{form.as_p}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="https://cdn.ckeditor.com/ckeditor5/38.0.0/classic/ckeditor.js" defer></script> </body> </html> models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords from .utils import get_language_choices class Category(models.Model): title = models.CharField(max_length = 64, unique = True) def __str__(self): return self.title class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' … -
Unexpected Behavior with Concurrent ModelViewset Requests
I'm experiencing an issue with a Django Rest Framework ModelViewSet endpoint named projects/. I have a set of requests (PATCH, DELETE, then GET) that are causing unexpected behavior. The timeline of requests and responses is as follows: PATCH request at 14:45:09.420 DELETE request at 14:45:12.724 3.DELETE 204 response at 14:45:12.852 PATCH 200 response at 14:45:13.263 GET request at 14:45:13.279 GET 200 response at 14:45:13.714 All responses indicate success. However, the GET response, which follows a DELETE, includes the supposedly deleted model. If I call the GET endpoint a bit later, the deleted model is no longer listed. This behavior suggests a potential race condition or a caching issue, where the PATCH operation completes after the DELETE, or the GET request returns a cached list not reflecting the deletion. The view, serializer and model code are all pretty vanilla: class ProjectViewSet(ModelViewSet): parser_classes = (MultiPartParser, FormParser, JSONParser) queryset = Project.objects.all() serializer_class = ProjectSerializer pagination_class = ProjectPagination class ProjectSerializer(serializers.ModelSerializer): creator = UserUUIDField(default=serializers.CurrentUserDefault()) image = serializers.ImageField(required=False) class Meta: model = Project fields = "__all__" class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) creator = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) image = models.ForeignKey( wand_image, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="projects" ) One model has a … -
Django project setup using django-configurations
I'm very new to Django and I'm trying to set up a new project, using django-configurations to manage the config of Development, Staging and Production environments. https://pypi.org/project/django-configurations/ I followed the quickstart guide, but after setting things up I keep getting this error when running manage.py startserver: File "[path_redacted]/django_test/.venv/lib/python3.11/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. This is a brand new blank project, no apps and no changes whatsoever from the default project setup. I only set up django-configurations as per the quickstart guide. I have manage.py set up as per the guide: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test.settings') os.environ.setdefault('DJANGO_CONFIGURATION', 'Development') try: from configurations.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Then do the same with settings.py, by adding the below class just after the default definition of BASE_DIR: class Development(Configuration): DEBUG = True The default installed apps are there and untouched, including the admin app: INSTALLED_APPS … -
why the django filter query not accepting the passed values?
I have below program that is suppose to execute objects.filter query on two columns and based that fetch the data of 3rd column. class API(GenericAPIView, ListModelMixin, CreateModelMixin): serializer_class = [DummySerializer, ATSerializers] def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.org = None self.ent = None def post(self, request, *args, **kwargs): org = request.data.get("org") ent = request.data.get("ent") self.org = org self.ent = ent if self.org is None or self.ent is None: return Response("Both fields are required to fetch token..", status=status.HTTP_400_BAD_REQUEST) queryset = self.get_queryset() print("[QUERY SET] :", queryset) if not queryset: return Response("No matching records found.", status=status.HTTP_404_NOT_FOUND) lnk_token = list(queryset.values_list('link_token', flat=True)) return Response({"lnk_tkn": lnk_token}, status=status.HTTP_200_OK) def get_queryset(self): org = self.org ent = self.ent print("this is get_queryset bloc") if org is None or ent is None: return tbl.objects.none() else: print(self.org, self.ent) filter_token = tbl.objects.filter(org=org, ent=ent) print(filter_token) lnk_token = filter_token.values_list('tkn', flat=True) return lnk_token def list(self, request, *args, **kwargs): queryset = self.get_queryset() if not queryset: return Response(f"Both IDs are the required fields.....") return Response( { "token": queryset } ) I am receiving the values of org and ent from request body in my post method and passed onto the get_queryset() GET method. Then the values are supposed to be passed to filter_token = tbl.objects.filter(org=org, ent=ent) That is when … -
Django redirect() returns 302
So, i'm trying to make a calculator with user log in and sign up funcionalities. The calculator is in an app called "calc" and the log in/sign up is in another app called "cadastro". When the user log in, the view should redirect to the calc index view, but i get a 302 code in the terminal instead. This is my log in view: def login(request): form = formularioLogin() if request.method == "POST": user = authenticate(username = request.POST.get("username"), password = request.POST.get("password")) if user: login_django(request, user) return redirect("calc:index") return JsonResponse({"erro": "Usuário ou senha incorretos."}) return render(request, "cadastro/login.html", {"form": form}) This is my calc:index view: @login_required(login_url="cadastro:login") def index(request): historico = calculos.objects.order_by("-pk") if request.method == "GET": if "apagar" in request.GET: apagar = request.GET.get("apagar") apagar = calculos.objects.filter(pk=apagar) apagar.delete() return render(request, "calc/index.html", {"historico": historico}) elif "conta" in request.GET: conta = request.GET.get("conta") if re.search("^[0-9.+*\-]+$", conta): res = str(eval(conta)) if conta != res: # create = calculos.objects.create(calculo=conta, resultado=res) return render(request, "calc/index.html", {"conta": res, "historico": historico}) return render(request, "calc/index.html", {"conta": res, "historico": historico}) return render(request, "calc/index.html", {"erro": "erro", "historico": historico}) return render(request, "calc/index.html", {"historico": historico}) This is my calc.urls: app_name = "calc" urlpatterns = [ url(r"^$", views.index, name="index"), ] And this is my cmd: CMD I'm using Django … -
Django Cron Jobs
quiero saber que es lo mejor para hacer cronjobs en django a dia de hoy 2024, ya que me encuentro con librerias que satisfacen esta necesidad pero que no estan actualizadas con ultimas versiones del 2011 o 2006 Saludos esperaba una cronjob que tuviera un disparador en django