Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception while running docker-compose up with Django Rest Framework
To setup secure websocket in Django Rest Framework, I added Daphne to docker-compose.yml as follows daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always When I bring the docker-compose up, I'm seeing the following error. If I remove the daphne entry from docker-compose.yml, this error does not happen. I was able to successfully build the compose earlier. daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen daphne_1 | httplib_response = self._make_request( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 398, in _make_request daphne_1 | conn.request(method, url, **httplib_request_kw) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1256, in request daphne_1 | self._send_request(method, url, body, headers, encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1302, in _send_request daphne_1 | self.endheaders(body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1251, in endheaders daphne_1 | self._send_output(message_body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1011, in _send_output daphne_1 | self.send(msg) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 951, in send daphne_1 | self.connect() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/transport/unixconn.py", line 30, in connect daphne_1 | sock.connect(self.unix_socket) daphne_1 | FileNotFoundError: [Errno 2] No such file or directory daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback … -
I'm facing this error "ImportError: cannot import name 'smart_text' from 'django.utils.encoding'"
I'm trying to implement Tags on my project using the django-tagging package. Below is the full error.\ File "C:\Users<user>\Desktop<App>\models.py", line 9, in from tagging.fields import TagField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\fields.py", line 9, in from tagging.forms import TagField as TagFormField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\forms.py", line 8, in from tagging.models import Tag File "C:\Users\Nicholas Karimi\Desktop\NicholasKarimi\WebLog\env\lib\site-packages\tagging\models.py", line 8, in from django.utils.encoding import smart_text ImportError: cannot import name 'smart_text' from 'django.utils.encoding' ("C:\Users<User>\Desktop<User><App>\env\lib\site-packages\django\utils\encoding.py) models.py\ class ModelName(models.Model): ..... tags = TagField() Working with django.VERSION (4, 2, 0, 'final', 0) -
how to add functionality of choose_all and remove_all functionality for a model in django-admin
I need to add the Choose all and Remove all functionality to one of the django model in the admin view. but not finding any documentation. I am creating Food table: <group1-> name:vegetarian food ---- vegetables nuts greens chicken egg <group2-> name: non-veg food ---- vegetables nuts greens chicken egg like above i need to choose the food-items and create a group. i want to display like groups option with choose_all/remove_all options. -
RelatedObjectDoesNotExist at /api/v1/user/
I am using drf-social-oauth2 for social authentication in django. When I make a request to backend using following json "grant_type": "convert_token", "client_id": "QhT0Z....u3m5f", "client_secret":"W2DMVGg.....CfhO", "backend":"google-oauth2", "token": "ya29.a0Ael9sCNIcDes5Zb85GJCGWj9ok5kmCH8oBAWWJP9gGRu1Mzrqgtkw6Ut4WE- aOaj0S5Fpf4IrZYjp8bYST93u6yb-MWIHzp3zmtUffbzKnA5VoKlvQ7aC5cSbCauBe4ckTn18XH0_3tWYn5QNg3D2bJqw6H1EAaCgYKARISARISFQF4udJhR0eV5UmE8pvApsrTCMq-8w0165" then following response is returned access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjVaU2tncnpJUlNIczlrd3liNUhrQXoyOFNwVVZnZCJ9.FRk7hYDP0ndlBpH3L2jkdNpO3kopRcLqCFfx-6C5GKA" expires_in: 27791.630586 refresh_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjdibURRUk54ckdLbVJiczR5UGd0ZTJidVNPMklQRyJ9.r5wH-RqhzN2DaG5uUF4Z7F-8ufPgBTUPn7fWLVFwt3k" scope: "read write" token_type: "Bearer" By default if this response is returned the user profile and email should automatically gets saved in the db but the drf-social-oauth2 is only returning the access tokens and is not saving user data. So when I make request to fetch user, following error occurs RelatedObjectDoesNotExist at /api/v1/user/ UserProfile has no student. Following is my written code settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', 'users', ... ] AUTH_USER_MODEL = 'users.UserProfile' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', } AUTHENTICATION_BACKENDS = ( # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Instagram OAuth2 'social_core.backends.instagram.InstagramOAuth2', # drf_social_oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv("G_APP_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv("G_APP_SECRET") # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] urls.py from django.contrib import admin from django.urls … -
Converting string to Django model name before calling filter() (Not duplicate)
model_name = "MyModel" model_name.objects.filter() AttributeError: 'str' object has no attribute 'objects' How can I make this work, I have already tried: exec(model_name) input(model_name) [model_name] I know there is a possible method where you import the model using apps.get_model(model_name="string") but I don't want to use this method due to the model already being imported beforehand. Is there any different way where I can convert model_name (string type) to a type that can be inserted at INSERTHERE.objects.filter() -
How to redirect two different Django applications on the same server with same url but different paths?
I have two Django applications running on the same server in Docker containers. App1 is on website.com/ using localhost:9595 and App2 other is on website.com/app2. localhost:9696 Problem begins when I go to website.com/app2/something where it redirects me to website.com/something which doesn't exist instead of going to website.com/app2/something. I can fix it in NGINX by adding: /something/{ proxy_pass localhost:9696/something/ } But then I have to do it for every subpage of my application2. -
How to document a tuple with different data types using drf-spectacular?
I'm using drf-spectacular to generate a Swagger documentation. I have a viewset that returns a dict (it doesn't go through a drf serializer as it's all native objects). The dict looks like this: data = { "lines": List[str], "points": List[Tuple[float, float, int, str]] "next_failure_date": str, "estimate_nth_failure": str "status": str, } I can't find a way for drf-spectacular to properly document the "points" key, it only gives me a "points": ["string"] What I tried : class SwaggerGrowthChartPoint: """Class used to generate the Swagger documentation""" def __init__(self, x: float, y: float, sap_id: int, created_on: str): self.x = x self.y = y self.sap_id = sap_id self.created_on = created_on class SwaggerGrowthChartPointField(serializers.Field): def to_representation(self, value: SwaggerGrowthChartPoint): return f"{value.x}, {value.y}, {value.sap_id}, {value.created_on}" def to_internal_value(self, data): return SwaggerGrowthChartPoint(*data) class SwaggerGrowthChartSerializer(serializers.Serializer): """Serializer used to generate the Swagger documentation""" lines = SwaggerGrowthChartLinesSerializer(many=True) points = serializers.ListField(child=SwaggerGrowthChartPointField()) next_failure_date = serializers.ListField(child=serializers.DateField()) estimate_nth_failure = serializers.DateField() status = serializers.CharField() But no luck. -
how to get socket id from this library
I'm using this library in my python code: ''' import socket socket.socket(socket.AF_INET,socket.SOCK_STREAM) python get socket id ''' how to get socket id (sid) and how to send message to selected client by socket id -
I can't call the function value in the model
my models.py : from django.db import models from django.urls import reverse from django.utils import timezone from django.db.models import Sum # Create your models here. class Plac(models.Model): c_name = models.CharField(max_length = 50) starting_date = models.DateTimeField(auto_now=True) posting_num = models.SmallIntegerField(default = None) payment_date = models.DateTimeField(auto_now=None) billingAm = models.SmallIntegerField(default = None) billing = models.BooleanField(default=False) def get_absolute_url(self): return reverse('place:place_detail', args=[self.pk]) def get_totalbilling(self): return Plac.objects.aggregate(Sum('billingAm'))['billingAm__sum'] or 0 class Rank(models.Model): name = models.ForeignKey(Plac,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True,) updated_at = models.DateTimeField(auto_now=True) ranking = models.SmallIntegerField(default = None) my html : <br /> <div>TotalPrice: {{plac.place.get_totalbilling}}</div> {% endblock content %} I want to see the result of "get_totalbilling" I try it for 3days.. but I can't coz I am beginner of django. -
unable get static image on webpage even after creating static folder and updating its path in settings.py and running collectstatic
I am using vscode.I created a django project named myproject, app named myapp and static folder in myproject dir. My image is not getting displayed in webpage after trying everything.I am not getting where is the issue please help. my static folder location C:\Users\nihar\myproject\static settings dir -STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') html file code {% load static %} <!DOCTYPE html> <body> <img src="{% static 'images/tttbg.jpg' %}"> </body> -
I want create a inventory management system in django(CRUD OPERATION)
Want to perform a crud operation in html view in django with this given model:- class Brand_Master(models.Model)`: brand_id = models.CharField(max_length=10,unique=True,verbose_name='Brand ID') brand_name = models.CharField(max_length=30,verbose_name='Brand Name') def __str__(self): return self.brand_name class Item_Master(models.Model): brand = models.ForeignKey(Brand_Master,on_delete=models.CASCADE,verbose_name='Brand ID') item_name = models.CharField(max_length=50,verbose_name='Item Name') item_code = models.CharField(max_length=20,unique=True,verbose_name='Item Code') price = models.FloatField(verbose_name='Price') def __str__(self): return self.item_code + "-" +self.item_name class Sale_Master(models.Model): item = models.ForeignKey(Item_Master,on_delete=models.CASCADE,verbose_name='Item') customer_name = models.CharField(max_length=100,verbose_name='Customer Name') number = models.PositiveBigIntegerField(verbose_name='Number') invoice = models.PositiveIntegerField(verbose_name='Invoice') I have created backend and want frontend view crud operation ` -
how to get a link to a file with https in json in drf
I have app with api on drf I installed the ssl certificate on the site and when I try to get the file I get an error: The page at site https://www.example.com was loaded over Https, but requested an insecure resource http://api.example.com/…… I think the problem is that with a get request in json, my link starts with http... How can i solve this problem and get file link starting with https ?? or is it something else? Json from get request: { "id": 50, "name": "Образец заполнения книги учета доходов", "category": "Бухгалтерия и налоги", "count_download": 0, "type_doc": "xls", "screenshot": "http://api.example.com/media/screenshot/%.png", "add_time": "2023-03-27", "pdffile": "http://api.example.com/media/pdf_docs/%.pdf" } I think perhaps it is necessary to somehow make a proxy server, but I don’t understand how… -
Djongo/MongoDB error while doing migration using django-allauth
Error i get djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "django_site" LIMIT 1 Params: (1,) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None I am trying to login using social media authentication(all-auth). But this gives error while migrating all-auth fields into database. I am using mongodb. -
How do I test url in Django with ?postId=1?
I want to test my url, but errors shows and something is wrong with this path Here is my path `path('comments/', views.get_comments_by_postid, name='comments')` and view i made `@require_http_methods(["GET"]) @login_required(login_url='login') def get_comments_by_postid(request): comment_id = request.GET.get('postId') comments_url = 'https://jsonplaceholder.typicode.com/comments' if comment_id is not None: comments_url += f'?postId={comment_id}' comments_response = requests.get(comments_url) comments = comments_response.json() return render(request, 'comments.html', {'comments': comments})` and that is the test i tried to make but it is not working, errors shows `def test_comments_by_added_postId_url(self): url = reverse('comments') + '?postId=1' print(resolve(url)) self.assertEquals(resolve(url).func, get_comments_by_postid)` -
"clean() got an unexpected keyword argument 'fix_unicode'"
clean() got an unexpected keyword argument 'fix_unicode' when i install clean-text i got errors Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] ERROR: Can not execute `setup.py` since setuptools is not available in the build environment. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. i tried everything available on internet but could not find any solution please help me to resolve this issue -
Auto select category code when we select the respective category
I am new in Django I am creating an admin panel where admin can create category list with category code. This is working fine. now my next task is that, admin will have the functionality to add product where he has to select the category name and i want that that category code belong to selected category should be auto selected when we select the category i have created a drop down for fetching the list of category category_list = Tcategory.objects.all() <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <label for="categories">Select Category</label> <select name="category" class="form-select form-control" id="category" name="category"> <option value="" disabled selected>Select Treatment Category</option> {%for categorys in category_list%} <option value="{{category}}">{{categorys}}</option> {%endfor%} </select> </div> </div> <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <input class="form-control" type="text" name="Tcategoryname" value="{{categorys.Tcode}}" placeholder="tcode"> </div> </div> By this I am able to fetch the list of category 1 - how i can get list of code from my model 2 - how i can do if user select category, and category code is auto selected -
upgrade django app from version 2 to the new(4)
How do I upgrade my django app from version 2 to the new(4). how to correctly and simply update the code, how to do it. here are the versions of all libraries It works on python 3.7.4 Babel==2.7.0 certifi==2019.6.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 Django==2.2.8 django-cas-ng==3.6.0 django-enum-choices==2.1.1 django-extensions==2.2.1 django-filter==2.1.0 django-method-override==1.0.3 django-rest-swagger==2.2.0 django-webpack-loader==0.6.0 djangorestframework==3.9.4 drf-extensions==0.5.0 idna==2.8 imagesize==1.1.0 itypes==1.1.0 Jinja2==2.10.1 lxml==4.4.1 Markdown==3.1.1 MarkupSafe==1.1.1 openapi-codec==1.3.2 packaging==19.0 psycopg2==2.8.2 Pygments==2.4.2 pyparsing==2.4.1.1 python-cas==1.4.0 pytz==2019.1 requests==2.22.0 setuptools==41.6.0 simplejson==3.16.0 six==1.12.0 snowballstemmer==1.9.0 sqlparse==0.3.0 uritemplate==3.0.0 urllib3==1.25.3 uuid==1.30 drf-yasg==1.17.0 waitress==1.4.2 httpretty==0.9.7 whitenoise==4.1.4 python-dotenv==0.10.3 django-cors-headers==3.1.1 django-nose==1.4.6 coverage==4.5.4 pycodestyle==2.5.0 I tried python -Wa manage.py test but i got an error from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' -
Data from DateTimeField() to TimeField() leaving only the time in the latter without the date?
Good morning! I have a django database model table. To fill this model table, data replenishment is used - a form in the template. One of the columns from this model table is a DateTimeField() data type. I also have a second table, the Django database model. The differences from the first table described above are minimal - just an additional added column - which has a TimeField() data type. I plan to copy from the first model - part of the data from the DateTimeField() column to the second table of the model - into the column - which has the data type TimeField(). I'm planning to copy some of the DateTimeField() data - just the time without the date. Data from DateTimeField() to TimeField() leaving only the time in the latter without the date. How can you come up with something for this? -
Wrong thumbnail url returned in Django/DRF
I am trying to create an application (Django and DRF), by which you can create and view posts. The posts contain an image, and the preview is supposed to only show a thumbnail of the original image, which will be created by the application using Pillow. I mainly followed this stackoverflow post, but changed it to fit my application. However, the image is saved in /media/images/, the thumbnail is saved in /media/resize/, the thumbnail-url is saved in the database as resize/image_thumb.jpg, but the thumbnail-url in the returned json-object in Postman is the image-url, not the thumbnail-url. Where am I going wrong? settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" urls.py from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('feed/', PostAPIView.as_view(), name='feed_of_posts'), path('feed/<int:id>', PostDetailAPIView.as_view(), name='update_delete_posts'), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class PostAPIView(ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.all() ... def perform_create(self, serializer): return serializer.save(poster = self.request.user) serializers.py class PostSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(source='image', required=False) class Meta: model = Post fields = ('id', 'image', 'pub_date', 'imageDescription', 'poster', 'thumbnail') def to_representation(self, instance): self.fields['poster'] = PosterSerializer(read_only=True) return super(PostSerializer, self).to_representation(instance) models.py class Post(models.Model): image = models.ImageField(upload_to='images/') thumbnail = models.ImageField(upload_to='resize/', editable=False) imageDescription = models.TextField() ... pub_date = models.DateTimeField(auto_now_add=True) … -
Add Fields to Django form not present in model
I have a student model to keep data of students. Models.py class Student(models.Model): roll_no = models.IntegerField(editable=True, blank=False, primary_key=True) name = models.CharField(max_length=30) date_of_birth = models.DateField(default='1900-01-01', blank=True) admission_no = models.IntegerField(default=roll_no) admission_date = models.DateField(default=datetime.now) student_cnic = models.CharField(max_length=15) father_cnic = models.CharField(max_length=15) grade = models.ForeignKey('school.SchoolClasses', on_delete=models.CASCADE, null=True, blank=True) mobile = models.CharField(max_length=12) active = models.BooleanField(default=True) Student Form looks like Forms.py class StudentForm(forms.ModelForm): extra_fields = ['school'] class Meta: model = Student fields = ['roll_no', 'name', 'date_of_birth', 'admission_no', 'admission_date', 'student_cnic', 'father_cnic', 'mobile', 'grade'] def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout(Row(Column('roll_no', css_class='form-group col-md-6'), Column('admission_no', css_class='form-group col-md-6'), ), Row(Column('date_of_birth', css_class='form-group col-md-6'), Column('admission_date', css_class='form-group col-md-6'), ), Row(Column('name', css_class='form-group col-md-3'), Column('student_cnic', css_class='form-group col-md-3'), Column('father_cnic', css_class='form-group col-md-3'), Column('mobile', css_class='form-group col-md-3'), ), Row( Column('school', css_class='form-group col-md-3'), Column('grade', css_class='form-group col-md-3'), ), Submit('submit', 'Add Student', css_class='btn btn-primary'), ) self.fields['date_of_birth'].widget = forms.DateInput(attrs={'type': 'date'}) self.fields['admission_date'].widget = forms.DateInput(attrs={'type': 'date'}) ` The school field is just to Filter the result for grade field to return only those grades present in the selected school But i am getting an error KeyError: "Key 'school' not found in 'StudentForm'. Choices are: admission_date, admission_no, date_of_birth, father_cnic, grade, mobile, name, roll_no, student_cnic." -
While deploying django app in jenkins why docker not run application when building image
I am new to CICD trying to understand docker. While deploying Django app using jenkins pipeline which is calling dockerfile to build docker image. The dockerfile calls runner.sh which have below line of code : uwsgi --http "0.0.0.0:${PORT}" --module my_proj.wsgi --master --processes 4 --threads 2 Everything is working fine, but i curious to know why this code not run application while building docker image and running application when this image is being run on host server. I tried running application in dockerfile in that case while deploying jenkins pipeline get stuck as it run the application and keep as stuck as application will keep on running while building image. -
How to extend the template for a Django Admin model add/create form?
In Django, you can override the Django Admin change forms by providing a path to a new template: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override change form template... change_form_template = "admin/some_custom_change_form.html" Then you can create a template within your application at app/templates/admin/some_custom_change_form.html that needs to extend the original template: {% extends "admin/change_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> I am trying to override not only the change form, but the form for creation/addition too. Django also provides add_form_template for the ModelAdmin interface too: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override add and change form template... change_form_template = "admin/some_custom_change_form.html" add_form_template = "admin/some_custom_add_form.html" Now I just need the original template to override. I can't for the life of me find in documentation where the templates you can override are located, so I made a best guess and tried admin/add_form.html {% extends "admin/add_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> Which throws an Exception on render of the add page, as it cannot find the chosen template to extend it. I've also tried using {% extends "admin/change_form.html" %} but that doesn't work as a different template is being used in … -
How to perform 2 operations in MathFilters ( Django )
I wanted to perform 2 operations 1: subtract entry_price from Exit_price then multiply the outcome by size. I am getting the error: Could not parse some characters: |(journals.exit_price||sub:journals.entry_price)|mul:journals.size <p class="pnl"> {% if journals.trade_direction == 'Long - Buy' %} {{ (journals.exit_price|sub:journals.entry_price)|mul:journals.size }} {% else %} {{ (journals.entry_price|sub:journals.exit_price)|mul:journals.size }} {% endif %} </p> -
django admin template overriding not working
I want to override templates/admin/change_form.html in my own django module app1, so following the standard, i added file change_form.html with following content to app1->templates->admin {% extends "admin/change_form.html" %} {% load i18n static %} {% block object-tools %} <h3>My extended html</h3> => Not rendered until => change_form_template = 'admin/change_form1.html' {{ block.super }} <script defer="defer" src="{% static 'app1/image_preview.js' %}"></script> {% endblock %} admin.py (I can achieve it by changing every admin and add giving change_form_template = 'admin/change_form1.html' but that is not the way i need it) from django.contrib import admin from .models import Model1 class Model1Admin(admin.ModelAdmin): # change_form_template = 'admin/change_form1.html' #overriding does not affect, but this does pass admin.site.register(Model1, Model1Admin) Expected output: <h3>My extended html</h3> should be the part of every change_form.html because I have extended admin/chamge_form.html without doing anything else anywhere while app1 exists in project and installed app in settings.py Complete steps (I have Django installed in default python of my system) django-admin startproject pr1 cd pr1 django-admin startapp app1 edited settings.py to append a line => INSTALLED_APPS += ['app1'] Added chnage_form.html to app1/templates/admin Made migrations, created superuser, logged in and opened http://127.0.0.1:8000/admin/app2/model1/add/ Complete code https://github.com/humblesami/django-templates -
I can't import multiselectfield
I'm trying to use multiselectfield in Django although I installed it with pip install django-multiselectfield and put it in my INSTALLED_APPS but I can't import it in my forms.py file... what can i do?