Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a mobile app with django, with the same codebase?
I am trying to build an ERP system, same as TRYTN, ERPNEXT, ODDO. For the web version, I decided to go with Django and React. What I want is to have a mobile app of the same system too. Now my problem is to choose what tech stack to use for it. My company donot want to go with React Native for it. They want a solution with python itself. So I would like to know what option do I have , with python. This erp is really a data heavy software, there will be tens of thousand of records to be fetched at each api request. I looked at FLET(Write flutter app with python) framework, but it is really new. So any suggestion will be appreciated? I have tried to look at the code base of odoo/ tryton, but could not get any insight, as to how are they doing it. -
Facing a Cors error but that is already enabled in Django rest framework and react
I am facing one issue in my app which is developed in react and Django rest framework. In DRF api i am uploading the video and playing in react app. But video player slider not working then i have enabled the byte range request in my django rest app. But when i am enabling that setting then it giving a cors error in vtt Caption file. and also getting a cors error while downloading a pdf file from react app but when i am disabled the byte range request the video player slider not working but pdf downloading and video caption file working fine. Here is the code of byte range request in django rest app. byte range request code Please share your suggestions thanks i have enabled the byte range request in my django rest app. But when i am enabling that setting then it giving a cors error in vtt Caption file. and also getting a cors error while downloading a pdf file from react app but when i am disabled the byte range request the video player slider not working but pdf downloading and video caption file working fine. -
Could not find config for 'static files' in settings.STORAGES
This error occurs when running Django 4.2.The Default: django.contrib.staticfiles.storage.StaticFilesStorage has been deprecated. -
Problems to install Django in Windows
Now I'm using Windows10 and Python in vscode, When I tried to install Django by %pip install Django, there's the following error: Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))) - skippingNote: you may need to restart the kernel to use updated packages. Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))) - skipping WARNING: Ignoring invalid distribution -orch (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -cipy (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -orch (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -cipy (d:\program files\anaconda\lib\site-packages) WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF … -
User sign-in process in Django not working properly
I'm encountering an issue with the user sign-in functionality in my Django application. When attempting to sign in a user, I'm consistently receiving an error message stating "email and/or password is not valid!" instead of successfully logging in the user. I have verified that the email and password inputs are correct. I've also checked my code and ensured that I'm using the authenticate() and login() functions correctly. here is the code i tried, keep in mind that i am able to regester new users but not able to sign them in: def signup(request): # Extract data from form and assign it to variables. if request.method =='POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] # Check if user exists. user_exsit = User.objects.filter(Q(username = username) | Q(email = email)).exists() if user_exsit: error_message= 'User name or email already exists!' return render(request, 'user_auth/signup.html', {'error_message': error_message}) # Check if the password match. ((JS)) if password != confirm_password: error_message = "Password does not match!" return render(request, 'user_auth/signup.html', {'error_message': error_message}) # Create new user. else: user = User.objects.create_user(username = username, email = email, password = password) user.set_password(password) user.save() return render(request, 'user_auth/signin.html') else: return render(request,'user_auth/signup.html') def signin(request): # Extract data from form. if … -
Trouble Getting Django to Access the Correct Static Directory
I'm having trouble getting Django/Wagtail to access the correct static directory. As a result, all static files are returning 404. This is in a local/dev environment. I currently have: PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "static"), ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" I'm using the following structure: my-project ├── apps │ └── app_1 │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── myproject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── settings.cpython-35.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media ├── static └── templates Django is trying to access: my-project\myproject\static which doesn't exist. When I try to move it to the correct directory, I get the following error: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. For example, I've tried: STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "..", "static"), ] To get it to move up a dirrectory, but that results in the error above. Also, I've run collectstatic. -
ModuleNotFoundError: No module named 'projectName' - wsgi Django reployment
I am trying to run my Django Project using Apache. When I launch Apache I receive an 'Internal Server Error', inspecting the logs I have found that it fails to execute the wsgi.py for my project and throws the errors below. mod_wsgi (pid=5128): Failed to exec Python script file 'C:/Env/localassets/localassets/wsgi.py'., referer: http://localhost/ mod_wsgi (pid=5128): Exception occurred processing WSGI script 'C:/Env/localassets/localassets/wsgi.py'., referer: http://localhost/ Traceback (most recent call last):\r, referer: http://localhost/ File "C:/Env/localassets/localassets/wsgi.py", line 16, in <module>\r, referer: http://localhost/ application = get_wsgi_application()\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r, referer: http://localhost/ django.setup(set_prefix=False)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\__init__.py", line 19, in setup\r, referer: http://localhost/ configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 102, in __getattr__\r, referer: http://localhost/ self._setup(name)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 89, in _setup\r, referer: http://localhost/ self._wrapped = Settings(settings_module)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 217, in __init__\r, referer: http://localhost/ mod = importlib.import_module(self.SETTINGS_MODULE)\r, referer: http://localhost/ File "C:\\Program Files\\Python310\\Lib\\importlib\\__init__.py", line 126, in import_module\r, referer: http://localhost/ return _bootstrap._gcd_import(name[level:], package, level)\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1050, in _gcd_import\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1027, in _find_and_load\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1050, in _gcd_import\r, … -
Can't get rid of modulenotfounderrror after moving project dirs around
when I run python manage.py runserver on myenv, I get the "modulenotfounderror" "no module named Quicpull" - which is my project Dir. I've tried multiple syntaxes in my installed apps, and I've updated the system env paths. -
Cannot create django superuser inside virtual environment
Firstly, if I missed finding a solution already posted, I apologize. I really did try figuring this out. So here is the command executed: "(VENV) user@server:/var/www/html/django-apps/GT1$ python manage.py createsuperuser The error returned is: Traceback (most recent call last): File "/var/www/html/django-apps/GT1/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/html/django-apps/GT1/manage.py", line 22, in <module> main() File "/var/www/html/django-apps/GT1/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? The virtual environment exists obviously because it's active when I'm trying. I've deleted the virtual and tried reinstalling. When I do that, I get a message that django is already installed. That message is: (VENV) darren@server:/var/www/html/django-apps$ sudo pip install django Requirement already satisfied: django in /usr/local/lib/python3.10/dist-packages (4.2.2) Requirement already satisfied: sqlparse>=0.3.1 in /usr/local/lib/python3.10/dist-packages (from django) (0.4.4) Requirement already satisfied: asgiref<4,>=3.6.0 in /usr/local/lib/python3.10/dist-packages (from django) (3.7.2) Requirement already satisfied: typing-extensions>=4 in /usr/local/lib/python3.10/dist-packages (from asgiref<4,>=3.6.0->django) (4.6.3) WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a … -
How can I optimize @property method by prefetching or caching an "unrelated" table
I have three model objects, two of which directly relate to each other. class Child(models.Model): date_of_birth = models.DateField() name = models.CharField(max_length=255) gender = models.CharField(max_length=10, choices=Gender.choices) @property def age(self): today = date.today() return age_on_date(date_calculating_on=today, date_of_birth=self.date_of_birth) class ChildBmiCheck(models.Model): home_bmi_check = models.ForeignKey(HomeBmiCheck, models.CASCADE, related_name="child_bmi_checks") child = models.ForeignKey(Child, models.PROTECT, related_name="bmi_checks") height_in_meters = models.DecimalField(max_digits=40, decimal_places=10, null=True) weight_in_kgs = models.DecimalField(max_digits=40, decimal_places=10, null=True) child_was_present = models.BooleanField(default=True) @property def zscore(self): if self.child_was_present is True: age = self.child.age * 12 # in months gender = self.child.gender # TODO this is slow because for every child bmi check we hit the DB # | # V matching_data = ReferenceZscoreData.objects.filter(sex=gender).get(age=age) return self.calculate_z_score(matching_data) else: return None And one that is used under the comment in the @property method above, which is not directly related through a foreign key relationship. class ReferenceZscoreData(models.Model): sex = models.CharField(max_length=1, choices=Sex.choices, db_index=True) age = models.IntegerField(db_index=True) property1ForZscore = models.FloatField() property2ForZscore = models.FloatField() property3ForZscore = models.FloatField() When I fetch Child BMI checks, I see that the DB is queried for the relavent ReferenceZscoreData every time this method is called. This makes the HTTP fetch in Django Rest Framework really slow. However, ReferenceZscoreData only changes once a year, so there is no reason to go to the database so often. I … -
Django Template: include another html template, but only once
How can I ensure that specific HTML files are not included multiple times in Django templates when passing metadata to different frontend frameworks? I am working on a project where we use Django templates and need to pass metadata from Django to various JavaScript frontend frameworks (currently React, but potentially refactor to others in the future). embed_data_foo.html {{ foo_data|json_script:"foo_data" }} some_page.html {% include "embed_data_foo.html" %} rendered <script id="foo_data" type="application/json">{"foo":"bar"}</script> Our templates are designed compositionally and relatively small, which makes it easy to avoid accidental duplication. However, I want to have guardrails in place to prevent these specific files from being included multiple times. So doing this multiple times potentially, in extended templates, should still only result in the only one being placed. some_page_but_with_whoopsies.html {% include "embed_data_foo.html" %} {% include "embed_data_foo.html" %} {% include "embed_data_foo.html" %} rendered <script id="foo_data" type="application/json">{"foo":"bar"}</script> <script id="foo_data" type="application/json">{"foo":"bar"}</script> <script id="foo_data" type="application/json">{"foo":"bar"}</script> In the C programming language, I would achieve this using the #ifndef, #define, #endif pattern. Is there a similar approach or technique that I can use in Django templates to ensure that files are included only if they have not been included before? Given that we will be onboarding many people in the near future, … -
How to apply custom validation on GenericTabularInline, TabularInline (related objects) in Django admin?
This is a question about GenericTabularInline, TabularInline, and admin.py. models.py class Chapters(models.Model): name = models.CharField(max_length=40, unique=True) class Projects(models.Model): name = models.CharField(max_length=40) class Courses(models.Model): name = models.CharField(max_length=30) is_active = models.BooleanField(default=False) chapters = SortedManyToManyField(Chapters, related_name="courses", blank=True, sort_value_field_name="chapter_number", base_class=CourseChapters) projects = models.ManyToManyField(Projects, related_name="courses", blank=True) # Here comes generic relations class QuestionsManager(models.Manager): def active(self): return self.get_queryset().filter(Q(fib__is_active=True) | Q(mcq__is_active=True) | Q(code__is_active=True)) class Questions(models.Model): chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={ "model__in": ["fib", "mcq", "code"]}, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() fib_mcq_code = GenericForeignKey("content_type", "object_id") objects = QuestionsManager() class CODE(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='code') is_active = models.BooleanField(default=False) class MCQ(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='mcq') is_active = models.BooleanField(default=False) class FIB(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='fib') is_active = models.BooleanField(default=False) admin.py class QuestionsChaptersInlineForm(forms.BaseInlineFormSet): def clean(self): pass class QuestionsChaptersInline(admin.TabularInline): model = Questions formset = QuestionsChaptersInlineForm extra = 0 readonly_fields = ['content_type', 'object_id', 'is_active', "modify"] def has_add_permission(self, request, obj): return False def has_delete_permission(self, request, obj): return False class ChapterAdminForm(forms.ModelForm): class Meta: model = Chapters fields = '__all__' def clean(self): cleaned_data = super().clean() if cleaned_data.get('is_active'): if not self.instance.questions_set.active().exists(): self.add_error('is_active', 'At least one question in this chapter must be active.') return cleaned_data class ChaptersAdmin(ImportExportModelAdmin, ImportExportActionModelAdmin, admin.ModelAdmin): form = ChapterAdminForm inlines = [QuestionsChaptersInline, CoursesChaptersInline] # =========================== class … -
Is there a way to filter multiple class objects in views.py and connect to eachother?
I have a Django project where I want to make 3 menus that can be accesed by clicking the select button in each main_menu(like mainfood) >> menu(pastas) >> items of pastas(bluh bluh) *main_menu is accesed from the homepage* I have created 3 classes in models.py called MainMenu, Menu, Item class MainMenu(models.Model): title = models.CharField(max_length=100) main_slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) def __str__(self): return self.title class Menu(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) main_menus = models.ForeignKey(MainMenu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT, null=True) def __str__(self): return f"{self.title}||{self.main_menus}" class Meta: ordering = ['-created'] class Item(models.Model): title = models.CharField(max_length=100) price = models.CharField(max_length=12) description = models.TextField(blank=True) created = models.DateTimeField("Date created", default=timezone.now) menus = models.ForeignKey(Menu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT) def __str__(self): return f"{self.title}||{self.menus}" class Meta: ordering = ['-created'] and I have filtered objects in views.py def menus(request,main_slug): matching_menus = Menu.objects.filter(main_menus__main_slug=main_slug).all() return render( request=request, template_name='Menu.html', context={"objects": matching_menus} ) def items(request,slug): matching_items = Item.objects.filter(menus__slug=slug).all() return render( request=request, template_name='Item.html', context={"objects": matching_items} ) and the urls.py : urlpatterns = [ ... path('<slug:main_slug>', views.menus), path('<str:slug>', views.items), ] it kinda WORKS but only menu is filtered correctly. I can go from MainMenu to Menu and the Menus are filtered correctly, but I CANNOT access the items in the Menus. when I click a menu … -
How to programmatically test Django Auth0 protected api's?
I want to do unit tests for my Django app. I'm using the Django-oauth-toolkit library to protect my views, but I can't test my APIs because they are protected by a Bearer Token. def test_get_meeting_list(self): response = self.client.get('/meetings/') # (I need to pass a token, # but I won't have the token) self.assertEqual(response.status_code, 200) # (AssertionError: 401 != 200) So, how could I test that? I tried to make a fake authentication like the official lib tests https://github.com/jazzband/django-oauth-toolkit/blob/master/tests/test_application_views.py but I realized that's will be very complex. -
Django: How to show an admin user message if correction was made during model save?
I have an app, and am wanting to do some automatic corrections to geometry (GeoDjango with PostGIS) rather than simply reject the save operation, since the corrections are being done after the data is committed to the database through the "MakeValid" database operation. I would like to inform the admin user that the model was corrected and to verify their changed geometry, and this is where I am running into trouble. I am attempting the "MakeValid" through an additional query in the model's "save" method after the initial save has completed, but it appears that I can only get the message to show if I move that logic into the admin logic overriding "save_model" to call "obj.save()" and then do my post-processing. Is there a better way to pass information back to the admin view from the model save? -
Django REST Framework Custom Registration Serializer Not Being Called
I'm currently working on a Django project where I'm using Django REST Framework and dj-rest-auth for user authentication. I have a custom user model that includes an additional field for Date of Birth (DOB). I've created a custom registration serializer to handle the additional field during registration. However, I'm running into an issue: my custom serializer is not being called during the registration process, leading to HTTP 400 errors from the frontend. Goal: I want to allow users to register by providing an email, password, and DOB. Problem: When I attempt to register a user from the frontend, I receive a HTTP 400 error. I'm also noticing that print statements in my custom registration serializer aren't showing up in the console logs, which leads me to believe it's not being called at all. What I've tried: I have tried to override the registration process in dj-rest-auth by providing a custom serializer, and configuring REST_AUTH_REGISTER_SERIALIZERS in my settings. I've also checked my URL routing and it seems to be correct. Here are the key sections of my code: models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): … -
Django tests: model name cannot be resolved, although site works
I have a website written in Django. Apart from main app, I have one called app and other users. In users I have implemented my CustomUser model, which I am also using inside models for app. When I run the website, it all works fine; however when I tried to create tests for the app I get: ValueError: Related model 'users.customuser' cannot be resolved (even though tests.py are empty now). And obviously, in app/tests.py I do from .models import CustomUser. I tried looking at the order of imports in settings.py but it seemed right to me: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'app', ] I have also done migrations for both apps. -
Django testing a simple model with Foreign Key and UpdateView
Two very simple models from django.db import models class Location(models.Model): name = models.CharField(max_length=255) location_number = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Project(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, to_field='location_number', db_column='location_number', related_name='projects', verbose_name='Standort') name = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __str__(self): return self.name with an UpdateView from .models import Project from django.views.generic import UpdateView class ProjectUpdateView(UpdateView): model = Project fields = "__all__" slug_url_kwarg = 'project_slug' slug_field = 'slug' should be tested with this simple test: from django.test import TestCase from django.urls import reverse from .models import Project, Location from urllib.parse import urlencode from django.utils.http import urlencode class ProjectUpdateTest(TestCase): def setUp(self): self.location = Location.objects.create( name='Test Location', ) self.project = Project.objects.create( location=self.location, slug="test", name='Test Project', ) def test_project_update_view(self): # Prepare the data for the form form_data = { 'name': 'Updated Project', 'location': self.location.pk, 'slug': 'test', } # Build the URL for the project detail view url = reverse('update_project', kwargs={ 'project_slug': self.project.slug }) # Encode the form data as form-encoded data encoded_form_data = urlencode(form_data, doseq=True) # Send a POST request to the project update view with the form-encoded data response = self.client.post(url, data=encoded_form_data, content_type='application/x-www-form-urlencoded') # Print form errors, if any form = response.context['form'] print(form.errors) self.project.refresh_from_db() self.assertEqual(self.project.name, 'Updated Project') But it fails with locationSelect a valid … -
how to upload file to server / django rest framework
Thanks to stack overflow, I implemented loading a file in views, but how to make sure that the file gets to the server and data appears in the database. If I upload a file through the admin panel, then everything works fine. I'm testing with postman. Thank you) # urls.py path('api/v1/UploadDataset/', UploadDataset.as_view()), # models.py class Datasets(models.Model): create_at = models.IntegerField(max_length=50) user = models.IntegerField(max_length=50) name_dataset = models.CharField(max_length=255) link_dataset = models.FileField (upload_to=datasets_filename) # serializers.py class UploadDatasetSerializer(serializers.ModelSerializer): class Meta: model = Datasets fields = '__all__' # views.py class UploadDataset(APIView): parser_classes = (MultiPartParser, FormParser ) #parser_classes = [FileUploadParser] def put(self, request, format=None): file_obj = request.FILES['file'] # do some stuff with uploaded file ??? return Response(status=204) -
drf_spectacular.utils.PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context'
I am using a PolymorphicProxySerializer provided by drf_spectacular but I am getting a strange error when attempting to load the schema usage @extend_schema( parameters=[NoteQueryParameters], responses=PolymorphicProxySerializer( component_name="NoteSerializer", serializers=[NoteSerializer, NoteSerializerWithJiraData], resource_type_field_name=None, ), ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) serializers class CleanedJiraDataSerializer(serializers.Serializer): key = serializers.CharField(max_length=20, allow_null=True) class BugSerializer(serializers.Serializer): failures = serializers.CharField(max_length=10, required=False, allow_null=True) suite = serializers.CharField(max_length=100, required=False, allow_null=True) notes = serializers.CharField(max_length=1000, required=False, allow_null=True) tags = StringListField(required=False, allow_null=True, allow_empty=True) testCaseNames = StringListField(required=False, allow_null=True, allow_empty=True) testCaseIds = StringListField(required=False, allow_null=True, allow_empty=True) jira = CleanedJiraDataSerializer(required=False, allow_null=True) class BugSerializerWithJiraData(BugSerializer): jira = serializers.DictField() class NoteSerializer(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializer()) class Meta: model = Notes fields = "__all__" class NoteSerializerWithJiraData(serializers.ModelSerializer): bug = serializers.ListField(child=BugSerializerWithJiraData()) class Meta: model = Notes fields = "__all__" Basically, if a boolean query parameter is added to the request, I will inject some dynamic data fetched from the jira api. I am trying to update the api docs to represent to two distinct possible schema PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context' -
How do I run a python APscheduler independant of subsequent deployments
I have a django application with a python AP scheduler running a specific job. I wish to run the job once every week. There might be subsequent deployments to the application and I do not want the scheduler to reset the jobs every time that happens. Is there any way to provide a past start date or check if a week has elapsed since the last run to ensure that the scheduler jobs run independant of deployments. The scheduler code - from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_job(send_weekly_email, 'interval', weeks=1) scheduler.start() -
Translate jquery ajax code snippet into HTMX or manage to fetch selector value
I built a 3 interdependent select lists using htmx, (country region town) and I managed to fetch the selected town as I have this on the last part <select id="localidades" class="form-control-sm custom-select " name="town" hx-get="{% url 'query_for_properties' %}" hx-trigger="change" hx-target="#response" required> <option value="">Select municipality</option> {% for z in lista_localidades %} <option value="{{z}}">{{z}}</option> {% endfor %} </select>` Here I fetch it alright (notice that I am calling this function from the above snippet) def query_for_properties(request): town = request.GET.get('town') etc as I need that town value for the next code. However, this next code needs to send the values to different targets and for each target a different value, like, number of cars, number of bikes etc to different selectors.And that is where I get stuck.The htmx docs, as usual everywhere, are only for the very simple scenarios, but if you need something else, you are a goner, stranded. I have no idea how to deal out different values to different targets. So, I tried ajax, and with jquery it was easy to build calls for every selector. However, because I built the interdependent select lists with htmx,ajax query doesn't get the value. Here it goes <script> $(document).ready(function(){ $("#localidades").on({ change: function(){ var … -
DJANGO - Error creating Solr container (java.nio.file.AccessDeniedException)
I'm trying to implement Solr in my Django project, but when I run the Solr container I get an AccessDenied error. Below are the container and haystack settings local.yml solr: image: solr:7.7.1 restart: always ports: - "8983:8983" volumes: - ./index/core:/opt/solr/server/solr/core environment: - SOLR_JAVA_MEM=-Xms512m -Xmx512m - SOLR_HEAP=512m settings.py HAYSTACK_CONNECTIONS = { "default": { "ENGINE": "haystack.backends.solr_backend.SolrEngine", "URL": env("SOLR_URL", default="http://0.0.0.0:8983/solr/core"), "SILENTLY_FAIL": False, "SOLR_TIMEOUT": 10 } } HAYSTACK_SIGNAL_PROCESSOR = "haystack.signals.RealtimeSignalProcessor" error: SolrCore Initialization Failures core: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: java.nio.file.AccessDeniedException: /opt/solr/server/solr/core/data -
Django project not displaying some components
so I am building a Django web application, and it has a preview section and this preview section is supposed to display a main-experience and additional-experience however when the form is filled, the main-experience is not being displayed, only the additional-experience displays, its as if the main-experience is being filtered out when the additional-experience is being displayed. What should I change in the code, such that both main and additional experiences are displayed in the preview? The associated codes are below. this is the code i have. both the views and the associated html: views.py: @login_required def experience_v(request): if request.method == 'POST': form = ExperienceForm(request.POST) if form.is_valid(): main_experience = form.save(commit=False) main_experience.user = request.user main_experience.is_main_experience = True main_experience.save() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) for entry in additional_experiences: exp = experience.objects.create( user=request.user, position=entry.position, company=entry.company, startdate=entry.startdate, enddate=entry.enddate, roles=entry.roles ) return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) @login_required def preview(request): personal_info = personalinfo.objects.filter(user=request.user).last() main_experience = experience.objects.filter(user=request.user, is_main_experience=True).first() additional_experiences = experience.objects.filter(user=request.user).exclude(pk=main_experience.pk) if main_experience else [] educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) return render(request, 'preview.html', { 'personal_info': personal_info, 'main_experience': main_experience, 'additional_experiences': additional_experiences, 'educations': educations, 'certs': certs }) html: <div class="preview-data"> <h2>Experience</h2> <div class="experience-item"> <p><span class="bred">Position</span>: {{ main_experience.position }}</p> <p><span class="bred">Company</span>: {{ main_experience.company }}</p> <p><span … -
I want to create testcase for my project but i got this error
this is the testcase i wrote i have user model that records create only with email confirmation so i have to get email code from EmailConfirm model and i can't pass it to test class as self.email_code. same problem for self.refresh_token and self.user_id class AccountTestCase(APITestCase): def setUp(self): self.email_code = None self.refresh_token = None self.user_id = None return super().setUp() def test_send_email_code(self): url = reverse("accounts:resend_code") data = { 'email': 'testuser@example.com' } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.email_code = EmailConfirm.objects.get(email='testuser@example.com').code def test_register(self): url = reverse("accounts:register") data = { 'username': 'testuser', 'email': 'testuser@example.com', 'password': 'testpassword', 'confirm_password': 'testpassword', 'code': self.email_code } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.user_id = response.data['id'] def test_login(self): url = reverse("accounts:login") data = { 'username': 'testuser', 'password': 'testpassword', } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_token = response.data['refresh'] def test_token_refresh(self): url = reverse("accounts:token_refresh") data = { 'refresh': self.refresh_token } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.access_token = response.data['access'] The errors: ERROR: test_register (accounts.tests.AccountTestCase) Traceback (most recent call last): File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\accounts\tests.py", line 40, in test_register response = self.client.post(url, data) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 296, in post response = super().post( File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line 209, in post data, content_type = self._encode_data(data, format, content_type) File "C:\Users\Mahdyar Eatemad\OneDrive\Projects\Django\ReelRave API\reelrave\venv\lib\site-packages\rest_framework\test.py", line …