Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax call takes too much more time to be resolved
The waiting (TTFB) takes many seconds as we can see below enter image description here and actually, I doubt in an external directory I have added to my django's view because when I don't use it, everything goes well, and here my project structure. . ├── app | |_ init | |_ oop(.py) | ├── conjug_app │ |_ init | |_ admin | |_ apps | |_ models | |tests | |views │ ├── my_conjugaison │ | init | | asgi | | settings | |_ urls | |wsgi ├── templates │ | "some files here" │ ├── manage(.py) and here is the settings: from pathlib import Path import os, sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EXTERNAL_LIBS_PATH = os.path.join(BASE_DIR, "app") sys.path = ["", EXTERNAL_LIBS_PATH] + sys.path -
Django password_reset with appname
I'm using auth views for for resetting password in django. Since I've declared this views inside my users app and used appname for the URLs I'm getting an error. I know that I should change the URL inside the django pre-built templates but I don't know the best way of overriding this kind of stuff. this is URL.py of my user application: app_name = 'users' urlpatterns = [ path('register/', views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html' ), name='password_reset_complete'),] this is the error: NoReverseMatch at /users/password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. this is the line it's referring: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} -
TypeError at /project_members/ must be str, not Post
i recived errors in this line project_id=form.cleaned_data['project_id'] response =requests.post('http://172.16.0.111/api/v4/projects/'+project_id+'/members', headers=headers, data=data) please how to convert this in type string -
pass value from template to view in Django
I am new to django.I need to send id of clicked button to my function pdf_view that pdf view use id of that button for filtering and returning some data. Here is my template : (regions[i].id is a number between 1 to 10, it is the thing that I need to send to views.py) <h5 class="card-title">regions[i].id </h5> <a href="{% url 'app:pdf-data' %}"> export pdf </a> part of views.py: def pdf_view(request): reg = **********************here i need to get region from template*********************** data = Model.objects.filter(region=reg) context = {'data':data } If I put region equal to a number , every thing goes well.I just need to get region from template.Please help me with this problem. -
In Django, how to rename user model?
I trying to rename my user model CustomUser => User Here what I've done: Rename Python class and all references makemigrations Did you rename the accounts.CustomUser model to User? [y/N] y Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 168, in handle migration_name=self.migration_name, File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 186, in _detect_changes self.generate_altered_fields() File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 959, in generate_altered_fields dependencies.extend(self._get_dependencies_for_foreign_key(new_field)) File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 1086, in _get_dependencies_for_foreign_key dep_app_label = field.remote_field.model._meta.app_label AttributeError: 'SettingsReference' object has no attribute '_meta' So I'm stuck with this exception, any help appreciated :) -
UI for Django based chatbot
I am currently working on a django based chatbot but I can't get to integrate it with any UI available on net or articles . It would be of much help if I can get guidance to make a simple UI based on javascript to integrate with my bot. -
What is the root directory of a site deployed on heroku?
The Root page of the site is: amaze2020.herokuapp.com I need to save a verification .txt file into the root directory of amaze2020.herokuapp.com. -
Django .values() on field name with '%' sign: "ValueError: unsupported format character '_' (0x5f) at index 83"
I have a model with a field called %_Coverage, and when I try to pass this to .values on a QuerySet, Django throws an error saying "ValueError: unsupported format character '_' (0x5f)". How can I escape the percent sign that it runs correctly? My_Message = type('My_Message', (models.Model,), { '__module__': __name__, 'id': models.AutoField(primary_key=True), 'name': 'My_Message', '%_Coverage': models.IntegerField }) class Message: My_Message = models.ForeignKey(My_Message, on_delete=models.CASCADE, null=True, blank=True) messages = Message.objects.filter(message_name='My_Message').values('My_Message__%_Coverage') print(messages) # throws an error # This works: messages = Message.objects.filter(message_name='My_Message') print(messages) # prints: <QuerySet []> Using f'My_Message__%_Coverage' throws the same error, and 'My_Message__%%_Coverage' complains that the field is not found. Here is the traceback. Traceback (most recent call last): File "python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "python3.8/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "python3.8/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "views/message_viewer.py", line 220, in my_view print(messages) File "python3.8/site-packages/django/db/models/query.py", line 263, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) … -
How can I get csrftoken for the form?
How can I get csrf_token for a form in JS without using jQuery? I found this code in the documentation, but it uses jQuery. // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); -
Problems with automatically registering some models in django admin
I have a base model that looks like this: ... from core.admin import TimeStampedNamedAndDescriptionAdmin class EditableNameAndDescriptionModel(NameAndDescriptionModel, TimeStampedModel): def __str__(self): return self.name class Meta(NameAndDescriptionModel.Meta): abstract = True admin_class = TimeStampedNamedAndDescriptionAdmin and a model that's extending this one: class Kebab(EditableNameAndDescriptionModel): class Meta(EditableNameAndDescriptionModel.Meta): verbose_name = _("Kebab") verbose_name_plural = _("Kebabs") I'm trying to automatically register all models that has Meta.admin_class defined using this in urls.py (since the app registry is loaded here) from core.admin import auto_register_models ... auto_register_models() admin.py def auto_register(model): if hasattr(model._meta, "admin_class"): field_list = [f.name for f in model._meta.get_fields() if f.auto_created == False] model_admin = type("AutoRegisteredAdmin", (model._meta.admin_class,), {'list_display': field_list}) try: admin.site.register(model, model_admin) except AlreadyRegistered: pass def auto_register_models(): for model in apps.get_app_config('core').get_models(): auto_register(model) ... based on this: https://technowhisp.com/auto-registering-models-in-django-admin/ The models get registered, but this is what it looks like in django admin. It doesn't matter whether I use model._meta.admin_class or ModelAdmin in the code above. The results are the same. ... just black text without any links to the models. And the URL for the model (/core/kebab/) just gives me a 404. If I run this in admin.py the models get registered as expected: def auto_register(model): field_list = [f.name for f in model._meta.get_fields() if f.auto_created == False] model_admin = type("AutoRegisteredAdmin", (ModelAdmin,), {'list_display': field_list}) … -
how to perform put/patch method for a model with an extended user(onetoone field) relationship django rest framework
I have an account model generic to all user types, and when user signs up, they chose a particular role, and with post.save method the schema for that role is automatically created. I want the user to be able to update their profile(specific to their roles) after sign up. the problem is that I try using the put or patch method, it raises error that {user: {this field is required}} models.py class Specialist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, default=1, blank=True) description = models.TextField(blank=True) profile_picture = models.ImageField(upload_to='doc_image/', blank=True, null=True) def __str__(self): return f'{self.user}' serializer.py class Meta: model = Specialist optional_fields = ['user', ] fields = ['user', 'hospital', 'description', 'profile_picture'] extra_kwargs = { 'user': {'read_only': False}, 'user': {'validators': []}, } def update(self, instance, validated_data): instance.user = validated_data.get('user', instance.user) instance.hospital = validated_data.get('hospital', instance.hospital) instance.description = validated_data.get('hospital', instance.description) instance.profile_picture = validated_data.get('profile_picture', instance.profile_picture) instance = super().update(instance, validated_data) return instance views.py class SpecialistUpdateView(APIView): def get(self, request, doctor_id): try: model = Specialist.objects.get(user_id = doctor_id) except Specialist.DoesNotExist: return Response(f'doctor with the id {doctor_id} is not found', status=status.HTTP_404_NOT_FOUND) serializer = SpecialistUpdateSerializer(model) return Response(serializer.data) def patch(self, request, doctor_id): model = Specialist.objects.get(user_id=doctor_id) serializer = SpecialistUpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE) I think … -
Can't get my serializer to read my nest list of objects
I am still new to Django and I'm ripping my hair out with this issue. I am receiving a JSON object from an external API. That I'm trying to save to our DB from Django. Here is an example of the JSON object. { "A bunch of Keys": "and values", "Units": [ "Year": "2020", "Make": "Jay Flight SLX", "ETC" : "ETC" "Parts": [ { "DealerId": "", "MajorUnitPartsId": 10187618, "PartNumber": "06-0544", "SupplierCode": "672", "Qty": 1, "Cost": 37.95, "Price": 0.0, "Retail": 37.95, "SetupInstall": "I", "Description": "20# PROPANE COVER BLACK", "dealstate": 5, "internaltype": 2 }, { "DealerId": "", "MajorUnitPartsId": 9637201, "PartNumber": "0274320", "SupplierCode": "JAY", "Qty": 1, "Cost": 0.92, "Price": 4.99, "Retail": 4.99, "SetupInstall": "I", "Description": "BATTEN,HENDRIX BEACH .88X8' CP2", "dealstate": 5, "internaltype": 4 }, ] "Trade": [ { "DealerId": "", "StdMake": "COBRA", "StdModel": "31", "StdYear": "1993", "StdCategory": "", "allowance": 3000.0, "acv": 500.0, "payoff": 0.0, "lienholder": "", "modelname": "", "unitclass": "C", "color": "", "odometer": 0, "manufacturer": "PASSPORT", "note": "", "unittype": "CLASS C" } { Now the issue I am running into is when my serializer kicks in I want to pop each list and then save them to their own modules. The main table works, The Unit table works and the Trade table works. … -
How can I save the user model "id" Automatic
class User(AbstractUser): last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) email = models.CharField(max_length=100) to verify the login password class Summaries(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) extended model class Student(models.Model): user = models.ForeignKey(Summaries, related_name = "student", on_delete = models.CASCADE) pub_date = models.DateTimeField(auto_now_add=True) last_name = models.CharField(max_length=100, verbose_name="Фамилия") create data within a personal data class additional(models.Model): student = models.ForeignKey(Student, related_name = "marks", on_delete=models.CASCADE) class_name = models.CharField(max_length=100) additional data is stored def create_resume(request): context = {} additionalFormset = modelformset_factory(additional, form=additionalForm) form = StudentForm(request.POST or None) formset = additionalFormset(request.POST or None, queryset= additional.objects.none(), prefix='additional') if request.method == "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): student = form.save(commit=False) student.save() form.save_m2m() for guar in formset: data = guar.save(commit=False) data.student = student data.save() except IntegrityError: print("Error Encountered") return redirect('summary_vacancy:meine_biografiess') context['formset'] = formset context['form'] = form return render(request, 'summary_vacancy/create_resume.html', context) I saved an additional model I have to add the "id" myself when I create new data How can I save the User model "id" transaction.atomic(): i don't understand for 3 modules -
Setting custom pagination in Django
I'm trying to set a custom pagination for my API endpoint, where if there is a filter in the URL, Django must return a specific amount of records, and another amount of records if there isn't any filter. I have the following code: valid_filters = {'Name', 'Date'} def _has_valid_filters(iterable): return not valid_filters.isdisjoint(iterable) class MyPagination(LimitOffsetPagination): def get_page_size(self, request): if _has_valid_filters(request.query_params.items()): return 15 else: return 30 class MyView(viewsets.ModelViewSet): pagination_class = MyPagination http_method_names = ['get'] serializer_class = My_Serializer def get_queryset(self): valid_filters = { 'Name': 'Name', 'Date': 'Date__gte', } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} queryset = Model.objects.filter(**filters) return queryset The problem with this code is that the pagination is always the same. While MyPagination is called, it looks like get_page_size is never called. Can anyone help me out on this? -
Django-3.1/DRF/React: Unable to save nested images (linked through GenericRelation)
I am building a Django+DRF/React app (simple blog app) and i am facing difficulties saving nested images Model Structure Model: Post Children: details: ContentType Model ( DRF: save is successfull ) images: ContentType Model ( DRF : save is not successfull ) Process Send images from <input type="file" multiple /> Process data through FormData Catch request.data and process it class PostFormView(generics.RetrieveUpdateDestroyAPIView): queryset = Post._objects.is_active() serializer_class = PostModelSerializer permission_classes = (IsOwnerOr401,) parser_classes = (parsers.MultiPartParser,parsers.JSONParser, parsers.FormParser, parsers.FileUploadParser) lookup_field = 'slug' lookup_url_kwarg = 'slug' def get_queryset(self): return super().get_queryset().annotate(**sharedAnnotations(request=self.request)) def update(self, request, *args, **kwargs): data = request.data _images = data.getlist('images') images = [] for _ in _images: if isinstance(_, dict): images.append(images) continue images.append({'image': _, 'object_id': self.get_object().pk, 'content_type': self.get_object().get_content_type().pk}) data['images'] = images print(data) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): instance._prefetched_objects_cache = {} return Response(serializer.data) Save images (FAIL): class MediaModelSerializer(ContentTypeModelSerializer): # inherits object_id & content_type fields just to avoid writing them over and over alongside (create & update fns) class Meta: model = Media fields='__all__' class PostModelSerializer(WritableNestedModelSerializer): is_active = serializers.BooleanField(default=True) path = serializers.HyperlinkedIdentityField( view_name="api:post-detail", lookup_field='slug') images = MediaModelSerializer(many=True) details = DetailModelSerializer(required=False, many=True) # annotated fields is_author = serializers.BooleanField(read_only=True, default=False) class Meta: model = Post … -
Proper URL for Django Translation
I have two flag icons and I am willing to give them URLs to determine which language should be displayed using Django translation. Though, I am kind of confused about this. How may I do such a thing? HTML: <ul class="navbar-nav d-block d-lg-none ml-auto mr-3"> <li class="nav-item"> <a href="{% url 'products'%}"><div class="ukflag mr-1"></div></a> <a href="fa-ir/{% url 'products' %}"><div class="irflag"></div></a> </li> </ul> Products.Views.py: from django.shortcuts import render from django.views.generic import TemplateView class ProductPageView(TemplateView): template_name = 'products.html' URLs.py: from django.contrib import admin from django.urls import include, path from home.views import HomePageView from products.views import ProductPageView from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path("", HomePageView.as_view(), name='home'), path(_('products/'), ProductPageView.as_view(), name='products'), prefix_default_language = False ) -
ModuleNotFoundError: No module named 'useracc' When deploying to heroku
Actually I m deploying my project to heroku to check how its working. I have created an app for user registrations and login management. App is working fine in the development server. I have registered the app in the settings installed app. When i am trying to deploy the app in the heroku, it's failing continuously with the same error module not found. below is my traceback of the error. Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'useracc' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for … -
django Page not found (404), map cannot be found
I was working on this django project where I keep getting this error when I am trying to access sightings/map Error Message: Page not found (404) Request Method: GET Request URL: http://35.188.51.159/sightings/map/ Raised by: sightings.views.detail" And the terminal is prompting: Not Found: /sightings/map/ [20/Oct/2020 15:43:07] "GET /sightings/map/ HTTP/1.1" 404 1742 Here is my sightings/views.py file which gives the map: def show_map(request): sightings = Squirrel.objects.all()[:100] context = { 'sightings': sightings } return render(request, 'sightings/map.html', context) And the sightings/urls.py from django.urls import path from . import views app_name = 'sightings' urlpatterns = [ path('', views.index, name='index'), path('add/', views.add, name='add'), path('stats/', views.stats, name='stats'), path('<squirrel_id>/', views.detail, name='detail'), path('map/', views.show_map, name='show_map'), ] All my other functions work just fine, the only issue is map. -
Django view for Stripe Payment Intent
I am trying to make a Django REST view which creates a PaymentIntent object for Stripe and send the client the client-secret. This is the code for this handler in javascript, how would It look for a Django View? : import Stripe from "stripe"; const stripe = new Stripe(process.env.SECRET_KEY); export default async (req, res) => { if (req.method === "POST") { try { const { amount } = req.body; // Psst. For production-ready applications we recommend not using the // amount directly from the client without verifying it first. This is to // prevent bad actors from changing the total amount on the client before // it gets sent to the server. A good approach is to send the quantity of // a uniquely identifiable product and calculate the total price server-side. // Then, you would only fulfill orders using the quantity you charged for. const paymentIntent = await stripe.paymentIntents.create({ amount, currency: "usd" }); res.status(200).send(paymentIntent.client_secret); } catch (err) { res.status(500).json({ statusCode: 500, message: err.message }); } } else { res.setHeader("Allow", "POST"); res.status(405).end("Method Not Allowed"); } }; I basically just want to convert the above handler into a Django view but I don't know what the correct syntax is. -
How do i access my webcam with python (Django) from the browser with the help of HTML and Javascript?
I am trying to create a web-app and I need to get video input from the webcam into Javascript or HTML and pass it to Python (Django) where I can use OpenCV with each frame. -
custom context_processor gives empty queryset
I have added a simple context_processors as follows, even though data is there, its output is empty, could anybody see something missing? context_processorys.py from .cms_models import Logo def custom_logos(request): return { 'obj': Logo.objects.all() } template config TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', 'client_apps.context_processors.custom_logos', ], }, }, ] client_apps is the name of my app, and if I do {{obj}} in base template it gives empty queryset -
passing model attributes to URL in Django
I am new to Django. I have a model with 2 fields called id (as pk) and region.I have a page to return objects in each region.There are 10 regions and I need to pass region number to url to retrieve data from db filtering that region. Here is my code : views.py def render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') *********here i need to get region from clicked button instead of pk************* data = MyModel.objects.filter(region=pk) template_path = 'pdf/Pdf.html' context = {'data':data} return response urls.py path('pdf/<pk>/', render_pdf_view, name='pdf-data') ***I need to pass region instead of pk*** template <a href="{% url 'application : pdf-data' ? %}"> export pdf </a> I don't know how to pass the region from clicked button to view and then pass it to url. Any help would be appreciated. -
API for delevery of fodd
The component provides an API for communicating with other components: Accepts and saves zones as a set of coordinates; Accepts the data of Couriers with reference to the delivery area; Accepts the coordinates of the delivery location and returns the Courier data and the delivery area ID. Not quite sure what models I should make and how it should work, would be grateful for a couple of tips -
Django registraton error appearing as one string
I have a registration page and I and trying to display the validation error message to the user. When I try to pass the error message to an alert is appears as a single alert with the list as a single string. I cannot get it to appear as multiple alerts. views.py def register_page(request): form = CreateUserForm() context = {'form': form} if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('dashboard:login') else: errors = dict(form.errors.items()) error_messages = [] for i in errors.keys(): for j in errors[i]: error_messages.append(j) messages.info(request, error_messages) return render(request, 'main/register.html', context) register.html {% for message in messages %} <div class="error-message alert alert-danger bottom" role="alert"> <div> <a class="close" href="#" data-dismiss="alert">×</a> {{ message }} </div> </div> {% endfor %} screenshot -
How to override Django admin delete_selected_confirmation.html
In my Django admin. If I delete anything in superadmin or inside an user created by superadmin it shows a confirmation page. I have delete_confirmation.html in my templates under my admin and in my another app. if i change anything in it or add a line it doesn't change plus it shows objects in my page which i don't want. i don't know how to override it.Plese refer to the image.My delete confirmation page