Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at / Reverse for 'conference' not found. 'conference' is not a valid view function or pattern name
I'm working on my project and I got stuck on this issue and have no ideas how to solve it. <li class="nav-item"> <a class="nav-link {% if 'conference' in segment %} active {% endif %}" href="{% url 'conference' %}"> <i class="ni ni-collection text-blue"></i> <span class="nav-link-text">Конференц зал</span> I got error here. my views.py from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse @login_required(login_url="/login/") def index(request): context = {'segment': 'conference'} html_template = loader.get_template('conference/conference.html') return HttpResponse(html_template.render(context, request)) @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] if load_template == 'admin': return HttpResponseRedirect(reverse('admin:index')) context['segment'] = load_template html_template = loader.get_template('home/' + load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template('home/page-404.html') return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template('home/page-500.html') return HttpResponse(html_template.render(context, request)) my urls.py of my app from django.urls import path from .views import * urlpatterns = [ path('conference/', index, name='conference'), # Other URL patterns for your app's views... ] All my apps are in apps folder. I have one folder for all templates of apps and inside of that I have templates with … -
unable to access admin panel django
I have changed my views and more specifically the request-mappings to "spring-like request mappings for djang". There for I had to change my urls to work as follows link to Pypi documentation of spring-like request mappings for django. After that change tho, Im unable to access admin panel, even tho I have it registered in my project urls.py. Project urls.py: from myapp.views import UserView from django.contrib import admin urlpatterns = UrlPattern() urlpatterns.register(UserView) urlpatterns += [path('', include('myapp.urls'))] urlpatterns += [path('admin/', admin.site.urls)] Of course I have it imported in my settings, it used to work before that url refactoring I did. I just want to mention that I like this way of work and my question is specifically how do I fix the access to the admin panel, if it is possible ofc. The error Im getting is: The current path, admin/, didn’t match any of these. -
Using the Tnymce Responsive File Manager in Django
How can I use Tnymce File Responsive Manager in Django? I can't use it in any way! I tried writing some code but it didn't work. Please help me! ` Full content {{ new.full_info }} ` <script type="text/javascript"> tinymce.init({ selector: 'textarea#myTextarea', plugins: [ 'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help', ], toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | insertfile link image | print preview media fullscreen | ' + 'forecolor backcolor emoticons | help', menu: { favs: { title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons' } }, menubar: 'favs file edit view insert format tools table help ', tinydrive_upload_path: '/upload', // content_css: 'css/content.css', file_picker_callback: function(callback, value, meta) { if (meta.filetype === 'file') { // Fayl tanlash dialogini ochish tinymce.activeEditor.windowManager.openUrl({ url: '/admin/filepicker/', // Fayl tanlash uchun Django view URL title: 'Fayl tanlash', onMessage: function(dialogApi, details) { // Tanlangan faylni fayl tanlash dialogidan olib kelib, callback ga uzatish callback(details.file); dialogApi.close(); } }); } } }); </script> -
drf-yasg : How can we use doc-string of different methods other than standard http method for swagger api documentation
I am using drf-yasg and django-rest-framework. I am having one common parent class which is having all http method defined, which will be inherited in sub-classes where business logic methods will be overided. I want subclass overrided method docstring in swagger api documentation class BaseAPIView(APIView): """ Base API View. """ def get(self, request): """ Base API get method description. """ result = self.process_get() # Call the overridden method return Response(result) def process_get(self): raise NotImplementedError class DerivedAPIView(BaseAPIView): """ Derived API View. """ def process_get(self): """ List all items. """ items = [ {"name": "Item 1", "description": "Description of Item 1", "price": 10.99}, {"name": "Item 2", "description": "Description of Item 2", "price": 20.99} ] return Response(items) Here in swagger document for DerivedAPIView get method i want DerivedAPIView process_get method docstring as api documentation. -
DRF: Redirect unauthenticated users to login form
Is there a way to redirect users who didn't pass through rest_framework.permissions.IsAuthenticated permission to login page? I can achieve it by rewriting dispatch method of my ApiView and adding extra NotAuthenticated exception catcher, but is there a softer way to do this? class IndexView(APIView): permission_classes = [ IsAuthenticated, ] def get(self, request, format=None): ... def dispatch(self, request, *args, **kwargs): self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except NotAuthenticated: "<---- added by me" return redirect("/login") except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response -
Change city slug on django-cities to only have city name with hyphens
I am using django-cities in my project, and I am stuck at an issue which I can't seem to be able to overcome on my own. I basically need the slug field of the City model to only list the city name, with hyphens if the name has spaces. This is the standard behaviour of the Country model slug. Instead, the City model returns something like [id]-[city]. So the slug for Country is: United-Arab-Emirates But the slug for City is: 292968-Abu-Dhabi I think I've identified where this is generated in django-cities. The BaseCity model has a field slug_contains_id which is set to True, then the slugify method adds it to the slug before the city name: django-cites.models: class BaseCity(Place, SlugModel): slug_contains_id = True name_std = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities', on_delete=SET_NULL_OR_CASCADE) region = models.ForeignKey(Region, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) subregion = models.ForeignKey(Subregion, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) location = PointField() population = models.IntegerField() elevation = models.IntegerField(null=True) kind = models.CharField(max_length=10) # http://www.geonames.org/export/codes.html timezone = models.CharField(max_length=40) class Meta: abstract = True unique_together = (('country', 'region', 'subregion', 'id', 'name'),) verbose_name_plural = "cities" @property def parent(self): return self.region def slugify(self): if self.id: return '{}-{}'.format(self.id, unicode_func(self.name)) return None But what I'm unable to … -
how to add next and prev pages in our single blog post in django
i wanna add next and prev pages in my single blog post and i tried something but dose not work so well and this my url that i made for my site http://127.0.0.1:8000/blog/pid views.py def blog_single(request, pid): post = blog_Post.objects.get(published_date__lte=timezone.now(), status=1, pk=pid) post.counted_views += 1 post.save() context = {'post':post} return render(request, "blog/blog-single.html", context) i try this next_post = blog_Post.objects.filter(id__gt=post.id).order_by('id').first() prev_post = blog_Post.objects.filter(id__lt=post.id).order_by('id').last() but it dose not work -
Django Docker container without database container - best practise?
I am a little bit confused about the database Docker container. I read everywhere that is not good practise to dockerize a database, for example here. But if I search for Django Docker container then I see almost in every Docker Compose file that a Postgres database container is included. For example I have this docker-compose.yml file: version: '3.9' services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - .:/app command: > sh -c "python manage.py migrate && python app/manage.py runserver 192.168.1.65:8000" env_file: - variables.env depends_on: - db db: image: postgres:13-alpine container_name: postgres volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=dzijn - POSTGRES_USER=zijn - POSTGRES_PASSWORD=password volumes: dev-db-data: dev-static-data: It has also a Docker database. Is it better to omit the database container in the Docker Compose file and for example to store the database in a cloud service? Because I am using Microsoft Azure for the hosting. -
General way of iterating over a dictionary containing multiple mpld3 graph images in Django?
I am working on a personal project. One part of this is to display multiple histograms on a webpage. So far, I have been able to get this to work using the following code: views.py: import pandas as pd import matplotlib.pyplot as plt,mpld3 import scipy.stats as stats import numpy as np for column in df.columns: fig=plt.figure() plt.hist(df[column]) histogram=mpld3.fig_to_html(fig) context[f"{column}Histogram"]=[histogram] HTML Code: {% for elem in PregnanciesHistogram %} {{elem|safe}} {% endfor %} {% for elem in GlucoseHistogram %} {{elem|safe}} {% endfor %} {% for elem in BloodPressureHistogram %} {{elem|safe}} {% endfor %} {% for elem in SkinThicknessHistogram %} {{elem|safe}} {% endfor %} {% for elem in InsulinHistogram %} {{elem|safe}} {% endfor %} {% for elem in BMIHistogram %} {{elem|safe}} {% endfor %} {% for elem in DiabetesPedigreeFunctionHistogram %} {{elem|safe}} {% endfor %} {% for elem in AgeHistogram %} {{elem|safe}} {% endfor %} I do see all the histograms on my webpage, but the problem is that all of the HTML code uses hardcoded keys in the dictionary. Is there a general way of writing what I wrote in this HTML code, using a for loop, without hardcoding the keys from the dictionary? I would appreciate it if someone could tell me … -
How to (conditionally) remove SCRIPT_NAME from MEDIA_URL in urls.py
Situation: working in Debug=True mode in Django. I want to serve files from the media root, so I follow the documentation hint: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And it works perfectly (remember to read the note: MEDIA_URL should be local i.e. media/. Don't put a / in front of it. Important!). I have a media resource called 123456.txt, in the admin interface I get the link: /media/123456.txt. Now I move to Apache (still in debug), but I run this Django site in a subfolder of the server, and everything works fine, thanks to the WSGI variable SCRIPT_NAME which gets prepended to all URIs. So just to be clear, I have https://example.com/subfolder as the root for the Django site and the previous media resource called 123456.txt, in the admin interface I get the link: /subfolder/media/123456.txt. So the link is correct. When I request the resource https://example.com/subfolder/media/123456.txt, Apache recognizes the subfolder and sends to Django a request for media/123456.txt, as expected. The problem is that the url pattern created by the static() helper function now includes the SCRIPT_NAME prefix, so when I click on the resource, I get an exception … -
Django SELECT Query
Hi Iam try to select from mysql using Django my models.py from django.db import models from django.db.models import Q class Series(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) des = models.CharField(max_length=255) img = models.CharField(max_length=255) isseries = models.IntegerField() istrend = models.CharField(max_length=255) background_img = models.CharField(max_length=255) trial_url = models.CharField(max_length=255) imdb_id = models.CharField(max_length=255) rate = models.CharField(max_length=255) date = models.CharField(max_length=255) status = models.IntegerField() isdel = models.IntegerField() section_id = models.IntegerField() poster_img = models.CharField(max_length=255) genres = models.CharField(max_length=255) class Meta: db_table = 'series' my sample Script series = series_db.objects.filter(istrend=1,status=1,isdel=0).order_by('id').values() i want to SELECT all columnt without isdel so i remove isdel from models.py, but when i remove it i cant use isdel to make WHERE isdel = 0 in mysql so i got This Error django.core.exceptions.FieldError: Cannot resolve keyword 'isdel' into field. so how i can use isdel to make a condition without select it LIKE this Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` = '1' AND `series`.`status` = 1) ORDER BY `series`.`id` ASC real Example SELECT `series`.`id`, `series`.`title`, `series`.`des`, `series`.`img`, `series`.`isseries`, `series`.`istrend`, `series`.`background_img`, `series`.`trial_url`, `series`.`imdb_id`, `series`.`rate`, `series`.`date`, `series`.`status`, `series`.`isdel`, `series`.`section_id`, `series`.`poster_img`, `series`.`genres` FROM `series` WHERE (`series`.`isdel` = 0 AND `series`.`istrend` … -
I am trying to install django-jazzmin but I am getting an error
When I try to install django-jazzmin using command pip install django-jazzmin I am getting the error. ERROR: Could not find a version that satisfies the requirement django>=2 (from django-jazzmin) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, 1.11.28, 1.11.29) ERROR: No matching distribution found … -
chatterbot: how to utter a default welcome message?
My Chatterbot instance is ready and trained. But it only replies when the user initialize the conversation. I want my chatterbot instance to utter a default message. How can I do that? My chatterbot instance is installed in a "django project". -
Celery Task Signals, Headers not accessible in signals.task_prerun
I am trying to change the behaviour of celery tasks by defining before_task_publish and task_prerun handler, requirement is, i need pass certain data between the tasks. I am trying to modify the headers of before_task_publish and trying to access the same in task_prerun using task.request.headers, but headers are blank. My approach is: from celery_setup import celery_app from celery import Celery, signals @signals.before_task_publish.connect def before_task_publish_handler(sender=None, body=None, headers=None, **kwargs): headers['shared_data'] = "Data to share" @celery_app.task def my_task(arg): print("Task running:", arg) @signals.task_prerun.connect def task_prerun_handler(task_id=None, task=None, **kwargs): shared_data = task.request.headers.get('shared_data') if shared_data: print("Shared data in task_prerun:", shared_data) # Calling the task my_task.apply_async(args=("Hello, Celery!",), headers={}) i am using celery 4.4.4 with Python3.7 I have try this approach, i am expecting to share the data among signals. -
Django: multiple return from one class of models.py, but problems using it in another class
I would like to use the same class to pull two teams and display them in a django admin combobox when inserting records. When I extracted only one teams it worked fine, all ok, but now that I added two returns it doesn't work. How can I use the same Teams class to return the team_home and team_away that I will use in the New_Match class? (team_home and team_away will be two comboboxes). I tried writing Teams.team_home and Teams.team_away, but I got the error: TypeError: 'DeferredAttribute' object is not callable. I don't even know if this was a good idea models.py class Teams(models.Model): team_home = models.CharField(max_length=40) team_away = models.CharField(max_length=40) def __str__(self): return self.team_home, self.team_away class New_Match(models.Model): team_home = ChainedForeignKey( Teams, related_name='team_home', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) team_away = ChainedForeignKey( Teams, related_name='team_away', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) P.S: I'm using smart_selects -
NotImplementedError: This backend doesn't support absolute paths.(Django)
I am trying to upload my media files to AWS Bucket and I am completely able to upload them there on bucket using this code. model.py class Evidence(models.Model): """ Stores an individual evidence file, related to :model:`reporting.ReportFindingLink` and :model:`users.User`. """ def set_upload_destination(self, filename): """ Sets the `upload_to` destination to the evidence folder for the associated report ID. """ return os.path.join("evidence", str(self.finding.report.id), filename) document = models.FileField( upload_to=set_upload_destination, validators=[validate_evidence_extension], blank=True, ) finding = models.ForeignKey("ReportFindingLink", on_delete=models.CASCADE) views.py def form_valid(self, form, **kwargs): self.object = form.save(commit=False) self.object.uploaded_by = self.request.user self.object.finding = self.finding_instance try: self.object.save() messages.success(self.request,"Evidence uploaded successfully", extra_tags="alert-success") except: messages.error(self.request, "Evidence file failed to upload", extra_tags="alert-danger") return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): if "modal" in self.kwargs: return reverse("reporting:upload_evidence_modal_success") return reverse("reporting:report_detail", args=(self.object.finding.report.pk,)) All of this is working fine. But trouble occurs when I am trying to delete the file. Huh? Here is my code for deleting the file. I must tell you guys that there is relationship established between Evidence and ReportingLink table. class ReportFindingLinkDelete(LoginRequiredMixin, SingleObjectMixin, View): """ Delete an individual :model:`reporting.ReportFindingLink`. """ model = ReportFindingLink def post(self, *args, **kwargs): finding = self.get_object() finding.delete() data = { "result": "success", "message": "Successfully deleted {finding} and cleaned up evidence".format(finding=finding), } logger.info( "Deleted %s %s by request of %s", finding.__class__.__name__, finding.id, … -
How merge different table record and show on timeline with django?
I have different table for different medias (like video, audio, ebooks) extending one abstract mode. I want to show them by merging in some order. This is my abstract model: class Media(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(default='', max_length=128) thumbs = GenericRelation(Image) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(to=User, null=True, on_delete=models.SET_NULL) class Meta: abstract = True And this is my extended Audio model: class Audio(Series): duration = models.IntegerField(default=0) metadata = GenericRelation(Metadata, related_query_name='audio_metadata', null=True) # some other fields How do I create a ranking system on the basis of some values in my media tables? And my second question is should the data with rankings be stored in Relation database? (If I store the ranks in some relation database, I would have to create django Generic model I guess and then I can keep data in cache and show on timeline). Please suggest here. -
has anyone used milvus vector database with Django
I am planning on using Django to front end an application that uses one of the ML/AI platforms, and the milvus vector database looks like a good choice. The question is how to use milvus as the database for Django? I have found the python libraries but none that reference how to do it with Django. I am hoping to get some advice on how to hook up milvus vector database to Django. -
What is apps.py in django?
I read about this,And i cunfused The application server takes the INSTALLED_APPS and loads or generates an AppConfig object for each app. This collection of AppConfig objects are then stored in an instance of theApps class. Please someone explain with simple example. Thanks -
Large File Uploads with Amazon S3 + Django 400 Bad Request
i was following this course, i think i did everything right but it gives me POST https://fakebucket.s3-eu-north-1.amazonaws.com/ 400 (Bad Request) views.py class FilePolicyAPI(APIView): """ This view is to get the AWS Upload Policy for our s3 bucket. What we do here is first create a FileItem object instance in our Django backend. This is to include the FileItem instance in the path we will use within our bucket as you'll see below. """ permission_classes = [permissions.IsAuthenticated] authentication_classes = [authentication.SessionAuthentication] def post(self, request, *args, **kwargs): """ The initial post request includes the filename and auth credientails. In our case, we'll use Session Authentication but any auth should work. """ filename_req = request.data.get('filename') if not filename_req: return Response({"message": "A filename is required"}, status=status.HTTP_400_BAD_REQUEST) policy_expires = int(time.time()+5000) user = request.user username_str = str(request.user.username) """ Below we create the Django object. We'll use this in our upload path to AWS. Example: To-be-uploaded file's name: Some Random File.mp4 Eventual Path on S3: <bucket>/username/2312/2312.mp4 """ file_obj = Post.objects.create( author = request.user, title=filename_req ) file_obj_id = file_obj.id upload_start_path = "{username}/".format( username = username_str, file_obj_id=file_obj_id ) _, file_extension = os.path.splitext(filename_req) filename_final = "{file_obj_id}{file_extension}".format( file_obj_id= file_obj_id, file_extension=file_extension ) """ Eventual file_upload_path includes the renamed file to the Django-stored FileItem … -
Error while running python3 manage.py migrate_schemas --shared in Django multi-tenant application
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Meta: swappable = 'AUTH_USER_MODEL' # Add related_name arguments to avoid clash with auth.User groups = models.ManyToManyField( 'auth.Group', related_name='user_custom_set', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user_custom', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='user_custom_set', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', related_query_name='user_custom', ) `your text` SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'django.contrib.contenttypes', "student", "teacher", "tenant", "account", ) INSTALLED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', "student", "teacher", "account", ) python3 manage.py migrate_schemas --shared \[standard:public\] === Running migrate for schema public \[standard:public\] Operations to perform: \[standard:public\] Apply all migrations: account, admin, auth, contenttypes, sessions, sites, student, teacher, tenant \[standard:public\] Running migrations: \[standard:public\] Applying contenttypes.0001_initial... \[standard:public\] OK \[standard:public\] Applying contenttypes.0002_remove_content_type_name... \[standard:public\] OK \[standard:public\] Applying auth.0001_initial... \[standard:public\] OK \[standard:public\] Applying auth.0002_alter_permission_name_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0003_alter_user_email_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0004_alter_user_username_opts... \[standard:public\] OK \[standard:public\] Applying auth.0005_alter_user_last_login_null... \[standard:public\] OK … -
Django form and Inline form with crispy forms layout
I have a form with a custom layout from "crispy forms" and an inline form manually in HTML. If I don't use custom layouts, I can save both with no problem, however I'll need to make a button to submit the forms together using layouts. This is my HTML: <form id="registro-form" class="main-form" action="?" method="POST"> <!-- Main Form --> {% csrf_token %} {% crispy form %} <hr> <!-- Inline Formset --> {{ itens_formset.management_form }} {% for formset_form in itens_formset %} <div class="inline-formset-item"> <!-- Render inline formset fields manually --> <div class="row no-gutters"> <!-- Render formset fields here --> </div> </div> {% endfor %} <!-- Submit Button --> <button class="btn btn-success mt-2 mb-5" type="submit" style="width: 110px;">Salvar</button> </form> This is my html code at the moment, but when I click the submit button, nothing happens. This is my views.py: class RegistrarCreate(GroupRequiredMixin, CreateView): # GroupRequiredMixin and other attributes def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ItemFormSet = inlineformset_factory(Registro, Item, form=ItemForm, extra=1, can_delete=False) if self.request.POST: context['itens_formset'] = ItemFormSet(self.request.POST, instance=self.object) else: context['itens_formset'] = ItemFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() itens_formset = context['itens_formset'] if itens_formset.is_valid(): self.object = form.save() itens_formset.instance = self.object itens_formset.save() return super().form_valid(form) else: print("Formset is invalid") print(itens_formset.errors) return self.render_to_response(self.get_context_data(form=form)) def get(self, request, *args, … -
The difference between prefetch_related and model_set in Djnago
I wonder what is the best flow when I need to retrieve foreign key model objects. is it to use prefetch_related in views.py like: queryset = queryset.prefetch_related('book_set') context={objects:queryset} or to use directly in the template by model_set: {% for attach in objects.book_set.all %} what is better and which one is good for performance? -
Cannot render custom form field in templates
So I've built this some kind of spam detection field that I want to use in our templates. As you can render other other form fields in the template with form.X, I cannot render this one: {{ forms.tour_form.form.spam_field }} <web.utils.forms.HoneypotField object at 0x7f3c0fd98820> But I can't seem to find what's the issue here? I'm using SpamDetectFormMixin in my forms. class HoneypotField(forms.BooleanField): default_widget = forms.CheckboxInput( attrs={"class": "hidden", "tabindex": "-1", "autocomplete": "off"} ) def __init__(self, *args, **kwargs): kwargs.setdefault("widget", self.default_widget) kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if cleaned_value := super().clean(value): raise ValidationError("") return cleaned_value class SpamDetectFormMixin(forms.Form): spam_field_keys = ["adf", "adg", "adh"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.random_key = random.choice(self.spam_field_keys) self.fields[self.random_key] = HoneypotField() @property def spam_field(self): return self.fields[self.random_key] -
How to make generate Custom ID for employee in django using different String
I have model's like this : class Karyawan(models.Model): id_karyawan = models.CharField(max_length=10, blank=True,null=True) nama_karyawan = models.CharField(max_length=50) jabatan = models.CharField(max_length=15) branch_id = models.ForeignKey(Branch, on_delete = models.CASCADE,null=True) agen_id = models.ForeignKey(Agen, on_delete = models.CASCADE,null=True) salary = models.IntegerField() alamat_karyawan = models.TextField() tanggal_masuk = models.DateField(null=True) kota_karyawan = models.CharField(max_length=30, null=True) ttl_karyawan = models.DateField(null=True) tanggal_resign = models.DateField(null=True,blank=True) no_hp_karyawan = models.CharField(max_length=15) slug_karyawan = AutoSlugField(populate_from='id_karyawan') I want id_karyawan filled using branch_id at first then following id using unique id like 'BDO001','BDO002', 'JKT001' etc.