Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Id from CreateView in django
Hello all I need some help getting the id from an object in django I have a createView where I want to send an notification for the user when a new object is created, and I need the object Id... def form_valid(self, form): # setting fields that are not open to user form.instance.created_by = self.request.user form.instance.status = 'open' messages.success(self.request, 'Ticket Created Successfully!') Notification.objects.create( created_by=self.request.user, created_for=form.instance.responsible, title=f"New ticket from {self.request.user.first_name} {self.request.user.last_name} =====> {form.instance.id}", message=f"Hello",) return super().form_valid(form) The problem is that {form.instance.id} is always none. Anyone can help me with that? Thanks in advance -
Why do my javascript integration in a django template does not work?
I am really new to django and i am trying to build a small page where a chart with chart.js is shown. I want to load the javascript file static. I created a basic html-file called data_table.html and added a folder static where three files are in: data_table.js, styles.css and a picture bild.jpg. The html file is: {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css"> <script type="text/javascript" src="{% static 'data_table.js' %}"></script> <title>Data viewer</title> </head> <body> <canvas id="myChart" width="200" height="200"></canvas> <script> </script> <p class="text">Picture:</p> <br> <img class="img" src="{% static 'bild.jpg' %}" alt="My image"> </body> </html> The css file and the picture are loaded. The picture is displayed and with the css file i can resize the picture. So that works i guess? The javascripts file looks as follows: const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for d in data%}'{{d.label}}',{%endfor%}], datasets: [{ label: '# of Votes', data: [{% for d in data%}{{d.data}},{%endfor%}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, … -
Django export model to csv for ManyToManyField
Have a few tables for which I successfully built export to CSV, based on the Models. However, for one where I count the 'likes' for the news (posts) I'm getting nowhere. Here is my model: class News(models.Model): news_title = models.CharField(max_length=300) news_text = models.TextField(max_length=2000) news_author = models.CharField(max_length=150) news_date = models.DateField(default=now) likes = models.ManyToManyField(User, related_name='user_like', blank=True) @property def total_likes(self): return self.likes.count() Problem is, that I can print out to CSV all items from the model, but if I print "likes" I get duplicated (or more) rows in CSV. The reason is, that if News is liked by 3 users, I get 3x rows on CSV for each User and under "Like Count" column I get their IDs. What I would like to get instead is: 1x row per News with a total of likes for each news. and view.py @login_required def export_news(request): newss = News.objects.all() response = HttpResponse(content_type='txt/csv') writer = csv.writer(response) writer.writerow(["ID","Title","Author","Date","Text","Likes Count"]) for news in newss.values_list('id','news_title','news_author','news_date','news_text','likes'): writer.writerow(news) response['Content-Disposition'] = 'attachment; filename="News_list.csv"' return response Appreciate any help. Thx -
How to get current value from django table
I am only getting the last value from my django table after clicking the delete button. html file - <body> <div class="for-body"> <!-- test table --> <form method="POST" action=""> {% csrf_token %} <input id="label" name="engname" value="{{ eng_name }}">{{ eng_name }}</input> <button name="update" class="add-button" type="submit"><b>Update</b></button> <button name="add" class="add-button1" type="submit"><b>Add Existing User</b></button> <tbody class="for-tbody1"> <tr class="for-tr1"> <td class="for-td1"> <dh-components-grid-body-render class="for-dhcomp"> <div class="for-div1"> <table class="for-table1" id="pgnum"> <thead class="for-thead1"> <tr class="for-tr2"> <td class="for-td2"><div class="dh-grid-headers-cell-default">User</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Email</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Role</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Remove</div></td> </tr> </thead> <tbody class="for-tbody2"> <tr class="for-tr3"> {% for i in user_list %} <td class="for-td3"><div class="cell-default-style">{{i.first_name}} {{i.last_name}}</div></td> <td class="for-td3"><div class="cell-default-style"><input type="hidden" value="{{ i.email }}" name="email">{{i.email}}</input></div></td> {% if i.is_superuser == True %} <td class="for-td3"><div class="cell-default-style">Super User</div></td> {% elif i.is_staff == True %} <td class="for-td3"><div class="cell-default-style">Admin</div></td> {% else %} <td class="for-td3"><div class="cell-default-style">Practitioner</div></td> {% endif %} <td class="for-td3"><div class="cell-default-style"><button class="btn" name="delete" type="submit"><img src="/static/assets/images/trash1.png" style="width: 18px;" alt="Delete"></button></div></td> </tr> {% endfor %} </tbody> </table> </div> </dh-components-grid-body-render> </td> </tr> </tbody> </form> </div> </body> views.py - def engagement_admin_edit(request, id): staff = request.user.is_staff a = User.is_authenticated if staff == True: eng_list = Grp.objects.all() eng = Grp.objects.get(id = id) eng_name = eng.gname eng_name = str(eng_name) eng_id = eng.id cursor = connection.cursor() cursor.execute('''SELECT * FROM main_enguser WHERE eid=%s''',[eng_id]) row = cursor.fetchall() users … -
How to optimize loading millions of records in MongoDB with Django admin?
I have MongoDB with over 20 million records integrated with Django administration. Both services are running in k8s. I have already applied some of the optimisations below: Adding NoCountPaginator (disable counting) Indexing MongoDB Sorting queryset Also, I read about adding skip and limit is not recommended since it will make the performance even worse. But still, loading is extremely slow and frequently throws timeout errors. Here's the custom manager to get queryset: models.py class RuleDataManagerRemoved(DjongoManager): def get_queryset(self): event_horizon = datetime.datetime.now() - datetime.timedelta(days=180) return RuleDataQuerySet(model=self.model, using=self._db, hints=self._hints).filter(last_change__gte=event_horizon) The filtering happens with indexed field, so I think the impact is not critical here. admin.py @admin.register(models.ChangedProductSlugs) class ChangedProductSlugsAdmin(RuleDataAdmin): paginator = NoCountPaginator show_full_result_count = False list_display = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug', 'tld', 'last_change', 'created_by', 'stav') list_filter = ('last_change', ('old_product_slug', SingleTextInputFilterOldProduct), ('old_category_slug', SingleTextInputFilterOldCategory), ('new_product_slug', SingleTextInputFilterNewProduct), ('new_category_slug', SingleTextInputFilterNewCategory), 'deleted', 'deleted_by', 'tld') search_fields = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug') resource_class = resources.ChangedProductSlugsResource actions = ['restore_queryset'] def stav(self, obj): return not obj.deleted stav.boolean = True def changelist_view(self, request, extra_context=None): default_filter = False try: ref = request.META['HTTP_REFERER'] pinfo = request.META['PATH_INFO'] qstr = ref.split(pinfo) if len(qstr) < 2: default_filter = True except: default_filter = True if default_filter: q = request.GET.copy() q['deleted__exact'] = '0' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() return super(ChangedProductSlugsAdmin, … -
Django HttpRequest type hint / annotation problem
def my_func(request: HttpRequest) -> str: return request.user.email gives me a warning in PyCharm, saying that user is not a defined attribute. However writing it as request: HttpRequest() removes this warning, and gives me proper parameters in suggestions. Could someone explain why this is happening, and if I did something wrong? I'm importing HttpRequest from django.http. -
Django | I want to show the page to 'AnonymousUser' even though I'm using request.user in views.py
I want to show the page to all users even if they are not logged in but because im using request.user in views.py this is not possible. Is there anyway to handle this? views.py: class ServerView(View): def get(self, request, server_tag): server = Server.objects.get(tag=server_tag) posts = server.posts.all() is_following = False relation = ServerFollow.objects.filter(server=server, user=request.user) if relation.exists(): is_following = True return render(request, 'servers/server.html', {'server':server, 'posts':posts, 'is_following':is_following}) -
GA4 accounts not listed in Python
I want to list GA4 accounts in Python. But first, the user needs to connect Google Analytics account. Then I want to list the accounts with google.analytics.admin. How should I go about this? I followed this document but it didn't work: https://developers.google.com/analytics/devguides/config/admin/v1/quickstart-client-libraries#step_1_enable_the_api -
Django more type of user - ask about advice
I work on my project and i want create 3 type of user include Admin(user and second user with different premission). I want ask which method i should use to do it ? I read a bit about AbstractUser, create group and "flag's" 1th user - will can only add comment/ save file 2th user - will can create model and what 1th have 3th user - admin Admin after 2th get created should get notification that 2th suer get created and he need to accept his perrmision first (before he can create models like email and admin can do it in admin panel i think) -
Django DetailView count increases by 3 instead of 1
I have a webpage where every view is being counted by and incremented by 3 where it is intended to be incremented by 1 instead here's what I have in my views.py from django.views.generic import ListView, DetailView class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail, self).get_object() object.views_count += 1 object.save() return object def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context html <section class="movie"> <img src="{{object.image.url}}"> <ul> <li>{{object}}</li> <li>{{object.description}}</li> <li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li> <li><a href="">{{object.cast}}</a></li> <li><i class="fa fa-eye" id="eye"></i> {{object.views_count}}</li> </ul> </section> It is scripted to increment by 1 but does not follow that logic.. what went wrong here? -
AttributeError at /class/55910/ 'tuple' object has no attribute 'get'
I've check the return render(), etc, I've all solutions and nothing happened. Thanks for solution, if you can solve this :) There is my classpage_views.py from django.shortcuts import render from django.http import HttpResponse from numpy import append from .models import Classes def class_article_preview(request, URLcodenumber): codenumber = Classes.objects.get(codenumber=URLcodenumber) schoolNum = '' classNum = '' def div_by_s_and_c(num): preSortArray = [] classSimLen = 1 if codenumber.is_2num_class == False: classSimLen = 1 else: classSimLen = 2 for sim in num: preSortArray.append(sim) schoolNumLen = len(codenumber.codenumber) - classSimLen for sim in preSortArray: nonlocal schoolNum schoolNum = schoolNum + str(sim) schoolNumLen = schoolNumLen - 1 if schoolNumLen <= 0: break for sim in reversed(preSortArray): nonlocal classNum classNum = classNum + sim classSimLen = classSimLen - 1 if classSimLen <= 0: classNum = classNum[::-1] break return classNum, schoolNum div_by_s_and_c(codenumber.codenumber) return classNum, schoolNum context = {'clsName': f'Школа №{schoolNum}, \n{classNum} параллель', 'articles': ['test', 'test2']} return render(request, 'blogpage\\articles_preview.html', context) def class_article_create(request): return render(request, 'blogpage\\create_article.html') This is traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/class/55910/ Django Version: 4.0.3 Python Version: 3.10.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'start_page', 'help_page', 'class_page'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner … -
What Django model field to use for the following JSON data from draft.js (react-draft-wysiwyg)?
I have a react-draft-wysiwyg component in my NextJS app, and I am trying to find a way to store that to my Django REST backend. This is the stringified JSON I get directly from the draft component, but I am not sure how to organize the django model to store such data as well as be able to make PATCH and GET requests later. Would appreciate any help! { blocks: [ { key: '64o0i', text: 'Introduction edited', type: 'header-three', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'dcomv', text: 'this will be the awesome shit', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'edvnc', text: 'Body paragraph', type: 'header-three', depth: 0, inlineStyleRanges: [ { offset: 0, length: 14, style: 'color-rgb(0,0,0)' }, { offset: 0, length: 14, style: 'bgcolor-rgb(255,255,255)' }, { offset: 0, length: 14, style: 'fontsize-24' }, { offset: 0, length: 14, style: 'fontfamily-ui-sans-serif, system-ui, -apple-system, "system-ui", "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji', }, ], entityRanges: [], data: {}, }, { key: 'd3sf7', text: 'this will be the awesome shit klasdfj lk;', type: 'unstyled', depth: 0, inlineStyleRanges: … -
Can't get data when writing interface using djangorestframework
from django.http import JsonResponse, Http404 from django.views import View from rest_framework.generics import GenericAPIView from rest_framework import filters from rest_framework.response import Response from persons.models import Persons from persons.serializer import PersonModelSerializer import json class PersonList(GenericAPIView): filter_backends = [filters.OrderingFilter] ordering_fields = ['name','nickname','grangs'] queryset = Persons.objects.all() serializer_class = PersonModelSerializer def get(self,request): person_qs = self.queryset person_qs = self.filter_queryset(person_qs) serializer = self.get_serializer(instance=person_qs,many=True) return Response(serializer.data) 编写一个查询接口报错提示: 'Do not evaluate the .queryset attribute directly, ' RuntimeError: Do not evaluate the .queryset attribute directly, as the result will be cached and reused between requests. Use .all() or call .get_queryset() instead.enter image description here -
Using a custom language gives "You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting."
I've just upgraded my Django project from 2.2 to 3.2 and the language broke. I had this piece of code which was working fine (inside my settings.py) LANGUAGE_CODE = 'tb' EXTRA_LANG_INFO = { 'tb': { 'bidi': False, 'code': 'tb', 'name': 'English', 'name_local': 'United States', 'fallback': ['en-US'], }, } import django.conf.locale LANG_INFO = dict(**django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO Now I get ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. Why is this happening and how can I fix it? Thanks. -
Static dict definition is python application till application is running
Trying to implement the the java static map implementation in python application. Tried approach: created a global dict, and trying to access it and update the same but not working. Created a class and created a global variable and trying to set and fetch from there. class staticdict: dict={} def init(self,type,data): self.dict[type]=data def __getitem__(self,type): return self.dict[type] setting the values : staticdict(type,nseTemp) fetching the values : print(" data----- "+ staticdict.getitem(type)) Error : TypeError: staticdict.getitem() missing 1 required positional argument: 'type' Also not sure this approach will work or it will keep on creating the new instance of class and override the dict present in the class. I want to keep the dict which will hold the data for static map -
How to use _set in SerializerMethod for instance?
I want to calculate the average rating by using SerializerMethodField(). The error in the following code is AttributeError: 'FeedbackModel' object has no attribute 'aggregate' I think _set is missing but I don't know where to put it..! class FeedbackSerializer(serializers.ModelSerializer): feedback_by_user_profile_pic = serializers.ImageField(source='feedback_by.profile_pic') average_rating = serializers.SerializerMethodField() def get_average_rating(self,instance): return instance.aggregate(average_rating=Avg('rating'))['average_rating'] class Meta: model = FeedbackModel fields = ['feedback_text','rating','date','feedback_by_user_profile_pic','average_rating'] Feedback Model class FeedbackModel(models.Model): feedback_text = models.CharField(max_length=1000) rating = models.IntegerField() date = models.DateField(auto_now=True) feedback_by = models.ForeignKey(UserModel,on_delete=models.CASCADE) business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'feedback' -
Django REST Serializer permanently changed in init
I'm facing a weird issue with DRF: I have several serializers for which I want to display certain fields only under specific conditions, such as url parameters there being in the request or the user having certain permissions. To decouple my serializer's presentation logic from the business logic, I decided to add a conditional_fields attribute to the serializer's Meta class: it's a dict in which the keys are strings representing conditions, such as "SHOW_HIDDEN_FIELDS" and their values are lists of field names that need to be removed if the key isn't present in the serializer context. Then I override my viewsets' get_serializer_context method to get the desired values inside of context. I made a remove_unsatisfied_condition_fields method which does the following: def remove_unsatisfied_condition_fields(self): conditional_fields = self.Meta.conditional_fields for condition, fields in conditional_fields.items(): if not self.context.get(condition, False): for field in fields: self.fields.pop(field, None) The serializers making use of it look like this: class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = Exercise fields = [ "id", "text", "solution", "correct_choices" ] conditional_fields = { "EXERCISE_SHOW_HIDDEN_FIELDS": ["solution", "correct_choices"], } Here comes the problem: if I manually call this method inside my serializers, in their __init__ method, like this: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.remove_unsatisfied_condition_fields() everything works fine. … -
The css in extended html file(child file) is not working in django
I have created two html pages and a CSS file in static directory This is my main.html {% load static %} <html> <head> <title> </title> <link rel ="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <nav> <ul> <li><img src="{% static 'images/logo.jpg'%}" height="49px" width="100px" > <li><a href=#> HOME</a></li> <li><a href=#> ABOUT</a></li> <li><a href="rent"> RENT</a></li> <li><a href="sale"> SALES</a></li> </ul> </nav> {% block content %} {% endblock %} </body> <hr> <footer> The CSS in main.html is working, This is my index.html {% extends 'main.html' %} {% block content %} <div id="showcase"> <div class="section-main container" > <h1>House rent & Sale</h1> <p class="lead hide-on-small">This is a web application </p> </div> </div> {% endblock%} The CSS in index.html is networking. How can I solve this ? Please help me -
Django Model advance Foreignkey Relation
I have a Django model which has relationship with user model. Where user are assigned to groups. especially "Admin", "Teacher","Student". So I want to make a foreign key relationship in such a way that it will show only The users that have been assigned to Teacher groups for Teacher_details model, And Similar for Student_Details Model. I have made the models Teacher_Details , Student_Details and established foreign key relation with User model. But the problem is that its showing all the user when I am filling Student_Details or Teacher_Details. Hope you got my problem. I am hoping positive response. The code looks like this: class Student_Details(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='none', upload_to='img/') details_updated = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=150) admission_date = models.DateField() previous_college = models.CharField(max_length=150) course_enrolled = models.ForeignKey(ModelUniversity,on_delete=models.CASCADE) semester = models.CharField(max_length=20,choices=semester,default=None) def __str__(self): return self.user.first_name class Teacher_Details(models.Model): address = models.CharField(max_length=150) image = models.ImageField(default='none', upload_to='img/') details_updated = models.DateTimeField(auto_now_add=True) subject_taught = models.ManyToManyField(to='Student.stu_subject') user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.first_name def subject_teacher_teaches(self): return [str(s) for s in self.subject_taught.all()] -
Django ForeignKey self conditions
I have the model, where each Character has 'mother' and 'father' fields. They are FroeignKey which refers to self. I want to put condition for the gender, 'F', 'Female' for the mother field and 'H', 'Male' for the father field. class Character(models.Model): H = 'Male' F = 'Female' GENDER_CHOICES = ( (H, 'Male'), (F, 'Female'), ) last_name = models.fields.CharField(max_length=100) first_name = models.fields.CharField(max_length=100) gender = models.CharField(max_length=30, choices=GENDER_CHOICES, null=True, blank=True) mother = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkmother') father = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkfather') date_birth = models.DateField(default=date.today, null=True, blank=True) date_death = models.DateField(default=date.today, null=True, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' -
Django - implement nested loop in ajax function
I have a Django app (3.2) and I am trying to implement filters in Ajax in jquery that will filter all products based on selected filters. The problem is that Ajax is filtering only areas, not needs and products. How can I implement a nested loop in Ajax so it will work in the same way as my product_list and I will see not the whole area but only relevant products? views.py def filter_data(request): client_type = request.GET.getlist('client_type[]') business_challange = request.GET.getlist('business_challange[]') product_list = Area.objects.prefetch_related(Prefetch("need_area", queryset=Need.objects.filter(category_need__product__isnull=False,category_need__product__status=1).distinct())).filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct() if len(client_type) > 0: product_list = product_list.filter(need_area__category_need__product__client_type__title__in=client_type).distinct() if len(business_challange) > 0: product_list = product_list.filter(need_area__category_need__product__business_challange__title__in=business_challange).distinct() context = { 'areas': product_list, } ajax_template = render_to_string('product-list-ajax.html', context) return JsonResponse({'data': ajax_template}) product-list-ajax.html {% for area in areas %} <div class="border mb-4 pb-4 px-2"> <h2 class="fw-bold my-2">{{area.title}}</h2> {% for need in area.need_area.all %} <h4 class="text-muted mt-4">{{need.title}}:</h4> {% for product_category in need.category_need.all %} {% for product in product_category.product.all %} <a href="{{product.get_absolute_url}}" class="pe-2"><span>{{product.title}}</span></a> {% endfor %} {% endfor %} {% endfor %} </div> {% endfor %} product-filters.js $(document).ready(function(){ $(".ajaxLoader").hide(); $(".form-check-input").on('click', function(){ var filterObj={}; $(".form-check-input").each(function(index,ele){ var filterVal=$(this).val(); var filterKey=$(this).data('filter'); filterObj[filterKey]=Array.from(document.querySelectorAll('input[data-filter='+filterKey+']:checked')).map(function(el){ return el.value; }); }); //Ajax $.ajax({ url: 'filter-data', data: filterObj, dataType: 'json', beofreSend: function(){ $(".ajaxLoader").show(); }, success: function(res){ $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); console.log(res) } }); … -
Python strptime for empty string or None value from database
Getting values from a database table and when the field is empty string or None its giving me this error: time data '' does not match format '%Y-%m-%d %H:%M:%S.%f' first_date = users.work.values_list('work_date', flat=True) a = datetime.datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S.%f') b = a.strftime("%m/%d/%Y") Output: 2022-06-02 11:16:41.012000+00:00 But the output also will be null in table How I can skip this '' or None values, without try except and other huge lines of code, please advice Thanks. -
Count and store Number of logins in Django
I am new to Django framework. I am trying to record number of logins by a particular user(s) and display it in my Django panel. I went through the discussion here https://stackoverflow.com/questions/2526966/count-number-of-logins-by-specific-user-django But could not understand which code is to put in which file i mean what to put in models.py and signals.py or otherwise. Please help. -
Django admin page not work properly and show weird look
Today I have updated Django to the latest version. But for some reason when the logged in to the admin page, all I cans see is a weird-looking admin page. enter image description here how to solve this problem? -
Django form won't submit but not showing error
models.py class HopperFillData(models.Model): no_mesin = models.CharField('No Mesin', max_length=3, choices=mesin_choice, default=mesin_choice[0]) product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Product', default=None) no_lot = models.IntegerField('No Lot', blank=True, null=True) temp = models.IntegerField('Temperature', blank=False, null=False) tanggal = models.DateField('Tanggal', blank=False, null=False) jam_isi = models.TimeField('Jam Isi', blank=False, null=False) target_pemakaian = models.PositiveIntegerField('Usage Total', blank=False, null=False) pemakaian_virgin = models.PositiveIntegerField('Usage Virgin', blank=False, null=False) pemakaian_regrind = models.PositiveIntegerField('Usage Regrind', blank=False, null=False) pic = models.ForeignKey(UserModel, on_delete=models.CASCADE, verbose_name='PIC', to_field='username', blank=True, null=True) shift = models.CharField('Shift', max_length=7) def __str__(self): hop = '{0.no_mesin}' return hop.format(self) def get_absolute_url(self): return reverse('hopper_fill_data') forms.py class HopperFillForm(ModelForm): def __init__(self, *args, **kwargs): super(HopperFillForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column('no_mesin', css_class = 'col-md-2'), Column('product', css_class = 'col-md-7'), Column('no_lot', css_class = 'col-md-1'), Column(AppendedText('temp', '°C'), css_class = 'col-md-2'), css_class = 'row' ), Row( Column(MultiWidgetField('tanggal', attrs = ({'style':'width : 30%; display: inline-block; margin-right:0.15em'},)), css_class='col-md-8'), Column('jam_isi', css_class = 'col-md-4'), css_class = 'row' ), Row( Column(AppendedText('target_pemakaian', 'kg'), css_class = 'col-md-4'), Column(AppendedText('pemakaian_virgin', 'kg'), css_class = 'col-md-4'), Column(AppendedText('pemakaian_regrind', 'kg'), css_class = 'col-md-4'), css_class = 'row' ), Submit('submit', 'Submit Material Hopper') ) self.fields['tanggal'].widget = SelectDateWidget(years = range(2000, date.today().year+3)) self.fields['tanggal'].initial = datetime.today() self.fields['jam_isi'].widget = forms.TimeInput(attrs={'type':'time'}) self.fields['jam_isi'].input_formats = settings.TIME_FORMAT self.fields['jam_isi'].initial = datetime.today().strftime('%H:%M') self.fields['shift'].widget = forms.HiddenInput() self.fields['shift'].initial = 'Shift 1' self.fields['pic'].widget = forms.HiddenInput() self.fields['pic'].initial = None class Meta: model = HopperFillData …