Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Panel not showing on production
I have recently deployed project on linux server. I can't access admin panel by going to my-domain/admin. i can view it when running project locally but on production it says "This site can't be reached" -
Use params for raw sql query
params = ', '.join([str(x) for x in list(user_domain_ids)]) latest_entries = DNSEntryHistory.objects.raw(SELECT t1.* from dnsapi_dnsentryhistory t1 where t1.date= (SELECT MAX(date) FROM dnsapi_dnsentryhistory t2 where t1.id=t2.id) and history_type='delete' and domain_id IN (%s)",[params]) I have a request and i want to send value separated by comma in my IN statement. This request works if the variable is hardcoded with a fstring but i don't want to get this solution because of SQL Injection issues. When I print the query it show -> SELECT t1.* from dnsapi_dnsentryhistory t1 where t1.date= (SELECT MAX(date) FROM dnsapi_dnsentryhistory t2 where t1.id=t2.id) and history_type='delete' and domain_id IN (2544, 1) which seems correct. Also when i use the printed request as the executed one, it works, so i'm so confused -
How to solve blank page after posting the form problem?
I want to send a basic form to views. I create everything that it need but when I submit the post, it doesn't send a return a blank page. This is my form and app:reports is the same page with form, because I want to return the same page. I need the values of year_one and year_two. <form method="post" action="{% url 'app:reports' %}"> {% csrf_token %} <label for="year_one">Select year 1:</label> <select id="year_one" name="year_one"> {% for case in query_trend %} <option value="{{case.date_created__year}}" >{{case.date_created__year}}</option> {% endfor %} </select> <label for="year_two">Select year 2:</label> <select id="year_two" name="year_two"> {% for case in query_trend %} <option value="{{case.date_created__year}}">{{case.date_created__year}}</option> {% endfor %} </select> <button onclick="test()">click</button> </form> And this is my view if self.request.method == 'POST': year_one = self.request.GET.get('year_one') year_two = self.request.GET.get('year_two') return HttpResponseRedirect('fdm:outstanding_reports') What should I do for using these values in views? -
How to properly show .dwg file in Reactjs web application
Currently, I want to render a large .dwg file in the reactjs web application, the .dwg file will be retrieved from my django server. Also, I will be doing some filtering onto the .dwg file to show the coordinate of different IoT devices. After hours of research, I found out there are two ways of showing .dwg file in the reactjs web application. Either using autodesk forge viewer extension in reactjs, however, there are little tutorials on how to implement that step by step. Another solution is to convert .dwg file to .dxf file and render it in the web. I want to know which solution is better, and please point me out if I am wrong about the solutions. I mean I really want to do it with the standard practice. Much appreciated. -
what is the best frontend framework to use with django [closed]
what is the best frontend framework to use with django? -
Django REST API booleanfield filter in view (e.g. filter(is_published=True) )
I will filter is_published=1 in REST API view. I want to receive only published articles. And i using MongoDB database. models.py: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=500, verbose_name="Başlık") content = RichTextUploadingField(max_length=10000) is_publish = models.BooleanField(default=0) created_date = models.DateField(auto_now_add=True, null=True, blank=True, editable=False) . . . view.py (I guess error is here): class PostList(generics.ListAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['content', 'title'] def get_queryset(self): queryset = Post.objects.filter(is_published=True).order_by("-created_date") return queryset serializers.py: from .models import Post from rest_framework import serializers class PostSerializer(serializers.ModelSerializer): class Meta: model = Post exclude = ['author'] my error code: DatabaseError at /post/list/ No exception message supplied -
Django dependant filters using json list variable contained within a foreign key
I have a form the a user can fill in. What I want is a dependant dropdown menu such that when a router (ce_hostname) is selected, the ports (l2_interfaces) for that router are selectable from the second dropdown (ce_wan_port). The list of ports are stored as a json list in the router and the router is stored as a foreign key. models.py #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order #For CE router definition. Required for all orders. class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15, validators=[CE_HOSTNAME_REGEX], verbose_name="CE Hostname", help_text="Hostname of router.") l2_interfaces = JSONField(null=True) #Layer 2 interfaces #For defining WAN links class Ce_Pe(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) #Order reference ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE, verbose_name="CE Hostname", help_text="Hostname of CE router.") ce_wan_port = models.CharField(max_length=500, null=True, blank=True) For the purposes of my dropdown, the ce_wan_port should be a dropdown menu of the l2_interfaces, which appears after a ce_hostname is selected. Example l2_interfaces data [ "Gi0/0/0", "Gi0/0/1", "Gi0/0/2" ] forms.py class Ce_PeForm(ModelForm): class Meta: model = Ce_Pe fields = ['ce_hostname', 'ce_wan_port',] def __init__(self, *args, order_reference, **kwargs): super().__init__(*args, **kwargs) order_id = str(order_reference.id) self.fields['ce_hostname'].queryset = Ce_Base.objects.filter(order_reference=order_id,) This is currently filtering for ce_hostname objects within the same … -
Django Aggregate Min Max Dynamic Ranges
I have following model class Claim: amount = models.PositiveIntegerField() I am trying to create Api that dynamically sends response in such way that amount ranges are dynamic. for example my minimum Claim amount is 100 and max is 1000 i wanted to show json in this way { "100-150":2, "150-250:3, "250-400:1, "400-500":5, "above_500":12 } I tried doing this way assuming my data range is between 1-2000 but this becomes of no use if my minimum amount lies in between 10000, 100000 d = Claim.objects.aggregate(upto_500=Count('pk', filter=Q(amount__lte=500)), above_500__below_1000=Count('pk', filter=Q(amount__range=[501, 999])), above_1000__below_2000=Count('pk', filter=Q(amount__range=[1000, 2000])), above_2000=Count('pk', filter=Q(amount__gte=2000)) ) any idea how we can make dynamic way of getting amount ranges and throwing it to front end. -
How to get a number in html page in humanized format(comma separated and same )
I am running a django project. I want to get some value, that is generated in my JS file, in html page in humanized format. That is if my value is 2678282, it should be presented as 2,678,282. And width for 111,111 and 999,999 should be same. I know {{load humanize}} can be used if we are getting data from views.py file. Like {{data.Value|floatformat:2|intcomma}} But I have value generated in my JS file.. As $("#text-number").text(data.Value) and I am placing it in html in span tag as <span id="text-number"></span> Here how can I get its humanized format? -
How to setting token authentication (Djoser) with AbstractUser
I'm a new learner of REST, and now I want to build a token authentication (Djoser) for my app with AbstractUser for CRUD users based on Djoser, some examples tutorials using AbstractBaseUser, PermissionsMixin, and BaseUserManager instead of AbstractUser, so it advanced with Me ! I want to start with a simples way! Here is my model: class User(AbstractUser): username = models.CharField(max_length=50, unique=True, blank=False) password = models.CharField(max_length=100, blank=False) email = models.EmailField(unique=True, blank=False) phone = models.CharField(max_length=10, unique=True, blank=True, null=True) serializers.py class UserSerializer(serializers.ModelSerializer): apartment = serializers.StringRelatedField( many=True, required=False) class Meta: model = User fields = [ 'id','username','password','email','phone','apartment' ] extra_kwargs = {'password': {'write_only': True}} views.py class UserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = UserSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerUserOrReadOnly] -
Django - How to handle the UNIQUE constraint when import a excel fields
I was did a small project to import file excel and show data it. In models.py How I show errors_message when I import another file excel had same id_student in data. I was try to take the id_student to compare with the data import in but seen like I do it worng. Can some one help me. Thank you -
Crispy forms field_class not applying correctly
I have a Django form in which I use crispy-forms along with bootstrap5. Everything was alright until I wanted to changed the Layout of my form. As my form is constructed dynamically, I just wanted to define the value of a set element item which is under the form (field_name, layout_index). The goal was to define it as a FieldWithButton, as I couldn't find another way to do that. To do that, I modified my helper in the __init__ method of my form : self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")), id=f'div_id_{item[0]}', css_class='mb-3 row') This is rendered nearly correctly in my form, I have the FieldWithButton with Div etc. However, the div which contains my FieldWithButton doesn't take the field_class of my helper that I defined, and instead creates a <divclass='col-10'>...</divclass='col-10'>. There's juste a space which disappeared and messed everything up. How can I either remove the class='col-10' part of my div and put it as its class or differently define my Field as a FieldWithButton ? Here's my whole form class if needed : class ScriptInputForm(forms.Form): def __init__(self, *args, **kwargs): variables = kwargs.pop('variables') # All variables to render variables_names = [*variables] # under the form {'name':['type', 'description']} super().__init__(*args, **kwargs) for var … -
Django url adding twice the request.path to the URL
in Django, if I use {% url 'logout' %}, the path is added twice to the URL. An example of it: if I click logout btn the URL looks like https://server_name/appname/appname/logout/ which does not exist, and actually I want to have https://server_name/appname/logout/ Here are my code. template: <li class="nav-item"> <a class="nav-link btn btn-logout" tabindex="-1" href="{% url 'logout' %}" >Logout</a > </li> url: urlpatterns = [ path('', views.index, name='index-pages'), re_path(r'^login/$', views.login_page, name='login'), re_path(r'^logout/$', views.logout_user, name='logout'), ] main app url: urlpatterns = [ path('', include('pages.urls')), path('dashboards/', include('dashboards.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), re_path('admin/', admin.site.urls), ] but if I change the template to <li class="nav-item"> <a class="nav-link btn btn-logout" tabindex="-1" href="logout" >Logout</a > </li> it is working, however, I have in some other places which I can't change. How can I prevent Django from adding the path to URL? -
Django - problem in workink with annotate
I want write a query for select best users(I have a model with name "LastResult". The best user is the one who have more LastResult object.) best_users = LastResult.objects.filter(answer__accept=True).annotate(solved_count=).order_by("-solved_count", "-time") in solved_count I want get LastResult.objects.filter(answer__accept=True).filter(user=user #I do not know what to write in this part).count() and next I can order objects with solved_count field LastResult Model: class LastResult(models.Model): time = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_send_file', null=True, blank=True) question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='question_a', null=True, blank=True) answer = models.ForeignKey(ProgrammingQuestionAnswer, on_delete=models.CASCADE, related_name='answer_qu', null=True, blank=True) Thanks for any help. Thank you for your prompt reply. It is essential :) -
How to avoid raw SQL query with multiple JOINs?
Is there any way how to make complex SQL selects in Django methods? With multiple JOINs cross multiple tables with different relations. I've tried many attempts with select_related method, but haven't figured out that. Simply - I need ListView for model Objekt filtered by model User. Database looks like this - https://dbdiagram.io/d/61d699903205b45b73d92750/ I think that these kind of queries has to be done much simpler way. Query set for ListView def get_queryset(self): return Objekt.objects.raw('''SELECT portal_objekt.id AS id, portal_objekt.cislo_objektu AS cislo_objektu, portal_objekt.mesto AS objekt_mesto, portal_objekt.ulice AS objekt_ulice, portal_objekt.c_popisne AS objekt_c_popisne, portal_objekt.c_orientacni AS objekt_c_orientacni, portal_objekt.psc AS objekt_psc, CASE WHEN portal_mereni.komodita = 'e' THEN 'elektřina' WHEN portal_mereni.komodita = 'p' THEN 'plyn' WHEN portal_mereni.komodita = 'v' THEN 'voda' WHEN portal_mereni.komodita = 't' THEN 'teplo' ELSE 'ostatní' END AS mereni_komodita FROM portal_objekt INNER JOIN portal_sluzbakesmlouve ON portal_sluzbakesmlouve.objekt_id = portal_objekt.id INNER JOIN portal_smlouva ON portal_sluzbakesmlouve.smlouva_id = portal_smlouva.id INNER JOIN portal_uzivatelkesmlouve ON portal_uzivatelkesmlouve.smlouva_id = portal_smlouva.id INNER JOIN portal_user ON portal_uzivatelkesmlouve.uzivatel_id = portal_user.id INNER JOIN portal_mereni ON portal_mereni.objekt_id = portal_objekt.id WHERE portal_user.email = %s AND portal_sluzbakesmlouve.platnost_od < CURRENT_DATE AND ( portal_sluzbakesmlouve.platnost_do > CURRENT_DATE OR portal_sluzbakesmlouve.platnost_do IS NULL ) ORDER BY portal_objekt.cislo_objektu''', [ self.request.user.email ] ) -
Executing only one row in the loop
I'm trying to execute all the rows in the payload through loop but after executing the first row I'm getting an 'str' object has no attribute 'get' like wise its happening for all the remaining rows in the API. payload: [ 0: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 1, Answer: "2", SID: "0",…} 1: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 2, Answer: "2", SID: "0",…} 2: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 3, Answer: "2", SID: "0",…} 3: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 4, Answer: "2", SID: "0",…} 4: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 5, Answer: "5", SID: "0",…} 5: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 6, Answer: "5", SID: "0",…} 6: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 7, Answer: "3", SID: "0",…} 7: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 8, Answer: "3", SID: "0",…} ] Here, I get the random number such as 8938 for the first row and remaining rows I should get as 0 views.py @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) … -
JavaScript how to set JWT for <img> resource
At my Django application, I want to display an image from an external web server. This web server only returns the image if an authorization token (JWT) is set in the request header. At my Django template, I currently do: <img src="{{ blabla.cover_url }}"> Where cover_url currently is only a string like "https://test.mydomain.com/test/OUINBWU.jpg" As I cannot send a whole HttpResponse object that includes the JWT using Django I need to use Javascript here to instruct my browser to load the <img> with a JWT in the request header. Assuming I have passed a valid JWT and the link to my template, how does the JavaScript code have to look like in order to request the img with the JWT set at the header? Total JS newbie here Thanks in advance -
How to add ID or class with every option in ChoiceField - forms.py Django
currently I make a tuple for options and passed the two arguments value and label like TAG_OPTION = ( ('', 'Choose Tagging'), ("Option A","Option A"), ("Option B","Option B"), ("Option C","Option C"), ("Option D","Option D"), ("Option AB","Option AB"), ("Option BA","Option BA") ) and then passed the TAG_OPTION to the choices of ChoiceField like tagging_type = forms.ChoiceField(choices=TAG_OPTION,widget=forms.Select(attrs={'id':'tagging_type'})) However, what output I want is, <select name="tagging_type" id="tagging_type"> <option value="">Choose Tagging</option> <option id="optA" value="Option A">Option A</option> <option id="optA" value="Option B">Option B</option> <option id="optA" value="Option C">Option C</option> <option id="optA" value="Option D">Option A</option> <option id="optB" value="Option AB">Option AB</option> <option id="optB" value="Option BA">Option BA</option> </select> Can anyone help me out to know the easy way to achieve this ? -
ValueError at /Insert The view CRUDOperation.views.Insertemp didn't return an HttpResponse object. It returned None instead
from django.shortcuts import render from CRUDOperation.models import EmpModel from django.contrib import messages def showemp(request): showall = EmpModel.objects.all() return render(request,'Index.html',{"data":showall}) def Insertemp(request): if request.method == 'POST': if request.POST.get('firstname') and request.POST.get('middlename') and request.POST.get('lastname') and request.POST.get('department') and request.POST.get('designation') and request.POST.get('location') and request.POST.get('salary') and request.POST.get('status') and request.POST.get('gender'): saverecord=EmpModel() saverecord.firstname=request.POST.get('firstname') saverecord.middlename=request.POST.get('middlename') saverecord.lastname=request.POST.get('lastname') saverecord.department=request.POST.get('designation') saverecord.designation=request.POST.get('designation') saverecord.location=request.POST.get('location') saverecord.status=request.POST.get('status') saverecord.salary=request.POST.get('salary') saverecord.gender=request.POST.get('gender') saverecord.save() messages.success(request,'Employee'+saverecord.firstname+'is saved successfully! :)') return render(request,'Insert.html') else: return render(request,'Insert.html') above is the code where the problem MIGHT be there,can someone point out what error is there? what problem could be there in the code? -
django-pgcrypto-fields taking long time to load
I'm using django 2.2.13 and django-pgcrypto-fields 2.5.2. Also i'm using email as authentication method. email is stored as pgcrypto field. There are around 10000 active users. When user tries to login it takes a long time (8-9 seconds). I tried to login from shell, it also takes a long time. from django.contrib.auth import authenticate user = authenticate(email='john@gmail.com', password='secret') The authenticate function takes almost 7-8 seconds to execute. user = authenticate(username='john', password='secret') When I try to authenticate using username, it executes within 1 seconds from app.models import User user = User.objects.filter(email=email).first() The above query also takes a long time to execute (7-8 seconds). How can I speed up authentication and filter queries for pgcrypto fields? -
how to export only filtered data to excel in django
this is my view but in this only return_type = 'time_slot"is working elif return_type= 'export is not working ' my intention is to export excel with filtered data so I came up with this. thanks in advance class TimeSlotReportView(AdminOnlyMixin, generic.DetailView): template_name = 'reports/time_slot_report.html' def get(self, request, *args, **kwargs): if request.is_ajax(): zone_val = request.GET.getlist('zone_val[]') slot_val = request.GET.getlist('slot_val[]') date_val = request.GET.get('date_val') return_type = request.GET.get('return_type') slots = [] if return_type == 'time_slot': for t in slot_val: slots.append(parse(t)) slot_len = len(slot_val) + 1 slot_size = len(slot_val) zones = Zone.objects.filter(id__in=zone_val) daily_tasks = DailyTask.objects.filter(date=date_val, zone__id__in=zone_val, slot__start_time__time__in=slots) total_used = 0 total_unused = 0 total = 0 for task in daily_tasks: total_used += task.used_tasks total_unused += task.unused_tasks total += task.total_tasks # print(total_used, '/', total_unused, '/', total) context = { 'daily_tasks': daily_tasks, 'zones': zones, 'slot_len': slot_len, 'slot_size': range(slot_size), 'task_used': total_used, 'task_unused': total_unused, 'task_all': total } html = render_to_string('reports/time_slot_filter.html', context, request) return JsonResponse({'html': html}) elif return_type == 'export_excel': def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=Timeslot Report' + \ str(datetime.datetime.now()) + '.xls' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Time Slot Report') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Zones', 'Coordinates'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Zone.objects.all().values_list('name', 'coordinates') for … -
Python Django Filter assist for filter[last_login][gte]
I have DjangoFilterBackend for filtering with respective JSON API Specs. Here is my filter class below. The problem with this is it works for /api/user?filter[last_login__gte]=2022-06-24T11:00:00Z How can I modify to make it /api/user?filter[last_login][gte]=2022-06-24T11:00:00Z class UserFilter(django_filters.FilterSet): id = django_filters.CharFilter(field_name="external_id") class Meta: model = User fields = { "id": ["exact", "in"], "email": ["exact", "in"], "first_name": ["exact", "in"], "last_name": ["exact", "in"], "is_active": ["exact"], "last_login": ["isnull", "exact", "lte", "gte", "gt", "lt"], } filter_overrides = { models.DateTimeField: {"filter_class": django_filters.IsoDateTimeFilter} } -
How to merge colms in python dictionary where particular fields are same?
I have list of dictionaries as u can see below: [{ 'name': 'First Filter', 'nut': '122222', 'cpv': '111' }, { 'name': 'First Filter', 'nut': '122222', 'cpv': '123' }, { 'name': 'First Filter', 'nut': '123-41', 'cpv': '111' }, { 'name': 'First Filter', 'nut': '123-41', 'cpv': '123' } ] I want results like this: ''' { 'name': 'First Filter', 'nut': ['122222', '123-41'], 'cpv': ['111', '123'] } ] ''' Please help me, i tried to do this by pandas dataframe but couldn't get it! -
Implementing SAML SSO session expiry on navigating back and forth between our system domains and external domains
My system uses django framework with MongoDB and reactJS. I have implemented SSO with the opensource python toolkit provided by OneLogin (https://pypi.org/project/python3-saml/) Suppose we have a known set of our system domains (www.app1.com, www.app2.com). Am trying to implement session expiry when a user logs in with SSO in either of our known domains and navigates out to an external domain(like youtube etc.). As long as the user switches between our known set of domains the existing session need not be invalidated. I have currently integrated with Azure active directory as the Identity Provider(IDP). When i login with SSO it redirects me to microsoft login and after successful login am redirected back to my backend server where i store the SAML token and redirect back to the frontend application domain. The session data is getting stored under the microsoft domain in the browser and hence i have no access to that session data to clear it from the frontend when the user is navigating out of my domain. And it doens't matter even if i delete the session data stored in my backend server since it is still present in the browser. It just takes that session from browser and sends … -
How to customise the default error message for empty username on login
login credentials : { "account_id":"", "password":"abdu@123" } response : { "account_id": [ "This field may not be blank." ] } This error comes from rest_framework.fields.CharField. I tried to override it by doing : class MyField(CharField): default_error_messages = { 'invalid': _('Not a valid string.'), 'blank': _('This field may not be blank changed......'), 'max_length': _('Ensure this field has no more than {max_length} characters.'), 'min_length': _('Ensure this field has at least {min_length} characters.'), } This doesn't change the error message.