Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i calculate the remaining amount of all customer in Django?
I want to calculate the get_remaining_amount for all customers. I am trying to retrieve the get_remaining_amount of all my customers. I don't understand how can i get that amount? models.py class Customer(models.Model): """Customer Model""" name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-created_on'] def get_remaning_amount(self): # Remaining Amount property_price = self.prop_select.price payment_done_by_customer = Payment.objects.filter(customer=self).aggregate(Sum('amount'))['amount__sum'] or Decimal('0') return property_price - payment_done_by_customer -
How do I do exponential or natural log in Django?
I have a formula, say, trustworthy = mt.exp(np.log(age) + wealth**2). I know this is written using numpy and math in Python. Nonetheless, I am not sure how to implement this in Django. What I did was from django.db.models.functions import Power,Ln,Exp trustworthy = Exp(Ln(age) + wealth*wealth) Nonetheless, there was an error and when I print out trustworthy, it became a string: Exp(Ln(Value(55))) + 16 Thanks a lot for helping ! -
Django 'str' object has no attribute 'add'
I am getting this error for below two line: subscriber.email.add(self.cleaned_data.get('email')) subscriber.address.add(self.cleaned_data.get('address')) I am using AbstractUser model and trying to add extra fields by adding new model class. Here is my code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=100) address = models.CharField(max_length=100) froms.py class SubscriberSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) address = forms.CharField(max_length=100) class Meta(UserCreationForm.Meta): model = UserManagement @transaction.atomic def save(self): user = super().save(commit=False) user.is_subscriber = True user.save() subscriber= Subscriber.objects.create(user=user) subscriber.email.add(self.cleaned_data.get('email')) subscriber.address.add(self.cleaned_data.get('address')) return user views.py class SubscriberSignUpView(CreateView): model = UserManagement form_class = SubscriberSignUpForm template_name = 'registration.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'subscriber' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('blog:my-account') console error: File "P:\django\django\farhyn\members\forms.py", line 21, in save subscriber.email.add(self.cleaned_data.get('email')) AttributeError: 'str' object has no attribute 'add' [27/Jul/2021 08:29:31] "POST /subscriber-signup/ HTTP/1.1" 500 99927 -
Python and Django - assigning fields in dict instead of overwriting?
I'm using a Python dict to map strings to Django fields. I want to update, or assign the value of the fields as so. self.sheet_headers_2_fields = { 'Index': self.index, 'Device Model': self.model, 'MAC address': self.mac_address, 'IP Address': self.ip_address, } for sheet_header, model_field in self.sheet_headers_2_fields.items(): model_field = item.get_field_value(sheet_header) I'm using the dict to make it easier to map strings to fields should more fields be added. Currently, this just overwrites model_field, instead of assigning it to the corresponding field, and thus, the model is not updated. Why does this not work? I know that Python passes by reference - my guess is that because model_field (A django field) is not the same type a item.get_field_value(sheet_header) (a str), it overwrites to a reference instead of updating the value. How can I achieve what I want, either with a dict, or some other method? -
Custom template filter and query
I'm attempting to get all active employees using a template filter, but I'm not having much luck. I was wondering if you might know why. models.py class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) active = models.BooleanField(default=False) My template filter is as follows: @register.filter def active_employees(model_instances): return model_instances.filter(active=False) template.html {% if request.user.employee.all|active_employees|length > 0 %} There is an active employee {% endif %} The error I get is as follows: Invalid filter: 'actual_employees' -
Update a Queryset in Django instead of For loop
I am trying to update a queryset, I would like to calculate a Field order class Temporal(model.Models): name=models.CharField(max_length=60) created_at = models.DateTimeField(auto_now_add=True) order = models.IntegerField(null=True, blank=True) in my app it is important to order_by created_at, and then assing a order as index, everytime a new object is created assing value cero and the rest of the objects the need to be plus +1, but I would like to do using queryset instead of using a for loop : items = Temporal.objects.all().order_by('-created_at') for index, item enumerate(items): item.order=index + 1 item.save() assuming thousands of items on the database this would be very slow... thanks in advance -
Deploy Django + React.js on Heroku
i'm currently deploying django with react in Heroku. But there is an issue when the deployment success, there is no "frontend" from react.js When i'm access the webpage in link below, It's just display an error page not found. I want to display component of React.js in the website https://mmuqiitf-react-django.herokuapp.com/ This is my folder structure : /backend /build /node_modules /public /src /staticfiles /todo .gitignore Aptfile db.slite3 manage.py package.json Procfile requirements.txt runtime.txt And this is my settings.py code : from pathlib import Path from django.conf import settings import django_heroku import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'todo' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Searchable Dropdown in Website - Django - Saving to data base
I am building a website and part of it involves a drop-down which is easily called in the HTML by {{ form.inspection_type }}. This is a pretty big drop-down and a pain to scroll all the way to what you need to select so I have been trying for the past few days to implement a searchable drop-down to replace it. I have tried every single library I would find on searchable drop-downs and non have worked with the specifics of my project. I have reverted to doing it through HTML and have again gone through about 40 different examples and iterations and have gotten close. The NEW code is a searchable drop-down that is populated with my Django database drop-down. However when I click submit it shows that no data was added to the list view that I have. Below is the old code that worked and didn't have a searchable drop-down and also I have added the new code that has the searchable drop-down but won't submit the data through. Let me know if I missed anything and you have any questions. Thanks! OLD - works but no searchable drop-down <form method="post" action=""> {{ form.inspection_type }} <input class="btn … -
Is it possible to control the visibility of a Featuregroup in folium with a html checkbox?
I'm working on a project in Django were I want to show layers on a map by checking or unchecking boxes which I created using bootstrap. I am aware it is possible to use LayerControl to get these boxes, but I would like to use the boxes I created. Is this possible in Folium? This is my views.py in Django. def third_view(request): m = folium.Map(width='100%', height='90%', crs='Simple', tiles=None) base_map = folium.FeatureGroup(name='Basemap', overlay=True) image= 'static/images/stitched_map.png' bounds=[[0, 0], [750, 750]] overlay = folium.raster_layers.ImageOverlay(image, bounds).add_to(base_map) base_map.add_to(m) html = 'Here lies Balin, son of Fundin' iframe = folium.IFrame(html) popup = folium.Popup(iframe, min_width=200, max_width=200) layer1 = folium.FeatureGroup(name='layer1', overlay=False) folium.Marker([350, 350], icon=icon_circle, tooltip='TA 1267', popup=popup).add_to(layer1) layer1.add_to(m) m.fit_bounds(bounds) m = m._repr_html_() context = { 'map': m, } return render(request, 'third.html', context) This is my html page/checkbox which I want to link it to: <div class="row"> <div class="col-sm-10"> {{ map|safe }} </div> <div class="col-sm-2"> <h3><span style="color: #e8c4b4;">Places</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Cities</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Points of Interest</label> </div> <h3><span style="color: #e8c4b4;">Travels</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Frodo</label> </div> </div> </div> This is the not yet working webpage -
get related model set in template
I've got a a model that is related to the User model class Employee(models.Model): user = models.ForeignKey(User, related_name='actual_user', on_delete=models.CASCADE, null=True, blank=True) employee_user = models.ForeignKey(User, related_name='employee', on_delete=models.CASCADE, null=True, blank=True) Within my template, i'd like to get all instances of Employee where employee_user matches the current user who is logged in. {% for employee in request.user.employee_set.all %} This is an employee. {% endfor %} This doesn't seem to be working. I was wondering if you might know why. Thanks! -
How to build the 404 page in Django
I'm making a blog in Django, and I've to add the 404 page i need to know how to add the not found error page 404 in Django If there's any easier way just by making the 404 html page and show in views really without complications Thanks a lot -
How to render a page based on the button clicked on another page django
I have a page like that {% for product in products %} <div class="col-lg-4"> <img alt="" class="thumbnail" src="{{ product.images.all.0.image.url }}"> <div class="box-element product"> <h5><strong>{{ product.name }}</strong></h5> <hr> <button data-product="{{ product.id }}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a data-product="{{ product.id }}" data-action="Save" class="btn btn-outline-secondary detail" href="{% url 'detail' %}"> Detail</a> ..... and when the user click on Detail, it should go to another page to display the details of the product based on which detail button he clicked on so I made detail.js file like that var detailBtns = document.getElementsByClassName("detail") //get all add to cart button with class update-cart for (i = 0; i < detailBtns.length; i++) { detailBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId ) console.log(current_user) GetDetail(productId, action) // this function will be called and will pass product id and action in body to your view for further processing. }) } function GetDetail(productId, action){ console.log("func") var url = '/detail/' fetch(url, { method: 'POST', headers:{ 'content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"productId": productId, "action": action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } and in the views there's a function that is connected to the URL detail/ def detail(request): data = json.loads(request.body) productId … -
allauth replace username field with custom one
I'm using allauth I want the user to login with user id instead of username field. when I try to set the setting.py for it settings.py: USERNAME_FIELD = None ACCOUNT_AUTHENTICATION_METHOD = 'user_id' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False it gives me this error AssertionError at /accounts/login/ No exception message supplied Its possible to have both user id and username but I want to login with only user id forms.py: class CustomLoginForm(LoginForm): user_id = forms.IntegerField(required= True, validators=[ MinValueValidator(10_000_000_00), MaxValueValidator(99_999_999_99) ], label='User ID') class Meta: model = MyUser fields = ('user_id',) exclude = ('username',) def login(self, request, user): user.user_id = self.cleaned_data['user_id'] user.save() return user, super(CustomLoginForm, self).login -
Django Admin (display database entry if value > x)
Good evening, I created a new database table in models.py (persons) which has name,age,active Now I added this code in the admin.py: class personsAdmin(admin.ModelAdmin): list_display = ('name','age') admin.site.register(persons, personsAdmin) In the admin area it shows me every person I added to the database. So far so good, but now I want to see only the person where active > 0. Can I do this in Django admin.py? -
A tree caret layout wherein whole website is accessible on basically one page
I am hoping I can get some direction on things I need to learn to get this implementation right. I don't want to take too much of your time - no need to actually write any code. I am hit by inspiration to have main index page on my app project be like a parts explosion navigation (e.g. like a popular car parts store where it has a caret system with list of makes > your vehicle model > your type of part > your part). My app isn't related at all I just like idea of having whole website on one page. So far as I understand it I could redesign my database and use some mptt or recursion. At my current proficiency level, I could only render a template with some dictionary or some other structure containing the skeleton of the database and then make little Ajax calls as the carets are clicked to fill in the details. Would this be really tacky? Any re-directs or encouragement would really really be appreciated. -
Django Design Philosophy
i wrote an small, resume web application which contains a profile (ManyToOneRel to User Model), Experience, Education,Skills,Awards and ... Models And a single CBV View inherited from TemplateView its working fine but i wrote this small, simple app so i can focus on some django design philosophies .. i want to know how can i follow some main principles like DRY, KISS and many other principles in my App class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') avatar = models.ImageField(upload_to=upload_image_path, null=True) phone_number = models.CharField(max_length=11) bio = models.TextField() state = models.CharField(max_length=90) city = models.CharField(max_length=90) interests = models.TextField(blank=True) github = models.CharField(max_length=230, blank=True) linkedin = models.CharField(max_length=230, blank=True) instagram = models.CharField(max_length=230, blank=True) telegram = models.CharField(max_length=230, blank=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' def __str__(self): return self.user.username class Experience(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='experiences') title = models.CharField(max_length=40) company_name = models.CharField(max_length=40) description = models.TextField() start = models.DateField() end = models.DateField() class Meta: verbose_name = 'Experience' verbose_name_plural = 'Experiences' def __str__(self): return self.title Index.html {% extends 'shared/_MainLayout.html' %} {% block content %} {% include 'resume_main/components/index/Nav.html' %} <div class="container-fluid p-0"> {% include 'resume_main/components/index/About.html'%} {% include 'resume_main/components/index/Experience.html' with experiences=profile.experiences.all %} {% include 'resume_main/components/index/Education.html' with educations=profile.educations.all %} {% include 'resume_main/components/index/Interests.html' with interests=profile.interests %} {% include 'resume_main/components/index/Skill.html' with skills=profile.skills.all %} … -
How do I resolve the following error in Django: "OperationalError: foreign key mismatch"
I'm getting the following error whenever I attempt to save to the table in a SQLite database: foreign key mismatch - "procedure_tbl" referencing "filename_tbl" In models.py, these are the tables that the error is referring to: class FilenameTbl(models.Model): rowid = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='FileID', db_column='rowid') filename = models.TextField(blank=True, null=True) creation_datetime = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'filename_tbl' ordering = ['rowid'] class ProcedureTbl(models.Model): rowid = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ProcedureID', db_column='rowid') ... filename_id = models.ForeignKey(FilenameTbl,db_column='filename_id', to_field='rowid',null=True,blank=True,on_delete=models.SET_NULL) class Meta: managed = False db_table = 'procedure_tbl' ordering = ['rowid'] Data can be read from the tables and querysets like the following return the correct data: queryset = FilenameTbl.objects.values( 'rowid', 'filename', 'proceduretbl__rowid') Raw SQLite commands to write/update to the ProcedureTbl table function properly. If I removed filename_id from the ProcedureTbl, then data can be saved to the table. -
Azure active directory SAML SSO configuration issue with Django backend
I am trying to set up SAML Single Sign-On (SSO) with my Django app, but I am getting an error when I try to login to my app. I go to the app url, Microsoft processes the request (the url displays microsoft.loginonline.com/etc briefly), and then I get redirected to this page: https://my-app.azurewebsites.net/.auth/login/aad/callback which displays this error: {"code":400,"message":"IDX10501: Signature validation failed. Unable to match keys: \nkid: '[PII is hidden]', \ntoken: '[PII is hidden]'."} The reply url is set to: https://my-app.azurewebsites.net/.auth/login/aad/callback I did the set-up following both the Azure docs and following this documentation: https://django-auth-adfs.readthedocs.io, it's ostensibly working on my localhost, just not on the actual azure app service... I am unsure of what I am doing wrong, and the error message is not very informative for me as I am new to back-end programming and cloud. Any help appreciated, thanks! -
Django not auto-filling a new html file
starting to learn django, and in the video im watching django automatically fills minimum html code when you create a new html file in the templates folder, but its not happening for me. i can switch to HTML language mode and ctrl+space & choose HTML_sample, but its not the same code as shown in the video. is it just a pycharm thing? the video uses pycharm, but they say the Django autofills the code so didnt think it was the issue. the html files path: "project_name\app_name\templates\app_name" using VScode 3.9 and django 3.2.5. (had some trouble with django-html, had to add it manually to the settings.json) -
Django Rest: Why is the access denied, although AccessAny is set as permission?
I want to give all people, without any permissions access to my API. The following definitions I made in my files: views.py from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.parsers import JSONParser from rest_framework.permissions import AllowAny from django.http import HttpResponse, JsonResponse from rest_framework import status from api.models import Application, Indice, Satellite, Band from api.serializers import OsdSerializer import logging logger = logging.getLogger(__name__) class OsdView(APIView): permission_classes = [AllowAny] def get(self, request): applications = Application.objects.all() serializer = OsdSerializer(applications, many=True) return Response({"Applications:": serializer.data}) class DetailView(APIView): permission_classes = [AllowAny] def get(self, request, machine_name): application = Application.objects.get(machine_name=machine_name) downloads = OsdSerializer(application, context={"date_from": request.query_params.get("from", None), "date_to": request.query_params.get("to", None), "location": request.query_params.get("location", None), }) return Response(downloads.data) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } But when I access the API the result is the following instead of the content: {"detail":"Invalid username/password."} -
No installed app with label 'polls' - activating models - error
I am learning Django3.2.5, from https://docs.djangoproject.com/en/3.2/intro/tutorial02/. I created a project with the name, 'mysite', then 'polls' app, and using the default 'SQLite' database. Project's (mysite) file hierarchy: mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py App's (polls) file hierarchy: polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py mysite/mysite/settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.29. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '4)2m9i5*y=icl-9bpiw#w@n!(y^y%38+8smh70mqupeppb&o#r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': … -
502 Bad Gateway nginx/1.20.0 Error when Deploying Django app using AWS Elastic Beanstalk
I was following closely following AWS's documentation on how to deploy Django apps using Elastic Beanstalk until I received a 502 Bad Gateway nginx/1.20.0 Error when opening my app. From there, I followed a couple of solutions offered by users that suffered similar problems. Specifically, I added a Procfile and went about editing how my django.config file was set up. However, the error still remains and I would like some guidance on how to tackle this problem. Below are the relevant logs and files: eb-engine.log django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hifive.wsgi:application Procfile web: gunicorn --bind :8000 --workers 3 --threads 2 djangoproject.wsgi:application settings.py """ Django settings for djangoproject project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'thesecuritykey' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost','127.0.0.1','djangoproject.eba-fuipjhfa.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS … -
How can I test a single field in a form?
I want to create a test that would confirm that in case of a user not putting any input into the question field, the error will be raised. def test_new_question_form_no_question(self): form = NewQuestionForm(data={ 'question': "", 'choice1': "ok", 'choice2': "fred@example.com", 'choice3': None }) self.assertEqual(len(form.errors), 1) That would probably be a perfect solution, but it doesnt work for me. Here I'll show why: class NewQuestionForm(forms.Form): question = forms.CharField(label='Question', max_length=1000) set = re.compile(r'fuck') choice1 = forms.CharField(label="Choice 1", validators=[RegexValidator(regex=set, inverse_match=True)]) choice2 = MultiEmailField() choice3 = forms.BooleanField(required=False) def clean_choice2(self): data = self.cleaned_data['choice2'] if 'fred@example.com' not in data: raise ValidationError("You've forgotten about Fred") return data def clean(self): super().clean() cc_myself=self.cleaned_data['choice3'] subject = self.cleaned_data**['question']******** if cc_myself and subject and 'help' not in subject: msg="What are you doing?" self.add_error('question', msg) In the part, which i highlighted with ******, there is this reference to question and because i didnt put a question in a test, this part cannot be executed. Thats why i struggle with testing if the form accepts only a filled question field. I tried this way def test_new_question_form_no_question(self): form = NewQuestionForm(data={ 'question': "", 'choice1': "ok", 'choice2': "fred@example.com", 'choice3': None }) self.assertFalse(form.is_valid()) Unfortunately doesnt work too. The thing that is shown on my terminal after i type ,,py … -
How to load ckeditor on Django project
I have a django project that have to following structure. -node_modules -src -account -chat -templates/chat chat.html -DjangoChat (my app) -venv .gitignore package-lock.json Inside chat.html I'm trying to load the ckeditor that is inside node_modules. <script src="/node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script> <script> ClassicEditor .create( document.querySelector( '#editor' ) ) .then( editor => { console.log( editor ); } ) .catch( error => { console.error( error ); } ); </script> for some reason is not working. The structure of my project is correct? If is, how I can access the ckeditor file? -
how to mount different volumes of your docker-compose with AWS EFS using django react and postgres
while using AWS ECS Fargate, how do we mount files in AWS EFS from the volumes of different applications being used in the docker-compose? version: "3.9" services: backend: build: ./backend restart: "on-failure" volumes: - ./backend:/backend <======= THIS ONE - ./backend/static:/backend/static <======= THIS ONE ports: - 8000:8000 ... db: image: postgres:latest restart: always volumes: - postgres_data:/var/lib/postgresql/data/ <======= THIS ONE ... frontend: build: ./frontend volumes: - ./frontend:/frontend <======= THIS ONE I have the above configuration of my docker-compose and what i am trying to achieve is to make sure all those volumes <=== THIS ONE persist no matter what happen to my AWS ECS Fargate Task From what i read i must use AWS EFS and define that option in the task definition, but my question is to know whether i could persist all of those volumes from my docker-compose at once when i provide the single path in AWS EFS or should i provide a single path for each one of the volume above?