Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying a Django application to Heroku - No module named 'django_project.wsgi
I'm trying to deploy a django application but I keep getting this error: ModuleNotFoundError: No module named 'django_project.wsgi' In fact, here's the full log: 2022-05-13T14:52:06.436735+00:00 app[web.1]: Traceback (most recent call last): 2022-05-13T14:52:06.436735+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-05-13T14:52:06.436736+00:00 app[web.1]: worker.init_process() 2022-05-13T14:52:06.436736+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-05-13T14:52:06.436736+00:00 app[web.1]: self.load_wsgi() 2022-05-13T14:52:06.436737+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-05-13T14:52:06.436737+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-05-13T14:52:06.436738+00:00 app[web.1]: self.callable = self.load() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-05-13T14:52:06.436740+00:00 app[web.1]: return self.load_wsgiapp() 2022-05-13T14:52:06.436740+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-05-13T14:52:06.436740+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-05-13T14:52:06.436741+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-05-13T14:52:06.436742+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-05-13T14:52:06.436742+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_project.wsgi' 2022-05-13T14:52:06.436801+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-05-13T14:52:06.442147+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-05-13T14:52:06.541420+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [INFO] Shutting … -
TypeError: 'cached_property' object is not callable - DJANGO
i want change location upload to mp3. but when i clicked upload, it goes to txt folder. so i give location to mp3, but suddenly got error. is it my code is wrong? please check it : def homepage(request): if request.method == 'POST' and request.FILES['upload']: upload = request.FILES['upload'] fss = FileSystemStorage.location(location='/media/mp3/') file = fss.save(upload.name, upload) file_url = fss.url(file) return render(request, 'homepage.html', {'file_url': file_url}) return render(request, 'homepage.html') i also add settings.py : MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and here's my folder: -
Instruct WebApp using Django to run the code locally and return results
I am a newbie to web development and python scripts. I am learning to host python scripts using Django. I would like to know how to instruct Django to run the script locally instead of running it on the server. For e.g. User visits the web app > enters parameters and submits the form > script should run locally from the client machine and return results back on the web app. The purpose of my python script is to test the network port status locally on the user machine's private network and return the results. Appreciate your advise. -
Creating a Django Model for a recipe #3
Another follow up question to Creating a Django Model for a recipe #2. I've run into an error with the following code: class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' name = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient class IngredientDetail(models.Model): '''A class to identify variable quantities of ingredients''' ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) class Meta: verbose_name_plural = 'Ingredient Details' def __str__(self): return self.quantity class Recipe(models.Model): '''A Recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail) instructions = models.TextField(null=True) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to= 'media/', null=True, blank=True) def __str__(self): return self.recipe I've set it up this way to associate variable quantities of ingredients with multiple recipes. However, when I run this code, the following issue is identified by Django: grocery_lists.IngredientDetail: (fields.E336) The model is used as an intermediate model by 'grocery_lists.Recipe.ingredients', but it does not have a foreign key to 'Recipe' or 'Ingredient'. As you can see, there IS a foreign key to 'Ingredient', so I'm not sure whats wrong. -
.sock file dissapearing [Django + Nginx + Gunicorn]
When trying to setup my django project on an AWS EC2 (ubuntu), it appears that whatever I do my .sock file is being deleted almost instantly by itself. My structure: home/ubuntu/sites/myapplication/manage.py [Unit] Description=gunicorn daemon After=nextwork.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/sites/myapplication ExecStart=/home/ubuntu/.local/share/virtualenvs/myapplication-yDrKR6kT/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/sites/myapplication/myapplication.sock application.wsgi:application [Install] WantedBy=multi-user.target Below are the commands I've used in no particular order (Nginx can't find the .sock file so it must be gunicorn) sudo systemctl deamon-reload sudo systemctl restart gunicorn sudo systemctl start gunicorn sudo systemctl enable gunicorn After running sudo systemctl start gunicorn I can see the .sock file appear in my application directory, however 10 seconds later it dissapears. It also instantly dissapears if I run the enable command. Most suggestions I find tell me to restart gunicorn, which doesnt work in my case. (Neither does rebooting the server FYI) It could be a permission issue but then I don't understand why the .sock file appears shortly and then is removed seemingly automatically by the system. -
Configuring PostgreSQL schema for default Django DB working with PgBouncer connection pool
I need to set the default DB schema for a Django project, so that all tables of all apps (including 3rd party apps) store their tables in the configured PostgreSQL schema. One solution is to use a DB connection option, like this: # in Django settings module add "OPTIONS" to default DB, specifying "search_path" for the connection DB_DEFAULT_SCHEMA = os.environ.get('DB_DEFAULT_SCHEMA', 'public') # use postgresql default "public" if not overwritten DATABASES['default']['OPTIONS'] = {'options': f'-c search_path={DB_DEFAULT_SCHEMA}'} This works for a direct connection to PostgreSQL, but not when connecting to PgBouncer (to use connection pools), failing with OperatonalError: unsupported startup parameter: options". It appears PgBouncer doesn't recognize options as a startup parameter (at this point of time). Another solution to set the schema without using startup parameters, is to prefix all tables with the schema . To make sure this works for built-in and 3rd party apps too (not just my own app), a solution is to inject the schema name to db_table attribute of all models when they're being loaded by Django, using class_prepared signal, and an AppConfig. This approach is close to what projects like django-db-prefix use, only need to make sure the schema name is well quoted: from django.conf import … -
Django: how to count the ratings and reviews of a post using django?
i have a model course and i also have a model review and rating that allows users rate a particular course. now i want to count all the ratings on each course when i filter. NOTE: in the courses detail view i figured out a way to count the ratings like this rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count(). This only worked in the detail view because i get the course first using course = Course.objects.get(slug=course_slug). Now i want to count the rating in course lists view, how can i do this while using filter? this is how the detail view looks like @login_required def course_details(request, course_slug): user = request.user course = Course.objects.get(slug=course_slug) reviews_count = CourseRating.objects.filter(active=True, course=course).count() rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count() this is how the list view look like NOTE: this is where i want to count all the rating of each course def index(request): courses = Course.objects.filter(course_publish_status="published").order_by('?') -
Detect when user register/Login on Context Proccessor Django
I have to do some checks all the time with the context proccessor.The value must be 'True' as soon as the user logs in.But when navigating the site after logging in, the value should be 'False'. So it should be a one-time True result.I need to do this both for the login process and when registering.And I have to implement them with Context Proccessor in Django. How can I do that? def user_info(request): ctx = dict() user = request.user ... ctx["isRegistered"] = False ctx["isLoggedIn"] = False # if user register website, that moment 'request' : # ctx["isRegistered"] = True return ctx -
understanding try except python/django
I need your help with understanding try-except python/Django. so I have this function: def submit_dept_head_application(request, application_id): cv = request.FILES['cv'] letter = request.FILES['letter'] candidate_id = request.data['candidateId'] rank_id = request.data['requestedRankId'] application_state = { 'candidate_id': candidate_id, 'rank_id': rank_id, 'cv_filename': cv.name, 'letter_filename': letter.name, } creator = Profile.objects.get(user=request.user.id) department = creator.department applicant = Profile.objects.get(user=candidate_id) applicant_profile_id = applicant.id rank = Rank.objects.get(id=rank_id) try: application = Application.objects.get(id=application_id) # TODO - update application except Application.DoesNotExist: application = None if application is None: application = Application(creator=creator, applicant=applicant, desired_rank=rank, application_state=application_state, department=department ) application.save() create_application_directory(application.id) ApplicationStep.objects.update_or_create( application=application, step_name=Step.STEP_1, defaults={'can_update': True, 'can_cancel': True, 'currentStep': True} ) copy_to_application_directory(cv, application.id) copy_to_application_directory(letter, application.id) send_email(settings.SENDGRID_SENDER, ['xxxxxx@gmail.com'], 'new application submitted', 'new application submitted') return Response(application.id, status=status.HTTP_200_OK) right now what is happening is that if there is no open application I create a new one. what I'm trying to do is to add another check, which is Application.objects.filter(applicant=applicant_profile_id) so if I have an opened application for this candidate it won't get to the application.save() but it will send an error. i don't really know how to do so and that's where i need your help please :) -
DRF --405 Method not allowed for update operation
I have done this before and may be it did work properly that time but now suddenly it's not working as it's expected to be. The viewset.py: class ProfileViewSet(ModelViewSet): serializer_class = ProfileSerializer http_method_names = ["post", "get", "put", "delete"] queryset = Profile.objects.all() def get(self, request, format=None): users = Profile.objects.all() serializer = ProfileSerializer(users, many=True) return Response(serializer.data) def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = ProfileSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(_("Name of User"), blank=True, null=True, max_length=255) phone_number = PhoneNumberField() zip_code = models.CharField(_("Zip Code"), blank=True, null=True, max_length=255) def __str__(self): return self.user.username seralizers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' urls.py router.register("profile/<int:pk>", ProfileViewSet, basename="profile_each") whenever I hit in postman It says "405 Method not allowed". Am I missing anything here please? -
Django. How to get URL by its name?
I want to get url by name specified in urls.py. Like {% url 'some_name' %} in template, but in Python. My urls.py: urlpatterns = [ ... path('admin_section/transactions/', AdminTransactionsView.as_view(), name='admin_transactions'), ... ] I want to something like: Input: url('admin_transactions') Output: '/admin_section/transactions/' I know about django.urls.reverse function, but its argument must be View, not url name -
Speech recognition suddenly detects "at" instead of "@"
usually when I say "at" for mail name speech recognition detects "@", but today when ı try the program it shows "at" instead of "@" . How can I solve this problem? -
DJANGO custom import CSV
I have a model with multiple fields. I want to make an importer (possibly with the django import-export library) that only takes two fields and with that calculates the rest of the fields that the model has. I wanted to listen and ask if you know of ways to do this. Since the documentation does not mention much. Thank you all! -
Django project located out of Apache ServerRoot
Got some problems trying to include Django-app in my already configured httpd2 apache server. I'd successfully installed mod_wsgi and set some configuration using the deployment manual: https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/modwsgi/ I added the following settings in httpd.conf WSGIScriptAlias /djangosrv/ /app/djangosrv/djangosrv/wsgi.py WSGIPythonPath /app/djangosrv <Directory /app/djangosrv/djangosrv> <Files wsgi.py> Require all granted </Files> </Directory> The project has the following structure and runs the only app named 'searchpage' /app/djangosrv -- djangosrv -- searchpage The URLs defined in /app/djangosrv/djangosrv/urls.py : urlpatterns = [ path('searchpage/', include('searchpage.urls')), path('admin/', admin.site.urls) ] When I try to open http://localhost/djangosrv/ I get 404: Page not found (404) Request Method: GET Request URL: http://localhost/djangosrv/ Using the URLconf defined in djangosrv.urls, Django tried these URL patterns, in this order: searchpage/ admin/ The empty path didn't match any of these. And when I try to access http://localhost/djangosrv/searchpage/ I get: Forbidden You don't have permission to access this resource. How can I configure routing in Django-project to make it work with non-server-root URLs ? Should I use some extra directory settings in httpd.conf and configure mod_rewrite ? CentOS 8 Apache/2.4.37 python3-mod_wsgi-4.6.4-4.el8.x86_64 python3-django3-3.1.7-1.el8 Any help would be greatly appreciated! -
Django: (fields.E300) Field defines a relation with 'Class' model , which is either not installed, or is abstract
Class model is a foreign key in File model I have no idea what causes the error above,I searched it and it mostly occurs when working with models in different apps, but that is not case in this situation, since both models are in the same models.py file. models.py from asyncio.windows_events import NULL from http.cookiejar import FileCookieJar from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, BaseUserManager class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class File (models.Model): file=models.FileField(); name=models.CharField(max_length=255); class_name=models.ForeignKey(Class,on_delete=models.CASCADE) def __str__(self): return self.name; class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class CustomUserManager(BaseUserManager,): def create_superuser(self,email,name,surname,password,**other_fields): other_fields.setdefault('is_staff',True) other_fields.setdefault('is_superuser',True) other_fields.setdefault('is_active',True) if other_fields.get('is_staff') is not True: raise ValueError('super user must be assigned to is_staff= True') if other_fields.get('is_superuser') is not True: raise ValueError('Super user must be assigned to is_super_user=True') return self.create_user(email,name,surname, password,**other_fields) def create_user(self,email,name,surname,password,**other_fields): if not email: raise ValueError(('You must provide an email address')) email=self.normalize_email(email); #for example ignore the case sensitivity user=self.model(email=email,name=name,surname=surname,**other_fields) user.set_password(password) user.save() return user; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name class Request(models.Model): requested_class=models.ForeignKey(Class,on_delete=models.CASCADE) requesting_student=models.ForeignKey(NewUser,on_delete=models.CASCADE) def __str__(self): return self.requesting_student.name # Create your models here. -
Django Authentification with class based views login() method
as I am trying to build a login/registration form, I came into a problem. I am building my form with class based views, and I want to use the login() method for the auth. The problem is that it won't work, even if I have followed the same example as the docs had. Here is my code: views.py: def login(request): if request.method == 'POST': form = MyLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/home") else: messages.error(request, 'There Was An Error Logging In, Try Again...') else: form = MyLoginForm() return render(request, 'users/firstAction/login.html', {'form': form}) My template: <body> <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Login </span> {% if messages %} <ul class="red"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% if form %} <form method="POST" novalidate class="login100-form validate-form"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="red"> <p>{{error}}</p> </div> {% endfor %} {% endif %} {% for field in form %} <div class="wrap-input100 … -
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify'
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify' Request Method: GET Request URL: http://localhost:8000/account/oidc/callback/?code=0.AQwA2kdaUAbvNU-5Y653jiyu-YHq0RPhP-9Cu3wqKQekVioMAJA.AQABAAIAAAD--DLA3VO7QrddgJg7Wevr6SStf98KkAv7heodBmkUKzmyvPGA7xsbND57p5XO-w3Cdn_KSw8Pbvcz5A1oB_i7zyj2emCgFtsFIlY-wI2MmRKmDBv0ZTJ07SUw_qJigWlRQeA5eXcCiE_f9WjU7qolelJFjA2GxgUXxH_7Fv7GMns1mXDPSicVwt_wBVzTDX-ONGIGqoR8tmsLMKOGBZtDKM9wy46LbXH3TOTR8ZwlyNZZDInpOuIWc2-RYyR73_fhjc57o07bVEJb7GT7sgzQ6Usp9a7pGAdLd3zaXZdPa-y3Dt71dlmLTqNkLi_COaTikBdzYRQEDRMMIjIKaLcSJXbCNRXd2pcPqDadXyS3_iZnhdfdFEK0-52vz-8pJUzZVGghTTiyTWojNd851369lriYC6SKn4qA7tcfLjqoHSJ71CkPVTD_dv1S_YZCPjzEBjuQ9FaKqJ6_EjhsQbwp1mrr6iJQg5fb-oGPEV21twaNvhppiApzhi_d7wKU-qRDv9xARGCuQ8R_w2smNNOrBamaSqQKph0pBVbq-N-04nT9ghp-83vhRCCrmPiCLRJfGb3xq-Pp2jwe4qBnoNhb2XNjZbtypPtel-EVY4XcqSAA&state=1TepMIKbpC2BHhWd0PpJJcBifzHqPrF6&session_state=bbe01820-0187-4e1e-9982-9431dc7bd273 Django Version: 1.9.7 Exception Type: AttributeError Exception Value: '_RSAPrivateKey' object has no attribute 'verify' Exception Location: C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\josepy\util.py in getattr, line 81 Python Executable: C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.5 -
How allow to fit read_only field for new record in TabularInline class in Django
I want to have a field readonly when record already saved but if admin adds a new record field must to be editable. Red arrows - read only; Blue arrow - edited. How I can achieve it? -
How to force a page-break on weasyprint?
I wonder if its possible to create a force break that splits the table rows? I think weasyprint does this in a sense but I want to break the rows in to specific counts (e.g 6 rows per page). Is that possible? I tried something like this: <table> <tr> <th>Header1</th> <th>Header2</th> </tr> {% for d in data %} {% if forloop.counter == 6 %} <p style="page-break-before: always;"></p> {% endif %} <tr> <td>{{ d.name }}</td> <td>{{ d.age }}</td> </tr> {% endfor %} </table> but it just break each row in different pages. Any help would be appreciated. -
Can I somehow combine columns into array of objects (list of dicts) by Django ORM?
I use PostgreSQL as a DB. And I have the following situation: Say, we have the following data (we got it joining two tables - orgs and markers). What I want to get by SELECT is Using raw SQL I would do something like this SELECT orgs.org_id, json_agg( json_build_object( 'id', markers.marker_id, 'name', markers.name ) ) as markers_data FROM orgs INNER JOIN markers ON orgs.org_id = markers.org_id GROUP BY orgs.org_id; But I want to combine those columns this way using Django ORM. Is it possible to do on SQL level not Python? So I don't have to just extract data from the DB and modify it to a desired format on Python level. -
How do I remove unused CSS when using Django, Sass and a frontend framework?
I am using a SCSS-based frontend framework (namely cirrus-ui) with my Django project. For compiling the CSS stylesheet with Sass, I use webpack to compile the static files (Presently only CSS stylesheets but I'm sure some JavaScript will probably work its way in there eventually). In the Python project, I use django-webpack-loader. My compiled, minified CSS stylesheet is a whopping 265 KiB. This is not ideal. I know about PurgeCSS and uncss. While I have not used them before, I think I understand how to call these from the webpack.config.js. What I don't know is how to utilize these or something similar with Django and its templates. Notes: I use Yarn to manage packages. main.scss (example excerpt). @use "cirrus-ui/src/cirrus-all" as *; I actually do provide a custom configuration map, but I don't see how that's relevant to the question. Relevant Django Configuration Details (settings.py) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'STATS_FILE': BASE_DIR / 'frontend/webpack-stats.json', 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.*\.hot-update.js', r'.*\.map'], } } STATICFILES_DIRS = [ './frontend/static', ] Project layout PROJECT ROOT/ - djangoproject/ - settings.py - templates (TEMP)/ - manage.py - frontend/ - .yarn/ - static/ - (Compiled Static Files Here) - assets/scss/main.css - webpack.config.js - webpack-stats.json - package.json … -
how to link a div using <a href> to appear in the middle of the screen instead of top?
this is to go back to home page that has a listview of posts and to keep the screen at where the post is located after clicking go back button in the post details page. <a href="/users/home#post{{ post.id }}"><button class="button" style="float: right; margin-right: 5px;">Go back</button><br></a> However, since there is a sticky nav bar at the top, it covers the post after clicking go back button. I want to make the post appear in the middle of the screen instead of at the top. -
DRF ModelSerializer meta extra_kwargs not working for related fields
I am designing API in DRF and have stumbled upon one issue that hopefully you can help me to solve. Let's assume I have the following model and a serializer: class SomeModel(models.Model): property = models.ForeignKey( Property, on_delete=models.PROTECT, ) name = models.CharField() address = models.OneToOneField(null=True, blank=True) ...more class SomeModelSerializer(serializer.ModelSerializer): class Meta: model = SomeModel fields = "__all__"" extra_kwargs = { "name": {"required": True}, "address": {"required": True}, "property": {"required": True}, } As you can see I am trying to add field kwargs by using extra_kwargs. The issue is that it won't work for a related field e.g. property or address field. I know I can just override it by defining a field manually and passing required=True, and that works but it's too long for my use case. Do you have any idea why this happen? Thanks. -
A problem with django using DefaultRouterWithNest
router2 = DefaultRouterWithNest() ( router2.register(r'eva',eval.Evadetail, basename='eva') .register(r'evand',eval.Evand,basename='eva-evand',parents_query_lookups=['eva_id']) .register(r'evard',eval.Evard,basename='eva-evard',parents_query_lookups=['eva_id','eva_nd_id']) ) problems: NameError: name 'DefaultRouterWithNest' is not defined what packeages should I import? -
Replacement in python package in Docker
GraphQL is still not supported in Django 4, so to use it I need to change the line: "from django.utils.encoding import force_text" to "from django.utils.encoding import force_str as force_text" in package "VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py" The problem occurs when using Docker, how could I replace this line when building the container?