Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm learning Django but I keep getting this error when I type : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I Have a Creating Superuser But I'm facing some Error till superuser run on Server. So, Give me A Solution of This Error. My models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone = models.CharField(max_length=10) cpassword = models.CharField(max_length=10) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ("email",) objects = CustomUserManager() -
Convert Django-React dynamic website to static site
I want to convert my personal portfolio website here into a static site. Currently, I am deployed on AWS Elastic Beanstalk which has gotten expensive over the last year or so, due to me running out of AWS free tier. I'd like to convert the following routes: https://www.tomaspremoli.com/ https://www.tomaspremoli.com/#/tutoring https://www.tomaspremoli.com/#/portfolio https://www.tomaspremoli.com/#/resume into static html pages, save all images that are fetched in the code, and save all api call responses. Some api calls just run on page load, however, some api calls happen in js after buttons are clicked (such as when getting pictures for specific portfolio entries). I have access to the source code and all the root user permissions, and am not sure what the best course of action is here. I can't seem to find a tool that does this for me easily, and have been toying around with the Pupeteer js library, with some progress, but also out of my area of expertise and struggling to get much done. Is there any tools that could simplify this for me? So far i've tried various manual processes that don't seem to get me very far. -
Django-server fails for ModuleNotFoundError: No module named '_ldap' when started by apache
When started in python 3.9 virtual environment by python manage.py runserver my django-server works fine, but when started by apache with the same virtual environment configured into python path it fails with the errors below: [Mon Mar 11 11:00:49.683439 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] from .ldapauth import * [Mon Mar 11 11:00:49.683446 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] File "/srv/django/pxpro/pxpro_editor/ldapauth.py", line 4, in <module> [Mon Mar 11 11:00:49.683495 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] import ldap [Mon Mar 11 11:00:49.683501 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] File "/srv/django/pxpro-env/lib/python3.9/site-packages/ldap/__init__.py", line 34, in <module> [Mon Mar 11 11:00:49.683504 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] import _ldap [Mon Mar 11 11:00:49.683512 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] ModuleNotFoundError: No module named '_ldap' I'm using django 4.2.10 with pyldap==3.0.0.post1 and python-ldap 3.4.4 in my python virtual environment my apache.conf: $ cat /etc/httpd/conf.d/pxpro.conf <VirtualHost *:8031> ServerAdmin <myserverAdmin> ServerName <myServer> # ServerAlias <server_fqdn> ErrorLog /var/log/httpd/pxpro-error_log CustomLog /var/log/httpd/pxpro-access_log combined LogLevel debug HostnameLookups Off UseCanonicalName Off ServerSignature Off Alias /media/ /srv/django/pxpro/media/ Alias /static/ /srv/django/pxpro/static/ #RedirectMatch 301 "^/static/media/uploads/(.*)$" "/media/uploads/$1" <IfModule wsgi_module> WSGIDaemonProcess pxpro_wsgi user=django group=django home=/srv/django python-home=/srv/django/pxpro-env startup-timeout=15 python-path=/srv/django/pxpro-env/lib/python3.9/site-packages WSGIProcessGroup pxpro_wsgi WSGIApplicationGroup pxpro_wsgi WSGIScriptAlias / /srv/django/pxpro/settings/wsgi.py process-group=pxpro_wsgi application-group=pxpro_wsgi </IfModule> ... Any idea … -
Im getting this error in my file in my decorate.py file
This is the error i get Although I tried to remove the httpresponse from my code even that isn't solving the issue. from multiprocessing import context from django.http import HttpResponse from django.shortcuts import redirect, render def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.authenticated: return redirect('homepage') else: return view_func(request,*args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request,*args, **kwargs): group is not None if request.user.groups.exists(): group=request.user.groups.all()[0].name if group in allowed_roles: return view_func(request,*args, **kwargs) if group == 'user': return render(request,'loginapp/user_dashboard') '''else: return HttpResponse('you are authorized')''' return wrapper_func return decorator def admin_only(view_func): def wrapper_func(request,*args, **kwargs): group is not None if request.user.groups.exists(): group=request.user.groups.all()[0].name if group == 'user': return render(request,'loginapp/user_dashboard') if group == 'admin': return render(request,'loginapp/admin_dashboard') return wrapper_func .......................................................................... -
Task Queue with cached libraries in Django
I am creating a WEB interface for various Python scripts through Django. Example in calculation.py I would have : import datetime def add_time(a, b): return = a + b + int(datetime.datetime.now()) Usages : A user could say "I want to run add from calculation.py with arguments [1, 3]" and that returns him the result when it's ready. A user could say "I want this to run add from calculation.py with arguments [1, 3] every 10 minutes and check if result is greater than X" and that would action something if it's true. Most of my script functions are quick but they need to import libraries that takes a lot of time to load. I am currently doing this directly with my Django service ; it's simple and load the libraries once which allows most of the next calls to be very fast but sometimes a heavy call is made and that is slowing down all my Django application and I seem limited if I want to have CRON scheduling for some scripts. Therefore I am looking at another solution. I started to look at : Celery (but it seems not supported anymore on Windows) Huey and Dramatiq Django-Q2 (easy to … -
Using slugs with Django (Form + Model)
I have the following error: Error in page Django admin DB Shell object The logic that I use in Django is based on a model and the ModelForm class. Here is the model: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse class Ingredient(models.Model): name = models.CharField(max_length=100) def __str__(self): return f'{self.name}' class Recipe(models.Model): slug = models.SlugField(null=True, unique=True, blank=True, editable=False) title = models.CharField(null=False, max_length=100) description = models.CharField(null=False, max_length=250) preparation = models.TextField(null=False) score = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) last_update = models.DateField(auto_now=True) presentation_image = models.ImageField(upload_to='images', null=True, blank=True) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return f'{self.slug}, {self.title}, {self.description}, {self.preparation}, {self.score}, {self.last_update}, {self.presentation_image}, {self.ingredients}' Here is the RecipeForm: from django import forms from django.core.validators import MinValueValidator, MaxValueValidator from .models import Recipe from .models import Ingredient class RecipeForm(forms.ModelForm): class Meta: model = Recipe exclude = ['slug', 'last_update'] widgets = { 'preparation': forms.Textarea() } labels = { 'title': 'Title', 'description': 'Description', 'preparation': 'Preparation', 'score': 'Score', 'presentation_image': 'Presentation Image', 'ingredients': 'Ingredients' } I understand that the problem is based on the fact that no slug is generated (since it is None in the shell). Since my path for a single recipe is based on a slug then Django simply tells me "Hey dude, no slug to … -
split payments using stripe in django
I am working on a project where, buyer will make the payment and that payment should be split into application-fee seller payment referral payment her is my code if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + taxes # if referrals: admin_amount = int((total_charges - shipping_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) payment_info = { "amount": total_charges, # Amount in cents "currency": "usd", "connected_accounts": [ {"account_id": 'acct_1OoODQIbLDChIvG2', "amount": seller_amount}, {"account_id": "acct_1OrzPRI5g3KKKWKv", "amount": referral_amount}, ] } stripe.api_key = "sk_test_EI5Kddsg2MCELde0vbX2cDGw" try: for account_info in payment_info["connected_accounts"]: # Set up transfer amount and destination separately transfer_amount = account_info["amount"] destination_account = account_info["account_id"] print("=======================================================", destination_account) session = stripe.checkout.Session.create( success_url=my_domain + '/payment_success/' + str(auction_id) + '/' + courier_id + "?mode=" + mode, cancel_url=my_domain + '/payment_failed/' + str(auction_id) + '/' + courier_id + "?mode=" + mode, payment_method_types=['card'], mode = 'payment', line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'NailSent Nails', }, 'unit_amount': int(total_charges), # amount should be in cents }, 'quantity': 1, }], payment_intent_data={ 'transfer_data': { 'destination': destination_account, 'amount': transfer_amount, # amount should be in cents } }, ) except stripe.error.StripeError as e: return HttpResponse(f"Error: {e}") i was trying to split … -
"AttributeError: 'NoneType' object has no attribute 'startswith' in Django Djongo"
I am encountering an AttributeError in my Django application while using Djongo as my database backend. The error message is as follows: AttributeError at /loginPage 'NoneType' object has no attribute 'startswith' This error occurs in the quote_name method in operations.py. Here is the relevant code snippet: class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name return '"{}"'.format(name) I understand that this error typically arises when a method is called on a NoneType object, but I'm unsure why it's happening in this context. Could anyone please provide insights into why this error might occur and how to resolve it? I'm using Django with Djongo as my database backend. Additionally, I'm trying to implement functionality where form data goes to two different collections in my MongoDB database. I've attempted to modify the code accordingly, but I'm encountering this error. Below is a snippet of the code where the error occurs: #forms.py class UserAdminCreationForm(UserCreationForm): company_name = forms.CharField(max_length=100) ROLE_CHOICES = [ ('admin', 'Admin'), ('user', 'User'), ] role = forms.ChoiceField(choices=ROLE_CHOICES, label='Role') email = forms.EmailField(required=True) class Meta: model = get_user_model() fields = ['company_name','role','first_name', 'last_name','email', 'password1', 'password2',] def save(self, commit=True): user = super().save(commit=False) # Get the user object without saving to the database yet user.company_name … -
Wagtail How to get the value of an orderable
I am a relative newcomer to programming Wagtail My attempt is a cascaded application where the title is formed from the relation to the underlying element. The cascade should be structured like this Fach --> Reihe --> Ebene --> Behaelter My models.py from django.db import models from django.utils.text import slugify from wagtail.models import Page from wagtail.admin.panels import FieldPanel # InlinePanel # PageChooserPanel from django import forms from wagtail.admin.forms import WagtailAdminPageForm from django.utils.translation import gettext_lazy as _ # Create your models here. class NoTitleForm(WagtailAdminPageForm): title = forms.CharField(required=False, disabled=True, help_text=('Title is autogenerated')) slug = forms.CharField(required=False, disabled=True, help_text=('Slug is autogenerated')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.initial['title']: self.initial['title'] = _('auto-generated-title') if not self.initial['slug']: self.initial['slug'] = _('auto-generated-slug') class ReihePage(Page): base_form_class = NoTitleForm content_panels = [ MultiFieldPanel( [ InlinePanel("Fach", label="Fach", min_num=0, max_num=10), ] ), FieldPanel('title'), FieldPanel('slug'), ] def clean(self): super().clean() new_title = "anzahl from Fach" + "title from Fach" <--** How to get the values from the InlinePanel** self.title = new_title self.slug = slugify(new_title) class ReihePageOrderable(Orderable): page = ParentalKey(ReihePage, related_name="Fach", null=True) fach = models.ForeignKey("Fachpage", on_delete=models.SET_NULL, null=True) anzahl = models.IntegerField(default=1) class FachPage(Page): laenge = models.IntegerField(null=True, blank=True, verbose_name='Länge in mm') breite = models.IntegerField(null=True, blank=True, verbose_name='Breite in mm') content_panels = [ # FieldPanel('bezeichnung'), FieldPanel('laenge'), FieldPanel('breite'), FieldPanel('title'), … -
ModuleNotFoundError: No module named " CustomModule"
I've had a problem for a week now. I can't integrate unit tests into my Django project. I wanted to test one of my models. I did the necessary import to retrieve the class from models.py. But when I run the test, I get this error: ModuleNotFoundError: No module named "application name". Despite configuring the application in setting.py in INSTALLED_APPS. All the init files are present. And I have double-checked the names. I don't know why I have this problem. When I run the runserver, I get a 200 response. Everything works, but when I try to run a test... I see this error. Thank you for enlightening me. Best regards. Creating a simple test without importing the model works. So it's definitely linked to the module. It's not being found. -
Can I connect my django app container to connect the mysql databse on my local machine?
I have a django application which is running in a container.. I was trying to connect to mysql databse running on my local machine.. In the settings.py of django project, I assing db_host to ip address my local machine for database configuration.. In container I tried to curl my local machine ip address and it worked fine.. Even then my django app gives the error..Can't connect to server on <ip_address>.. Is it even possible to connect if yes, then how?? My Dockerfile. # Use an official Python runtime as a parent image FROM python:3.9-slim # Set environment variables for Python ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory in the container WORKDIR /app # Copy the current directory contents into the container at /app COPY . /app # Install system dependencies for mysqlclient RUN apt-get update \ && apt-get install -y python3-dev default-libmysqlclient-dev build-essential pkg-config gcc curl \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies RUN pip install --upgrade pip \ && pip install -r requirements.txt # Expose port 8000 to allow communication to/from server EXPOSE 8000 # Run the Django development server CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
cannot create from a factoryBoy class
I try to make a class a make some instances but I can't create any instance with the class in my django shell factories.py import factory from webshare.models import WebShareFileFolders class WebShareFileFactoryBoy(factory.django.DjangoModelFactory): class Meta: model = WebShareFileFolders inode = factory.Sequence(lambda n: n) name = factory.Faker('name') path = factory.Faker('text', max_nb_chars=50) is_dir = factory.Faker('boolean') and then the error in my console >>> from webshare.tests.factories import WebShareFileFactoryBoy >>> instance = WebShareFileFactoryBoy() Traceback (most recent call last): File "C:\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> TypeError: 'module' object is not callable >>> instance = WebShareFileFactoryBoy.create() Traceback (most recent call last): File "C:\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> AttributeError: module 'webshare.tests.factories.WebShareFileFactoryBoy' has no attribute 'create' Thank you for your help ;) Python 3.7.9 factory-boy 3.3.0 I just try to make instance from a factory class -
IntegrityError when I go to create superuser in Django
I am doing a blog project, I have made the user registration and login to be done through email, instead of using username. When I went to create the superuser to access admin, I get the following error in terminal. For the database I have connected it with PostgreSQL. django.db.utils.IntegrityError: llave duplicada viola restricción de unicidad «accounts_customuser_username_key» DETAIL: Ya existe la llave (username)=() Can someone help me with this problem? I hope you can guide me to solve this problem and to understand it so that I can solve it. Also to know if it is a problem with Django and the database configuration or if it has to do with PostgreSQL. -
Upload files to s3 bucket for a react js and django application
I am trying to use ASW s3 services to upload files. When clicked on a button to upload a file, the user should be able to select a file from his computer and upload it to the s3 bucket. The following code has been done by me views.py def upload_file(file_name, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False """ # If S3 object_name was not specified, use file_name if object_name is None: object_name = os.path.basename(file_name) # Upload the file s3_client = boto3.client('s3') try: response = s3_client.upload_file(file_name, 'my-bucket', object_name) except ClientError as e: logging.error(e) return False return True urls.py - Django app router = DefaultRouter() router.register(r'userdata', UserDataViewSet) router.register(r'education', EducationViewSet) router.register(r'workexperience', WorkExperienceViewSet) router.register(r'clientregistration', ClientRegistrationViewSet) router.register(r'jobdescription', JobDescriptionViewSet) router.register(r'assessment', AssessmentViewSet) router.register(r'appointment', AppointmentViewSet) urlpatterns = [ path('', include(router.urls)), path('api/recruiters/', get_recruiters, name='get_recruiters'), path('api/clients/', get_clients, name='get_clients'), path('submit-assessment/', submit_assessment, name='submit_assessment'), path('api/amanager/', get_accoutmanagers, name='get_accountmanagers'), path('api/job-descriptions/', get_job_descriptions, name='get_job_descriptions'), path('api/job-descriptions/<int:job_id>/assessments/', get_assessments_for_job, name='get_assessments_for_job'), path('clientregistration/', ClientRegistrationViewSet.as_view({'post': 'create'}), name='clientregistration'), path('api/get_user_details/', get_user_details, name='get_user_details'), path('submit_user_data/', submit_user_data, name='submit_user_data'), path('upload_file/', upload_file, name='upload_file') ] And on my react frontend const handleUploadResume = () => { // Assuming 'resumeFile' … -
How to Show Serializer Error in Django Templates
I created a register page using the Django rest framework, now I write all validation code in serializers.py and serializers.py in writing some errors but I can't see those errors in templates. class PersonSerializer(serializers.ModelSerializer): GENDER_CHOICES = [ ("male", "Male"), ("female", "Female"), ("other", "Other"), ] gender = serializers.ChoiceField(choices=GENDER_CHOICES) class Meta: model = Person fields = "__all__" def create(self, validated_data): gender = validated_data.pop("gender") validated_data["gender"] = gender.lower() return Person.objects.create(**validated_data) def validate(self, data: Union[str,int]) -> Union[str,int,None]: username = data.get("username") password = data.get("password") confirmpassword=data.get("confirmpassword") phone = data.get("phone") if Person.objects.filter(username=username).exists(): raise serializers.ValidationError('Username is allready exists') if len(phone) != 10: raise serializers.ValidationError("phone number is not valid") if password != confirmpassword: raise serializers.ValidationError('password not match') return data I expect to show an error in the Templates. -
client_max_body_size 0; is not being aplied even setting in every section
Why client_max_body_size 0; is not being aplied?? I'm receiving the following error trying to upload a file of 50M 413 Request Entity Too Large nginx/1.25.3 But I have setted the client_max_body_size 0; in every section My application is dockerized but mapping the config file to docker, so the config is working, but max body not client_max_body_size 0; upstream lito_upstream { # ip_hash; server viajah-api:8000; server front_viajah:3000; } server { client_max_body_size 0; location /static/ { client_max_body_size 0; autoindex on; alias /src/static/; } location /media/ { client_max_body_size 0; autoindex on; alias /src/media/; } location / { client_max_body_size 0; proxy_pass http://viajah-api:8000/; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Passa os cabeçalhos de cookie proxy_set_header Cookie $http_cookie; } listen 8000; server_name api.viajahturismo.com.br; } #server server { client_max_body_size 0; #Defines the port on which the server will listen for requests. include /etc/nginx/mime.types; location /media/ { client_max_body_size 0; autoindex on; alias /app/media/; } location / { client_max_body_size 0; proxy_set_header Host $host; proxy_pass http://front_viajah:3000; } listen 3000; server_name viajahturismo.com.br; } -
I made a "add to cart" function for my website but the js is not working
I made an add to cart function for my website So, in product-detail.html: <div class="button"> <input type="hidden" value="{{p.id}}" class="product-id" name=""> <input type="hidden" value="{{p.title}}" class="product-title" name=""> <a href="#" class="btn" id="add-to-cart-btn">Add to cart</a> <a href="#" class="btn">Buy Now</a> </div> and I also make a js file for this So, in function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajex({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price, }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Item added to cart") console.log("Added products to cart"); } }) }) In this code somethig is wrong with this portion dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Item added to cart") console.log("Added products to cart"); } Other thing is working perfectly well because In the console It is not displaying Adding products to cart and Item added to cart So Please help me out with this problem... -
`SSL: CERTIFICATE_VERIFY_FAILED` certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'. (_ssl.c:1007)
Issue Deploying Django Project on cPanel: Certificate Verification Error I am facing an issue while deploying my Django project on cPanel. The error indicates a certificate verification problem with the SMTP server 'smtp.gmail.com'. I have tried various solutions found online, but the issue persists. Here is my email configuration in settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '***' EMAIL_HOST_PASSWORD = '***' EMAIL_PORT = 587 Despite trying different solutions, I continue to receive the following error: csharp certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'. (_ssl.c:1007) I also attempted to create a custom EMAIL_BACKEND with the following code: import ssl from django.core.mail.backends.smtp import EmailBackend as SMTPBackend from django.utils.functional import cached_property class EmailBackend(SMTPBackend): @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context However, this resulted in the error: bash code 535, b'Incorrect authentication data' I also attempted to use GPT, but did not find any useful resources. The output from the openssl s_client command indicates a successful SSL handshake, but the common name (CN) in the server certificate is listed as grace.mysecurecloudserver.com, not smtp.gmail.com. Is there a problem with my … -
Passing input form value to URL variable
I need to pass the form input entered by the user to the URL variable in Django <form> <div class="input-group"> <input type="text" name="ticker" class="form-control" placeholder="Search"> <div class="input-group-btn"> <a her="{% url 'Main:search' %}" class="btn btn-default"> <i class="bi bi-search"></i> </a> </div> </div> </form> The input value needs to be passed as a variable in the following URL logic "{% url 'Main:search' %}" urls.py app_name = 'Main' urlpatterns = [ path("", views.index, name='index'), path('search/<ticker>', views.search, name='search'), ] views.py def search(request, ticker): ticker = ticker.upper() result = Symbol.objects.filter(symbol=ticker).first() if result is not None: return redirect('Symbol:index', ticker=ticker) else: return render(request, 'symbol_not_found.html') -
How to send extra parameter to unittest's side_effect in Python?
I'm using side_effect for dynamic mocking in unittest. This is the code. // main functionn from api import get_users_from_api def get_users(user_ids): for user_id in user_ids: res = get_users_from_api(user_id) // test script def get_dynamic_users_mock(user_id): mock_by_user_id = { 1: { "id": 1, "first_name": "John", "last_name": "Doe", ... }, 2: { "id": 2, "first_name": "Jane", "last_name": "Smith", ... }, ... } return mock_by_user_id[user_id] @patch("api.get_users_from_api") def test_get_users(self, mock_get_users) user_ids = [1, 2, 3] mock_get_users.side_effect = get_dynamic_users_mock # mock get_users_from_api get_users(user_ids) # call main function I want to send extra parameter from test_get_users to this get_dynamic_users_mock function. How to do this? -
How to change the background color of an input field of a Django form if it contains errors
I'm trying to code a form with fields that, if a user inputs data that doesn't pass the validation of the form, change their background colors from the default white to lightcoral. Here is a fragment of the HTML file that contains the form itself: <div id="div_formbox"> <form method="post" id="form_appointments"> {% csrf_token %} {{ form.non_field_errors }} <div class="input_group"> <div class="input_field {% if form.name.errors %}error{% endif %}"> {{ form.name}} </div> <div class="input_field {% if form.last_name.errors %}error{% endif %}"> {{ form.last_name }} </div> <div class="input_field {% if form.email.errors %}error{% endif %}"> {{ form.email }} </div> </div> <button type="submit">Send</button> </form> </div> And here is the part of the CSS file where I try to apply the color change to the input fields with errors: .error { background-color: lightcoral; } As you can see, I'm using Django tags to change the class of the form fields with errors from "input_field" to "error". Next, in the CSS file, I reference the "error" class to apply the styling I want. But it doesn't work. I've tried a bunch of variations but none have worked. I'm out of ideas. -
Celery server not terminating immediately when using prefork and without pool line command
I'm working on a django project with celery and redis installed. When I run the Celery server as 'celery -A main_proj -l debug -P solo' or 'celery -A main_proj -l debug -P threads', I can terminate them just fine by just pressing CTRL-C once or twice for warm/cold shutdown. However, when I run Celery as 'celery -A main_proj -l debug' and 'celery -A main_proj -l debug -P prefork', whenever I try to terminate them, it just get stuck at Worker: Stopping Pool. No matter how long I wait, it stays like that until I decide to terminate it with taskkill. I'm fine with the first two alternatives but I want to know why the latter options don't finish quickly. This is the code I have for my celery app: from __future__ import absolute_import, unicode_literals import os from celery.schedules import crontab from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main_proj.settings') app = Celery('main_proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Additionally, withing the settings.py file I set the CELERY_BROKER_URL with a redis URL that I get from Railway and I have the following code within the init file for the main_proj folder: from .celery import app as celery_app __all__ = ('celery_app',) This is what always happens whenever I … -
subdomain routing in django application
I have a django project that's hosted on a custom domain (e.g. mydomain.com). I have "app" app. For example, in development, requests looked like mydomain.com/app/dashboard. However, I wanted to use a subdomain instead so that my entire app is hosted on the subdomain app.mydomain.com and requests to mydomain.com/app/dashboard would route to app.mydomain.com/dashboard. I am using Nginx to handle this but I'm running into a few problems. Main part of nginx config: server { listen 443 ssl; server_name mydomain.co www.mydomain.co; location ~ ^/app(/?)(.*)$ { return 301 https://app.mydomain.co/$2; } location ~ ^/help(/?)(.*)$ { return 301 https://help.mydomain.co/$2; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # WebSocket specific headers proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } server { listen 443 ssl http2; server_name app.mydomain.co; location / { # Proxy to your Django application server proxy_pass http://127.0.0.1:8000; # Adjust the port to match your setup proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } # same for help When my url pattern is like this: path('app', include('app.urls')), and I try to access the dashboard it redirects to app.mydomain.com/dashboard which is not valid since /dashboard is a url exclusively … -
upload images in Django save onlyto folder but not saving to mysql database
I need help my code below save image to folder but not saving to mysql database. pls i dont knw where am getting it wrong. VIEW.PY def indeximg(request): if request.method == "POST": form=ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('uploadok') else: form = ImageForm() return render(request, 'indeximg.html', {'form': form}) def uploadok(request): return HttpResponse(' upload successful') IN MODEL.PY class Image(models.Model): caption=models.CharField(max_length=100) image=models.ImageField(upload_to='images/') -
Best method to model django database using through table to access associations by date
Looking for advice on a tidy solution for accessing The end result I am looking for is the following report: cast, start_date, wire, winch I currently run a script when a cast object is submitted via form to get the active wire associated with the cast, and save it in the 'wire' foreign key field. The active wire is accessed in the script through property tags. Technically this information is retained in the database through a series of models associating a cast with a wire (Cast-DrumLocation-WireDrum), and the date fields that store when the events occurred. These events update the association between cast and wire. Is the way I modelled this a proper solution?, or is there another solutions where the wire foreign key does not need to be stored as a field in the cast model. class Cast(models.Model): id = models.AutoField(db_column='Id', primary_key=True) startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') wire = models.ForeignKey('Wire', models.DO_NOTHING, db_column='WireId') winch = models.ForeignKey('Winch', models.DO_NOTHING, db_column='WinchId') class Drum(models.Model): id = models.AutoField(db_column='Id', primary_key=True\) location = models.ManyToManyField(Location, through='DrumLocation', related_name='active_location') material = models.TextField(db_column='Material') wiretype = models.TextField(db_column='WireType') class Winch(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.TextField(db_column='Name') drums = models.ManyToManyField(Drum, through='Drumlocation', related_name='active_drum') class Wire(models.Model): id = models.AutoField(db_column='Id', primary_key=True) nsfid = models.TextField(db_column='NsfId') drums …