Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom django mangement command to add/amend views.py, filters.py etc
Django has the built-in command startapp which creates a new app directory and some standard files within. I was wondering whether custom management commands (or something different?) can be used to automate similar repetitive steps. For example I find myself repeating a certain set of steps when creating certain generic new homepages. To name a few: Adding a url to urlpatterns in <app>.urls.py Creating a template in <app>.templates Adding a view, subclassing django.views.generic.TemplateView to <app>.views.py Adding the template to the view Adding ViewSet to <app>.rest.py Register this ViewSet to router in <app>.urls.py Ideally I would like to create a command in the following style createNewPage --viewName <name1> --viewSetName <name2> --url <url> --api <api_url> Is something like this achievable? -
issue with Ajax request & Django
I am trying to parse data from my selected items in the datatable towards my ajax request wich will go to a view in Django: Js: ` $(document).ready(function() { var table var userLang = navigator.language || navigator.userLanguage; if (userLang == "fr-BE") { url = 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/French.json' } else { url = 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/Dutch.json' } table = $('#example').DataTable( { columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { orderable: false, style: 'multi', selector: 'td:first-child' }, language: { url: url } } ); } ); $('#submit_phones').click( function() { var info = table.rows( { selected: true } ).data(); var URL = "{% url 'upload_devices' %}"; $.ajax({ type: "POST", url: URL, dataType: "json", data: { info : info , csrfmiddlewaretoken : '{{ csrf_token }}' }, success : function(json) { alert(json); alert("Successfully sent the data to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); alert($.ajax) }); ` When i call info just after the assignment it is filled with objects. The button click function gets called but the only thing thats in my request is the middlewaretoken variable -
Weird saving behavior on django user field on save
I have 2 models User and Suspension class Suspension: content_type = models.ForeignKey(ContentType, related_name='suspension', on_delete=models.CASCADE) object_id = models.CharField(max_length=255) content_object = GenericForeignKey('content_type', 'object_id') suspended = models.BooleanField(_("suspended"), default=False) reason = models.TextField(blank=True) I want to change user.is_active based on a related suspension.suspended instance. My code is: def form_valid(self, form): from userprofile.models import User as user model_name = self.get_model_name_from_url_kwargs() model = eval(model_name) suspension, created = Suspension.objects.get_or_create( content_type = ContentType.objects.get(app_label=model._meta.app_label, model=model._meta.model_name), object_id = self.kwargs['pk'], ) suspension.reason = form.cleaned_data['reason'] suspension.suspended = form.cleaned_data['suspended'] suspension.content_object.is_active = not form.cleaned_data['suspended'] suspension.save() return super().form_valid(form) I can confirm that printing suspension.content_object.is_active returns a correct result, however, it is not saved. What is wrong? -
Django Rest Framework: How to use EXCEPTION_HANDLER with DEBUG = True?
I'm using a custom exception handler for my REST API. I'd like to use my custom exception handler, which responds with JSON data that my front end knows how to handle. The problem is that with the setting DEBUG = True, Django doesn't use my custom exception handler. Instead, it responds with the standard HTML debug page, like this: Here's my settings.py: DEBUG = True REST_FRAMEWORK = { # I still get the default Django 'EXCEPTION_HANDLER': 'stripe_app.utils.custom_exception_handler' } ... I know that I could just set DEBUG = False, but if I did that I'd also have to change many other things that use the DEBUG variable. So, How can I use my custom exception handler with the DEBUG = True setting? I've already looked for answers in the DRF docs: https://www.django-rest-framework.org/api-guide/settings/#exception_handler and the Django docs: https://docs.djangoproject.com/en/3.1/ref/settings/#debug but I can't find the answer I'm looking for. -
Django Switcher behaving unexpectedly
I have a switcher object that as I understand it would return the value function if it has matched the key in the parameters. Here is the code to better understand the process: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def test_switch(request): first_switcher = { 'first': first_call(), 'second': second_call(), 'third': third_call(), 'fourth': fourth_call() } second_switcher = { 'one': one_fxn(), 'two': two_fxn(), 'three': three_fxn() } if first_switcher.get('first', False): if second_switcher.get('one', False): logger.info("got here") def first_call(): logger.info('first switcher first args') return True def second_call(): logger.info('first switcher second args') return True def third_call(): logger.info('first switcher third args') return True def fourth_call(): logger.info('first switcher fourth args') return True def one_fxn(): logger.info('second switcher one args') return True def two_fxn(): logger.info('second switcher two args') return True def three_fxn(): logger.info('second switcher three args') return True The program is expected to return the value function it matched the key into. Something like this: first switcher first args second switcher one args got here But it's calling all the functions as seen in the log files. first switcher first args first switcher second args first switcher third args first switcher fourth args second switcher one args second switcher two args second switcher three args … -
How to fix this error in Django, "Cannot assign must be an instance."
I need help fixing this weird error please. I have an application whereby a teacher can add assignment, the student can then submit assignment and then the teacher can grade it. Right now, every other functionalities works perfectly well except when grading the result. Error log Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\sms\schoolapp\views.py", line 1948, in grading_submit Assignment_name=grade_field_assignment_name, Grade=grade_field, Out_Of_Grade=out_grade_filed) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\db\models\base.py", line 483, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 220, in __set__ self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /en/grading_submit Exception Value: Cannot assign "'STUDENT 1'": "Grade_Student.Student_ID" must be a "add_students_by_manager" instance. models.py class Grade_Student(models.Model): Student_ID = models.ForeignKey(add_students_by_manager, on_delete=models.CASCADE) course = models.ForeignKey(add_courses, on_delete=models.CASCADE) Assignment_name = models.CharField(max_length=200) Grade = models.IntegerField() Out_Of_Grade = models.IntegerField() def __str__(self): return str(self.Student_ID) + " scored " + str(self.Grade) + " out of " + str(self.Out_Of_Grade) + " in " + str(self.course) views.py def grading_submit(request): if request.method=="POST": grade_field_stu_id = request.POST.get('grade_field_stu_id') grade_field_course_name = request.POST.get('grade_field_course_name') grade_field_assignment_name = request.POST.get('grade_field_assignment_name') grade_field = request.POST.get('grade_field') out_grade_filed = request.POST.get('out_grade_filed') print(grade_field, grade_field_stu_id, grade_field_course_name, grade_field_assignment_name, out_grade_filed) Grade_Student_data= Grade_Student(Student_ID=grade_field_stu_id, course=grade_field_course_name, Assignment_name=grade_field_assignment_name, Grade=grade_field, Out_Of_Grade=out_grade_filed) Grade_Student_data.save() messages.success(request, _("You Successfully Grade a student!")) return redirect('assignment_page') else: return redirect('/') grading_page.html … -
Django test using same DB all the time
I'm working on adding test code in the middle of the work. There are lots of DB like School, Academy those are crawled and Category that should exist before test. So, is there any idea that whenever I run test, there already be School, Academy, Category in DB? -
Add extra content to django admin instance select
I have model Video and when I go to this model in the django admin, I want an additional context with request ({'request': request}) to be passed to the template, how to do it? -
Content Security Policy (CSP) Not Set: django and apache server
I am getting Content Security Policy (CSP) Not Set errors despite of Configuring django-csp flags integration in django settings.py file. Only getting errors with /static/ folder. CSP flag used: CSP_STYLE_SRC = ("'self'",) http://ip_address/static/ http://site_own_ip_address/static/css/ -
Django-rest-framework : Trying to display datas from intermediate table
I have problems to display some datas in my API. I have two tables (Book and Order) + one other intermediate table (Ordering) with an extra field (number of each book in one order). I try to display this extra field when I serialize my orders. My models : title = models.CharField(max_length=255) author = models.CharField(max_length=255, null=True) genre = models.CharField(max_length=255, null=True) height = models.IntegerField(null=True) description = models.TextField(null=True) publisher = models.CharField(max_length=255, null=True) quantity = models.IntegerField(null=True) ratings = models.IntegerField(null=True) def __str__(self): return self.title class Order(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) books = models.ManyToManyField(Book, through='Ordering') def __str__(self): return '%s : %s' % (self.user, list(self.books.all())) class Ordering(models.Model): book = models.ForeignKey(Book, related_name='book_in_order', on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name='order_has_books', on_delete=models.CASCADE) books_number = models.IntegerField() def __str__(self): return f"{self.books_number}" And the serializers: class Meta: model = Book fields = '__all__' class UserSerializer(serializers.ModelSerializer): order_set = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = User fields = '__all__' extra_kwargs = {'password': { 'write_only': True, 'required': True, }} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class OrderingSerializer(serializers.Serializer): book = BookSerializer() class Meta: model = Ordering fields = '__all__' return serializer.data class OrderSerializer(serializers.ModelSerializer): books = serializers.StringRelatedField(many=True, read_only=True) user = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = Order fields = '__all__' … -
drf-spectacular does not detect any schema
I want to use drf-spectacular (https://github.com/tfranzel/drf-spectacular) to create an open api documentation for my django API. All my view can be find like this: my app / views / view1.py view2.py I mostly use the generics views, here is an example: class SystemDetail(generics.RetrieveAPIView): """ Get a system detail User in group x can see all system. Other groups have access to system with the corresponding dealer name. For now it return Not Found id Not Authorized. """ lookup_field = 'uuid' def get_queryset(self): user_groups = self.request.user.groups.all().values_list('name', flat=True) if 'x' not in user_groups: dealer = MANUFACTER_CHOICE dealer_name: str = [dealer_name[1] for dealer_name in dealer if dealer_name[1].lower() in user_groups][0] return System.objects.filter(dealer__name=dealer_name) return System.objects.all() def get_serializer_class(self): user_groups = self.request.user.groups.all().values_list('name', flat=True) if 'x' not in user_groups: return ExternalSystemSerializer return SystemSerializer I set up drf-spectacular using the docs. I added it to my INSTALLED_APPS in my settings.py and in my urls. urlpatterns = [ # back path('', include('api.urls')), path('schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), path('v1/', include('users.urls.v1', namespace='users')),] All my endpoint are served under my-domain-name/v1/my-endpoint. When I try to see my swagger It returns an empty dict as if I had no views in my project, however when I was using … -
Manage django administration on tenants
Good evening, I'am configuring a django app with multitenancy: single database shared schema. I want that each user (to which I'll add an extra field like "is_tenant_administrator") can access ONLY to the administration of its tenant and no more; Furthermore the user "supersusers" can administrate over all tenants. Is there any official documentation to how manage this? I found other posts but it is so old... Thank you for your help. -
Django Webpack - cannot use file loader on dev mode
I am using the Django Webpack environment. But I cannot use url() tags that I have defined in css or scss in development environment (eg: app.scss). It works smoothly in production environment. What changes should I make to the webpack config files to fix the problem? Thanks. dev mode prod mode app.js import '../scss/app.scss' base.html {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example</title> {% render_bundle 'app' 'css' %} </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!-- Content --> <h1 class="hello">hello world</h1> <!-- Content --> {% if settings.DEBUG and settings.WEBPACK_LIVE_SERVER %} <script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/vendor.bundle.js"></script> <script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/app.bundle.js"></script> {% else %} {% render_bundle 'vendor' 'js' %} {% render_bundle 'app' 'js' %} {% endif %} </body> </html> app.scss @import "variables"; @import "~bootstrap/scss/bootstrap"; @font-face { font-family: "Source Sans Pro"; src: url("../fonts/SourceSansPro-Light.woff2") format("woff2"); … -
Can django be used for real time complex apps?
I'm learning django so i built Facebook clone with it the code is about 10k lines and I've no idea how to make it real time Should i use ajax? They use append function they add the template in it in the tutorials meanwhile the template alone in the clone is 500lines it's gonna be weird And in django channels they're only using chat apps in examples so I don't know how to customise it Is there any techniques to make it real time or django isn't made for for real time apps? -
Concatenate two model fields and produce sum field
So I was trying to concatenate field A and field B which would result into field C. But I can't make it work. Can anyone enlighten me? This is the model that I was using class Claims(TimeStampedModel): A = models.ForeignKey( 'InsureePolicy', related_name='Insuree', on_delete=models.CASCADE) B = models.DateTimeField(null=True, blank=True) C = models.CharField(max_length=256, blank=True, null=True) -
serialization of a value from two models with links to foreign key
A have three models: class ModelA(models.Model): some_field = models.ForeignKey(ModelB) class ModelC(models.Model): some_field = models.ForeignKey(ModelB) class ModelB(models.Model): first_field = models.CharField() second_field = models.CharField() I want serialize ModelA and get value from ModelC. How can you do it? class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ('id', 'some_field', 'here_is_value_from_ModelC'???) -
Save network device config into database
I try to get the configuration from a network device (switch, router, firewall) and save it into a database. To do so I use Netconf with the ncclient library. The configuration is received in the XML format. Here is an example of a configuration. <native xmlns=\"http://cisco.com/ns/yang/Cisco-IOS-XE-native\"> <hostname>R1</hostname> <username> <name>testuser</name> <password> <encryption>15</encryption> <password>123</password> </password> </username> <username> <name>user</name> <privilege>15</privilege> <secret> <encryption>15</encryption> <secret>123</secret> </secret> </username> <interface> <GigabitEthernet> <name>1</name> <description>MANAGEMENT INTERFACE</description> <ip> <address> <primary> <address>10.10.20.48</address> <mask>255.255.255.0</mask> </primary> </address> </ip> </GigabitEthernet> <GigabitEthernet> <name>2</name> <description>Test</description> <ip> <address> <primary> <address>10.10.30.2</address> <mask>255.255.255.0</mask> </primary> </address> </ip> </GigabitEthernet> </interface> <ntp> <server xmlns=\"http://cisco.com/ns/yang/Cisco-IOS-XE-ntp\"> <server-list> <ip-address>2.3.4.5</ip-address> </server-list> <server-list> <ip-address>6.6.6.6</ip-address> </server-list> </server> </ntp> </native> I use django REST framework with the following models: class Interface(models.Model): SPEED = (('10Base', '10'), ('100Base', '100'), ('1GBase', '1000'), ('2.5GBase', '2500'), ('5GBase', '5000'), ('10GBase', '10000'), ('40GBase', '40000'), ('100GBase', '100000')) name = models.CharField(max_length=50, blank=False, null=False) description = models.CharField(max_length=200, blank=True, null=True) speed = models.CharField(max_length=50, choices=SPEED, blank=False, null=False) if_type = models.CharField(max_length=50, blank=True, null=True) enabled = models.BooleanField(blank=True, null=True) class Device(models.Model): hostname = models.CharField(max_length=50, blank=True, null=True) boot_variable = models.CharField(max_length=50, blank=True, null=True) interfaces = models.ManyToManyField(to=Interface, blank=True, related_name='interfaces') To save the configuration into the database I use ElementTree: from xml.etree import ElementTree as ET def parse_xml_to_dict(self, xml_data: str) -> dict: dom = ET.fromstring(xml_data) device_data = {} … -
How to check for particular constraint in Django?
I have Following model. class BusCompanyStaff(BaseModel): user = models.OneToOneField( BusCompanyUser, on_delete=models.CASCADE ) position = models.ForeignKey( StaffPosition, on_delete=models.SET_NULL, null=True, related_name='position' ) created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='created_by' ) staff_of = models.ForeignKey( BusCompany, on_delete=models.CASCADE ) and my StaffPostion model is class StaffPosition(BaseModel): name = TitleCharField( max_length=20, validators=[validate_staff_position], unique=True) class Meta: default_permissions = () verbose_name = 'Staff Position' verbose_name_plural = 'Staff Positions' def __str__(self): return self.name Problem is one bus company can only have one staff position 'Owner' and allow many other staff position i.e 'mamagers, cashiers' but Owner position is set to be unique for particular bus company. I tried this in clean method. def clean(self): if len(BusCompanyStaff.objects.filter( position__name='Owner')) > 1: raise DjangoValidationError( {'position': _('Cannot Assign two owners.')} ) But above method checked 'Owner' for all bus companies I am not getting how to make Owner as Unique for particular bus company. -
Why does the html file render differently with Django and when opened directly?
The code below was taken from Bootstrap https://getbootstrap.com/docs/5.0/examples/headers/. When I run the code below through Django, I get the following result: Django Result But when I open the html file directly I get this: Direct HTML Why do they look so different? I opened the inspector and the code is exactly the same <!DOCTYPE html> <html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.82.0"> <title>Headers · Bootstrap v5.0</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/headers/"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180"> <link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png"> <link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png"> <link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json"> <link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3"> <link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico"> <meta name="theme-color" content="#7952b3"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --> <link href="headers.css" rel="stylesheet"> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="bootstrap" viewBox="0 0 118 94"> <title>Bootstrap</title> <path fill-rule="evenodd" clip-rule="evenodd" d="M24.509 0c-6.733 0-11.715 5.893-11.492 12.284.214 6.14-.064 14.092-2.066 20.577C8.943 39.365 5.547 43.485 0 44.014v5.972c5.547.529 8.943 4.649 10.951 11.153 2.002 6.485 2.28 14.437 2.066 20.577C12.794 … -
Django, Python: coordinates are getting converted automatically from db
Good morning, inside my django-application I have a second database (which I can only read from, so not my own) that's build into my settings.py. One of the columns has point-coordinates like... POINT (390002.1610814564 6001433.406049595) When selecting the data from db with... try: with connections['db_second'].cursor() as cursor: cursor.execute("SELECT * from ...") row = cursor.fetchall() except Exception as e: cursor.close() ...this data get's converted into... 0101000020E964000022936245FEDA1741A4A29D5E0DE85641 Does anyone know how to stop this (auto)converting? Or do I have to convert this data manually back into the needed coordinate-system? And if so: does anyone know how this convertion-type is called? Note: The data comes from a postgres-db. Thank you for all your help and have a great day! -
django-hosts redirecting to another domain
I followed the official django-hosts documentation and successfully created subdomains but the links in my app are redirecting me another domain like if I have href='{% static 'login' %}' it will redirect me to 'login/' instead of 'subdomain.locahost/login'. -
problem with serializing many objects from file Django-Rest_Framework
I have a small REST API application that connects with google books and allows user to GET books as json, filter by date and authors. I m stuck now because i want to implement functionality to post books. I dont know how to create and such serializer that will instantiate himself with books from json_books.json and save himself as models regarding many to many realtion of book and authors. I am not even sure if this is possible :) If so any idea how to write it ? models.py class Book(models.Model): title = models.CharField(max_length=1000) published_date = models.DateField(auto_now_add=False) categories = models.CharField(max_length=300, null=True, blank=True) average_rating = models.FloatField(null=True, blank=True) ratings_count = models.IntegerField(null=True, blank=True) thumbnail = models.URLField(null=True, blank=True) def __str__(self): return f'title: {self.title} \n' \ f'date of publication: {self.published_date} \n' \ f'authors: {[author.name for author in self.authors.all()]}' class Author(models.Model): name = models.CharField(max_length=200) books = models.ManyToManyField(Book, related_name='authors') def __str__(self): return str(self.name) views.py def save_to_file(request): query = request.GET.get('query') FILE = 'STXnext/json_books.json' URL = f'https://www.googleapis.com/books/v1/volumes?q={query}' books = get_from_google_api(URL) with open(FILE, 'w') as f: f.write(json.dumps(books, indent=4)) messages.success( request, f"books with query{query} added to file ", fail_silently=True ) return redirect(reverse_url('home')) After saving to file my json_books.json looks like this [ { "authors": [ "Kristin Thompson" ], "title": "The Frodo … -
source code visible on browser when i navigate language django and extension of page is html
please solve my error i am very sad of this stuff. I dont know the html is visible other url are working fine but the problem occurs only when i visit this above url body { color: rgb(255, 153, 0); background: #f5f5f5; font-family: 'Varela Round', sans-serif; background: linear-gradient(to right, midnightblue, midnightblue 10%, rgb(255, 255, 255) 10%); overflow: hidden; background-clip: text; -webkit-background-clip: text; background-size: 200% 100%; background-position: 100%; transition: background-position 275ms ease; } .form-control { box-shadow: none; border-color: #ddd; } .form-control:focus { border-color: #000000; } .login-form { width: 350px; margin: 0 auto; padding: 30px 0; } .login-form form { color: #000000; border-radius: 1px; margin-top: 60px; margin-bottom: 15px; background: rgb(170, 255, 0); border: 1px solid #f3f3f3; box-shadow: 0px 2px 20px rgba(0, 0, 0, 0.9); padding: 30px; } .login-form h4 { text-align: center; font-size: 22px; margin-bottom: 20px; } .login-form .avatar { color: #fff; margin: 0 auto 30px; text-align: center; width: 100px; height: 100px; border-radius: 50%; z-index: 9; background: #4aba70; padding: 15px; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1); } .login-form .avatar i { font-size: 62px; } .login-form .form-group { margin-bottom: 20px; } .login-form .form-control, .login-form .btn { min-height: 40px; border-radius: 2px; transition: all 0.5s; } .login-form .close { position: absolute; top: 15px; … -
Print the table from admin page django
I am new to django and web development, I want to ask is there a way to print the table in the admin page onto paper? -
Django model is saving twice with image resize
I am trying to resize images before upload using the following code. However, I get two saved models after submitting the form when I apply the custom def save(self, *args, **kwargs): function. Why is that? class Players(models.Model): super().save(*args, **kwargs) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) player_img = models.ImageField(upload_to='profile_pics', default="default.jpg", null=True, blank=True) def save(self, *args, **kwargs): img_read = storage.open(self.player_img.name, 'rb') img = Image.open(img_read) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) in_mem_file = io.BytesIO() img.convert('RGB').save(in_mem_file, format='JPEG') img.save(in_mem_file, format='JPEG') img_write = storage.open(self.player_img.name, 'w+') img_write.write(in_mem_file.getvalue()) img_write.close() img_read.close() Views.py class player_add(LoginRequiredMixin, CreateView): model = Players template_name = 'player_create.html' form_class = forms.PlayerForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form)