Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
intento instalar mysqlclient y me da un error
C:\Users\usuario1>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [39 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\\lib\\mariadb', 'C:/mariadb-connector\\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\\include\\mariadb', 'C:/mariadb-connector\\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('__version__', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\__init__.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\__init__.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running egg_info writing src\mysqlclient.egg-info\PKG-INFO writing dependency_links to src\mysqlclient.egg-info\dependency_links.txt writing top-level names to src\mysqlclient.egg-info\top_level.txt reading manifest file 'src\mysqlclient.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE' writing manifest file 'src\mysqlclient.egg-info\SOURCES.txt' copying src\MySQLdb\_mysql.c -> build\lib.win-amd64-cpython-312\MySQLdb … -
Access to XMLHttpRequest has been blocked by CORS policy in Django
I have deployed a web app and created a sub domain for it as the url of its backend (e.g main url is domain.com and subdomain is api.domain.com) and both are in https, too. While I request from frontend to my created api in Django Rest Framework error Access to XMLHttpRequest has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource is given. Code below is the part of my settings.py. CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I shall be thankful for giving me the solution. -
Django HTML Tags - Merge For Loop with Conditional Statement
I am using Django and I am wondering if there is a way to modify the tags below so that the for loop stops iterating once a specific condition is met? webpage.html <div> {% for person in crew.crew_set.all %} {% if person.job|stringformat:'s' == 'Supervisor' %} <div>Supervisor</div> {% endif %} {% endfor %} </div> The code above results in "Supervisor" being written 50 times. Can I merge the two tags or use a break statement somehow so "Supervisor" is only listed once? I'm not listing my models / views because I'm really just trying to get a better understanding of how to use tags on my html pages. -
Django requests.FILES explanation
Having troubles in understanding how django rest framework request's attributes works. Trying to save via request.data.files: if 'files' in request.data: print(ser.data['id']) for file in request.data['files']: MessageFiles.objects.create(message=Message.objects.get(id=ser.data['id']), files=file) Got: 'bytes' object has no attribute '_committed' if I do this via default django method it works if request.FILES: print(request.FILES) for n in request.FILES.getlist('files'): MessageFiles.objects.create(message=Message.objects.get(id=ser.data['id']), files=n) What is the difference? Thanks for your answers! -
how to save the images in the fly in Django?
I'm using Django view, and I'm trying to save the image on the fly and pass it to the template HTML This is the view.py def img_upscaler(request): # some code upscaled = sr.upsample(image) cv2.imwrite("result.png", upscaled) return render(request, "upsc_main.html",{'form': form}) I want the result of the cv2.imwrite method to be saved on the fly and passed in render to be called in the HTML template. I tried many ways to do it and I can't get it. any help? thank you in advance. -
Django loggers setup
I've working on a Django monolith project and I've setup basic logging in my settings.py file like in the code below. It is working, I have logs folder and there 2 log files info and error. I feel that it is not the best solution and would like to improve it and to be more advanced. Django documentation is quote confused related to the topic. Could you share your experience and how do you setup logging on your Django projects? Thank you in advance for any answers! Here is my code in settings.py file: # Define the log directory LOG_DIR = os.path.join(BASE_DIR, "logs") # Create the log directory if it doesn't exist if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) FORMATTERS = ( { "verbose": { "format": "{levelname} {asctime:s} {name} {threadName} {thread:d} {module} {filename} {lineno:d} {name} {funcName} {process:d} {message}", "style": "{", }, "simple": { "format": "{levelname} {asctime:s} {name} {module} {filename} {lineno:d} {funcName} {message}", "style": "{", }, }, ) HANDLERS = { "console_handler": { "class": "logging.StreamHandler", "formatter": "simple", "level": "DEBUG", }, "info_handler": { "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/log_info.log", "mode": "a", "encoding": "utf-8", "formatter": "verbose", "level": "INFO", "backupCount": 5, "maxBytes": 1024 * 1024 * 5, # 5 MB }, "error_handler": { "class": "logging.handlers.RotatingFileHandler", "filename": f"{BASE_DIR}/logs/log_error.log", "mode": "a", … -
How to auth user to Django admin site using external API end point
I'm using an external endpoint to check if the username and password are given and if it is valid I return success:true if not I return it as false. and ofc I generate a token and return it back to him. Here is the function amusing for this : @api_view(["POST"]) # decorator to make this a rest API endpoint def login_user(request): """ Login User Endpoint takes in email & password as input from the client side """ username, password = request.data["username"], request.data["password"] # authenticate function from Django auth library is used here # to check if the provided credentials are correct or not user = authenticate(username=username, password=password) # If authentication is successful then generate a token else return an error message as a JSON object if user: token, _ = Token.objects.get_or_create(user=user) the_company_object = hiring_app_company.objects.get(user=user) user_object = { "name": f"{user.first_name} {user.last_name}", "email": user.username, "image": f"https://admin.apexnile.com{the_company_object.company_logo.url}", "link":f"https://admin.apexnile.com/admin/" } return Response( {"success": True, "user": user_object, "token": token.key}, status=status.HTTP_200_OK, ) else: return Response( {"success": False, "error": "Invalid Credentials"}, status=status.HTTP_401_UNAUTHORIZED, ) The API called are being called from a totally different server which uses Next auth and it authenticates the user based on the response returned from this API call. now the problem is sometimes … -
React nginx to django gunicorn error 502 not visible on gunicorn
I'm asking this question because, despite more or less similar topics, I haven't found an answer to my problem. I have 2 servers (A and B). On server A, there is my react app using nginx to be served. On server B, there is my django drf deploying with gunicorn. Django drf is the backend of my front react app. Django is not accessible on internet but i can reach him from server A (using curl http://serverb_ip:8080). I set up react nginx conf as follow: upstream django { least_conn; server serverb_ip:8080; } server { listen 80; server_name servera_name; return 301 https://$server_name$request_uri; } server { listen 3000; listen \[::\]:3000; server_name pro.boutigou.fr; access_log /var/log/nginx/app.log; root /home/bouti/frontend/producer/build; client_max_body_size 10M; location /producer/api/v1/ { access_log /var/log/nginx/app_proxy.log; error_log /var/log/nginx/error_proxy.log debug; proxy_pass http://django; } location / { access_log /var/log/nginx/app_http.log; try_files $uri /index.html; add_header X-Frame-Options SAMEORIGIN; } } And my gunicorn set up on serverb: \[Unit\] Description=gunicorn daemon Requires=gunicorn.socket After=network.target \[Service\] User=bouti Group=www-data WorkingDirectory=/home/bouti/backend/api ExecStart=/home/bouti/backend/env/bin/gunicorn \\ --access-logfile - \\ --workers 3 \\ --bind unix:/run/gunicorn.sock \\ api.wsgi:application \[Install\] WantedBy=multi-user.target Request from react to my backend are visible in /var/log/nginx/app_proxy.log and /var/log/nginx/error_proxy.log. But there are not visible in gunicorn journal. In /var/log/nginx/error_proxy.log, there is: 2023/10/22 14:30:41 \[debug\] 76218#76218: \*13234 http … -
CORS issue between Django backend and React frontend in Docker environment
I have a Django backend and a React frontend set up in separate Docker containers, both running on the same Docker network. The backend is accessible via the DNS backendServer and the frontend via frontendServer. I'm encountering a CORS issue when trying to make API requests from my React frontend to my Django backend. The error message in the browser console is: Access to XMLHttpRequest at 'http://localhost:8000/api/project/?page=1' from origin 'http://192.168.1.63:3000' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`. Is there something else I might be missing or another configuration I need to make to allow requests from my React frontend to my Django backend? Any help or suggestions would be greatly appreciated. Thank you! I've tried the following steps to resolve the issue: Installed and configured the django-cors-headers middleware in my Django project. Added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to MIDDLEWARE in my settings.py file. Set CORS_ALLOWED_ORIGINS to include my frontend URL (http://192.168.1.63:3000). Ensured that my Docker containers are on the same network. Despite these steps, I'm still encountering the CORS issue. The 192.168.1.63 is my dev server that hosts the docker services. -
JSON from api request in func app encoded differently to that of a Django app
I have a Django application which contains a function that calls an API and adds the data from the response into my database. I am trying to move this function into an Azure function app, however the JSON that is returned from the request seems to be encoded differently which is causing the database insert to fail. Request function from Django: def fetch_magic_set_data(code, max_retries=3, sleep_base=2): for retry in range(max_retries): try: response = requests.get(f'https://mtgjson.com/api/v5/{code}.json') response.raise_for_status() magic_sets_json = response.json() if 'data' in magic_sets_json and 'cards' in magic_sets_json['data']: return True, magic_sets_json['data'] else: print(f'Response is empty for {code}, retrying...') except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except RequestException as req_err: print(f'Request error occurred: {req_err}') sleep_time = sleep_base * (2 ** retry) time.sleep(sleep_time) return False, None Request function from function app: def get_response(url, max_attempts=10): for attempt in range(max_attempts): try: response = requests.get(url) if response.status_code == 200: return response elif 400 <= response.status_code < 600: logger.warning(f"Status: {response.status_code}. Error from {url}.") if response.status_code == 404: return None except requests.RequestException as e: logger.warning(f"Attempt {attempt + 1} of {max_attempts}. Error: {e}") if attempt < max_attempts - 1: time.sleep((2 ** attempt) + (attempt % 2)) else: logger.error(f"Failed to get response from {url} after {max_attempts} attempts.") return None return None … -
Add Log entry on Model Export Actions
I have enabled Log entries in the Django Admin class CustomLogEntryAdmin(admin.ModelAdmin): list_display = [ "action_time", "user", "content_type", "object_id", "object_repr", "action_flag", "change_message", ] # list filter list_filter = ["action_time", "user", "content_type"] # search search_fields = ["user__username", "object_repr"] admin.site.register(LogEntry, CustomLogEntryAdmin) And I have another model whose admin.py code is like this class RegAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = RegAdminResource def has_view_permission(self, request, obj=None): return True def has_module_permission(self, request): return True By default all change, addition and deletion entries are logged but I also want to log an entry when any export action is performed on it. ChatGPT suggests that I should something like this # in admin class def export_action(self, request, *args, **kwargs): # Log the export action LogEntry.objects.create( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(self.model).id, object_id=None, object_repr=str(self.model), action_flag=1, # Assuming 1 stands for the action flag of 'change' change_message="Export action triggered.", ) return super().export_action(request, *args, **kwargs) But this function is not triggered when an export action is performed. I confirmed by adding a print statement. How should I do this? Any help would be appreciated. -
Is there a way to pass Javascript variable to Django template before form submit?
I am trying to get a selected approver and do a validation check before a form gets submitted in Django...It's turning out to be fairly complicated...I've gotten most of the way there...but can't seem to figure out how to "get" the ID translated in the Django template...I've gotten the ID...but can't seem to make the final connection.... Here's my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here's my HTML... Check Availability <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> {% if not start_conflict or end_conflict or during conflict %} <td class="title117">Yes</td> {% else %} <td class="title117">No</td> {% endif %} </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> Here's my form... class DailyPlannerForm(forms.ModelForm): class Meta: model = NewDailyPlannerEvent … -
How to add Google AdSense to my Django blog project?
I have a Django blog app. The Google Adsense said that the script is not found in my website, however I copied it. Thank you in advance. I have a default.html which is extended to all the other html pages. It contains the header with login/logout and signup buttons, the logo, a welcoming message and most importantly the Google Ads scripts. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" property="og:description" content="These articles are about movies and created by users."> <meta name="keywords" content="seo, python, django, movies, articles, opinions, posts, users, actress, actor, hollywood, mainstream, film"> <meta name="author" content="************"> <!-- Google AdSense meta tag --> <meta name="google-adsense-account" content="ca-pub-************"> <title>Articles</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="************" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> <!-- Google AdSense --> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-************" crossorigin="anonymous"></script> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=************"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '************'); </script> <!-- Google Acceptable-Ads Message --> <script async src="https://fundingchoicesmessages.google.com/i/pub-************?ers=1" nonce="************"></script><script nonce="************">(function() {function signalGooglefcPresent() {if (!window.frames['googlefcPresent']) {if (document.body) {const iframe = document.createElement('iframe'); iframe.style = 'width: 0; height: 0; border: none; z-index: -1000; left: -1000px; top: -1000px;'; iframe.style.display = … -
Why is this block not overwriting the image?
I have : <a class="navbar-brand" href="/" >{% block brand %}<img src="{% static 'logo.png' %} " />{% endblock%}</a > How ever the block is still showing the same image of the child template, how can I overwrite it? just for the "/" page. I have a static folder in the main project folder and a template folder, I have added their respective config in settings.py see: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], STATICFILES_DIRS = [BASE_DIR / 'static'] here is the child template: {% extends "base.html" %} {%load static%} {% block brand %}<img src="{% static 'reviews/logo.png' %}" />{%endblock%} -
Streaming data using Langchain RetrivalQA
I am using Django, and Langchain with OpenAI to generate responses to my prompts. I was trying to enable streaming using Server-Sent-Events (SSE) in my API function. When I run my code It does stream the OpenAI output in the terminal, but it returns the output as a whole to the client once the streaming has ended. I tried using StreamingHttpResponse but, didn't get any success. It would be really awesome if any one can suggest what's wrong in the code. API Function: @api_view(['GET','POST']) def sse_view(request): if request.method != 'POST': return Response({"message": "Use the POST method for the response"}) url = request.data.get("url") questions = request.data.get("questions") prompt = request.data.get("promptName") if not url or not questions: return Response({"message": "Please provide valid URL and questions"}) # Process the documents received from the user try: doc_store = process_url(url) if not doc_store: return Response({"message": "PDF document not loaded"}) except Exception as e: return Response({"message": "Error loading PDF document"}) custom_prompt_template = set_custom_prompt(url,prompt) # Load and process documents loader = DirectoryLoader(DATA_PATH, glob='*.pdf', loader_cls=PyPDFLoader) documents = loader.load() text_splitter = CustomRecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=30) texts = text_splitter.split_documents(documents) #Creating Embeddings using OpenAI embeddings = OpenAIEmbeddings(chunk_size= 16, openai_api_key= openai_gpt_key,) db = FAISS.from_documents(texts, embeddings) db.save_local(DB_FAISS_PATH) search_kwargs = { 'k': 30, 'fetch_k':100, 'maximal_marginal_relevance': True, 'distance_metric': … -
I have two form to get email in my webpage but whenever i submit the form the message form is not valid is displayef
urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('email-submit/form1/', views.email_submit, name='email-submit1'), path('email-submit/form2/', views.email_submit, name='email-submit2'), ] forms.py from django import forms from .models import EmailSubscription class EmailSubscriptionForm(forms.ModelForm): class Meta: model = EmailSubscription fields = ['email'] models.py from django.db import models class EmailSubscription(models.Model): email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib import messages from .forms import EmailSubscriptionForm def home(request): return render(request, 'maincontent/home.html') def about(request): form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) def contact(request): return render(request, 'maincontent/contact.html') def email_submit(request): if request.method == 'POST': form_id = request.POST.get('form_id') if form_id == 'form1': form = EmailSubscriptionForm(request.POST) elif form_id == 'form2': form = EmailSubscriptionForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form.save() messages.success(request, f'Thank you for subscribing with email: {email} ({form_id.capitalize()})') else: messages.error(request, f'Form {form_id.capitalize()} is not valid.') form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) email_form_1.html <form class="email-submit" id="data-form-1" method="post" action="{% url 'email-submit1' %}"> {% csrf_token %} <input type="hidden" name="form_id" value="form1"> <input type="email" placeholder="Enter your email..." name="{{ form.email_address.name }}" id="{{ form.email_address.id }}" required/> <button type="submit"> Sign … -
How Post Amount Number From React to Django py script
hello i want send data from my react app.jsx to django script file that scirpt have amount variable and need number to give to him in my script from django.db import models from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from . serializer import * from azbankgateways import (bankfactories,models as bank_models,default_settings as settings,) import logging from django.urls import reverse from django.shortcuts import render from django.http import HttpResponse, Http404 from django.http import JsonResponse # Bank from azbankgateways.exceptions import AZBankGatewaysException from azbankgateways.models.banks import Bank # API # Create your models here. # ViewSets define the view behavior. class BankViewSet(viewsets.ModelViewSet): queryset = Bank.objects.all() serializer_class = BankSerializer # Bank Functions def go_to_gateway_view(request): # خواندن مبلغ از هر جایی که مد نظر است amount = 5000 # تنظیم شماره موبایل کاربر از هر جایی که مد نظر است user_mobile_number = '+989112221234' # اختیاری factory = bankfactories.BankFactory() try: bank = factory.auto_create() # or factory.create(bank_models.BankType.BMI) or set identifier bank.set_request(request) bank.set_amount(amount) # یو آر ال بازگشت به نرم افزار برای ادامه فرآیند bank.set_client_callback_url('/callback-gateway') bank.set_mobile_number(user_mobile_number) # اختیاری # در صورت تمایل اتصال این رکورد به رکورد فاکتور یا هر چیزی که بعدا بتوانید ارتباط بین محصول یا خدمات را با این # پرداخت برقرار کنید. bank_record = … -
CSRF verification error from dockerized Django behind dockerized nginx
I have two docker containers running together, one for a Django app using gunicorn, and one for nginx serving static files and redirecting requests to the Django app. I have used different ports for the Django/gunicorn server, exposed only to nginx (8000), the nginx server, exposed in the docker container (80), and externally when using the docker container (so I mapped the port to a different one, say 8888). I also access it with a "xyz.local" host name from the device where docker runs. This is all happening in a home network, no HTTPS involved. Now when I submit a form, e.g. the admin interface's login form, I get a CSRF verification failure saying xyz.local:8888 is not a trusted origin. I understand that I can add "http://xyz.local:8888" to the CSRF_TRUSTED_ORIGINS to make it work, or disable CSRF protection altogether, but I'm wondering if that is the correct/best way in this setup. I would like to have the Django docker container be as unaware of the outside world as possible, so that I can just run it on another device having a different host name or with a different docker-compose configuration using a different port, without having to rebuild the docker … -
Django Unit Test for class with TokenAuthentication
this is my first time writing unit test so in my Django Project I have this class from views.py class AllClientProfilesView(generics.ListAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = ClientProfileSerializer def get_queryset(self): return ClientProfile.objects.all() and my test code is class AllClientProfilesViewTest(APITestCase): def setUp(self): call_command('flush', interactive=False) self.user = User.objects.create_user(id='2' , phone_number=506879765) self.token = Token.objects.create(user=self.user) self.profile1 = ClientProfile.objects.create(name='Profile 1', ) self.profile2 = ClientProfile.objects.create(name='Profile 2', ) self.profile3 = ClientProfile.objects.create(name='Profile 3', ) def test_view_requires_authentication(self): url = reverse('myURL') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_get_all_client_profiles(self): url = reverse('myURL') self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) expected_profiles = ClientProfile.objects.all() self.assertEqual(len(response.data), expected_profiles.count()) for data, expected_profile in zip(response.data, expected_profiles): serializer = ClientProfileSerializer(expected_profile) self.assertEqual(data, serializer.data) but when I run it I got this error and I don't know how to fix it return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id -
{'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')}
I have a contact form on my website where users fill in their name, email and message to contact support which in this case is sales@mydomain.co and say the sender's email is abc@gmail.com. When a user submits the form, the form yields an error {'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')} The form works if the sender's email belongs to the organization sales@mydomain.co. Is it possible to for a user to send an email(using a different organization email, such as Gmail) through the online form? here is my forms.py class ContactForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) email = forms.EmailField(label='Your email', max_length=100) message = forms.CharField(max_length=600, widget=forms.Textarea) def send_mail(self): logger.info("Sending email to customer service") subject = "Site message" message = f"From: {self.cleaned_data['name']} <{self.cleaned_data['email']}>\n{self.cleaned_data['message']}" sender_email = self.cleaned_data['email'] # Use the user's email as the sender recipient_list = ['sales@mydomain.co'] # My domain email address send_mail( subject, message, sender_email, recipient_list, fail_silently=False, ) -
Attempting to migrate an Django ImageField, but failing to migrate
I am currently facing a problem with trying to migrate a Django Image field from a folder named media_root located inside a folder named static_cdn inside of my current project here is what my current file structure looks like as that may help; veganetworkmain -----profiles -------static_cdn ---------media_root ----------test.png Test.png is a png file that is generated using a picture generation algorithm using Pillow, here is what Test.png actually looks like: However what actually happens when I try to implement the code to get the picture into my program using a Django Image Field is that it just becomes white as seen here: I had tried methods like using python manage.py makemigrations, python manage.py migrate, changing the static by changing url_patterns and setting and even python ./manage.py makemigrations profiles. Here are the links to each method that I had tried: Django - makemigrations - No changes detected Page not found 404 Django media files And finally here is my code that I am currently working with during this time: models.py from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User from .utils import get_random_word from django.template.defaultfilters import slugify from django.db.models import Q -------------------------------------------------- class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) … -
400 Bad Request Error in an application using Django, Gunicorn, and Nginx
I've been trying to troubleshoot my issue with no success for a while now, so I hope posting here helps. I am developing an application using Django REST Framework, Gunicorn, and Nginx. The idea is to have Gunicorn serve the Django applicaiton, and have Nginx be used as a reverse proxy that holds the SSL certs. I've referenced multiple guides on hosting applications using these three technologies, with little success. I have my Django application connected to gunicorn using a sock file on port 80, and my Nginx server blocks listen for both port 80 and 433 (for SSL purposes). I have tried just about everything I can think of, and yet I am still getting a 400 - Bad Request error whenever I navigate to the domain that should serve the API. This is my Nginx sites-available file, with just a couple of names changed for security purposes: server { listen 80; server_name www.querymarketplace.net; return 301 http://querymarketplaceapi.net$request_uri; } server { listen 80; server_name querymarketplaceapi.net 157.245.10.103; location /static/ { root /home/jbisc/qm_marketplace/; } location / { include proxy_params; proxy_pass http://unix:/home/jbisc/qm_marketplace.sock; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; } } server { listen 443 ssl; listen [::]:443 ssl; # Optional: … -
How do I pass a Javascript variable to my Django framework to be used in template or via get_context?
I have been working to pass form values to a modal using Django. I have gotten most of the way there, but I can't quite make out how to connect the two.... Here is my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here is my HTML... <button class="button209" id="avail">Check Availability</button> <div id="myModalavail" class="modal"> <div class="modal-content"> <span class="close"></span> <img class="logo4" src="/static/images/threecircles.svg"> <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> <td class="title117">Yes</td> </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> </div> Obviously, form.approvers is going to give me all of the eligible approvers in my form....However I'm just trying to pass the selected approvers... This line of code is working flawlessly.... var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); It is getting the … -
A function working in a custom file but not in a "custom migration" on Django
I am beginner in Django and just started learning migrations. In a DB table, I am trying to remove a row that has a specific field value. When I create a custom file which uses Django settings, the function properly deletes the row. But when I use the snippet in another function in a custom migration file, the deletion doesn't take place. It is possible that I am missing something elementary as a beginner. So I am trying to delete all orders the status of which is cancelled. The function that works in a separate file is: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_skeleton.settings") django.setup() from main_app.models import Order def delete_test_fnc(): all_orders = Order.objects.all() for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() delete_test_fnc() The custom migration where delete doesnt work (other two modifications work without issues) is: from datetime import timedelta from django.db import migrations CURRENT_ORDERS = [] def modify_delivery_warranty(apps, schema_editor): global CURRENT_ORDERS orders = apps.get_model("main_app", "Order") all_orders = orders.objects.all() CURRENT_ORDERS = all_orders for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() elif order.status == "Pending": order.delivery = order.order_date + timedelta(days=3) elif order.status == "Completed": order.warranty = "24 months" order.save() … -
anyone face this issue in django?
enter image description here when i created a employee form and view the form it show like as image. <tr> <td>{{ form.employee_name.label }}</td> <td>{{ record.employee_name }}</td> </tr> <tr> <td>{{ form.dob.label }}</td> <td>{{ record.dob }}</td> </tr> <tr> <td>{{ form.age.label }}</td> <td>{{ form.age }}</td> </tr> only age field show like this, i review all my code , it didnt find and issue, if face same issue please help me