Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to decrypt encrypted <path:pk> and pass it to functions at generics.RetrieveUpdateDestroyAPIView - Django
I want to pass encrypted ids of object in Response, therefore I used AES. now I want accept the encrypted pk which is a path 'xx/xxxx/xxxx', and decrypt it first thing in the view. ` import base64, re from Crypto.Cipher import AES from Crypto import Random from django.conf import settings import codecs # make utf8mb4 recognizable. codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None) class AESCipher: def __init__(self, key, blk_sz): self.key = key self.blk_sz = blk_sz def encrypt( self, raw ): # raw is the main value if raw is None or len(raw) == 0: raise NameError("No value given to encrypt") raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz) raw = raw.encode('utf8mb4') # Initialization vector to avoid same encrypt for same strings. iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf8mb4') def decrypt( self, enc ): # enc is the encrypted value if enc is None or len(enc) == 0: raise NameError("No value given to decrypt") enc = base64.b64decode(enc) iv = enc[:16] # AES.MODE_CFB that allows bigger length or latin values cipher = AES.new(self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf8mb4') ` I tried … -
Django - How to Use same view function for multiple different URL Endpoints, but different "parameter" sent?
I'm fairly new to Django and here's my case. If i have 3 endpoints that i can't modify, and i need to point them to one same View function such as : urls.py urlpatterns = [ ... url(r'^a/', views.functionz.as_view(), name='a'), url(r'^b/', views.functionz.as_view(), name='b'), url(r'^c/', views.functionz.as_view(), name='c'), ... ] If I'm restricted from changing the endpoints a/, b/, and c/ to something else that accepts parameters like xyz/a or xyz/b, how can my view function functionz identify the difference between them when it is being called? Can I do something like this pseudocode? views.py Class XYZ(API View): def post(self, request, format=None): if request.endpoint == '/a/': # do things if and only if the client hits /a/ -
django | Celery Async Task Result Pagination
I use celery and redis as backend for my async tasks. I like to paginate my results in the template. I use Javascript (ajax Requests) to request the data. Now I like to paginate the results also with Javascript after request the data. I hope someone can help me. Thats my javascript: $(document).ready(() => { console.log('Sanity Check!'); }); $('.button').on('click', function() { $.ajax({ url: '/tasks/', data: { type: $(this).data('type'),}, method: 'POST', }) .done((res) => { getStatus(res.task_id); getStatusConfluence(res.task_id_confluence); }) .fail((err) => { console.log(err); }); }); function getStatus(taskID) { $.ajax({ url: `/tasks/${taskID}/`, method: 'GET' }) .done((res) => { num_hosts = res.value.length for (i=0; i < num_hosts; i++){ const html = ` <tr> <td>${res.value[i]['name']}</td> <td>${res.value[i]['OK']}</td> <td>${res.value[i]['WARN']}</td> <td>${res.value[i]['CRIT']}</td> </tr> ` $('#result').prepend(html); } const taskStatus = res.task_status; if (taskStatus === 'SUCCESS' || taskStatus === 'FAILURE') return false; setTimeout(function() { getStatus(res.task_id); }, 1000); }) .fail((err) => { console.log(err) }); } function getStatusConfluence(taskID) { $.ajax({ url: `/tasks/${taskID}/`, method: 'GET' }) .done((res) => { num_hosts = res.value.length for (i=0; i < num_hosts; i++){ const html = ` <tr> <td>${res.value[i]['title']}</td> </tr> ` $('#result_confluence').prepend(html); } }) .fail((err) => { console.log(err) }); } -
auto fill a field in model via function django
I was searching to find a way to fill a field of a model via a function. example : def myfunction(): return a_file class SomeModel(models.Model): a_field_name=models.FileField(value=my_function()) I some how was thinking to rewrite the create().share with me your idea -
How to catch an element from a for loop in Django template?
I'm looping through to different categories and rendering results (of its name and its associated pages). This code is rendering correctly. {% for category in categories %} <div class="row"> <div class="col-lg-4"> <h3><a href="{{category.get_absolute_url}}"></a>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p><a href="{{page.get_absolute_url}}">{{page.page_title}}</p> {% endfor %} </div> </div> {% endfor %} I'd like to catch an specific element inside the for loop (to be precise the 4th one in the forloop counter) and customize it (adding some html and text only to that one). I tried using the forloop.counter like this: {% if forloop.counter == 4 %} <!-- modified content --> {% endif %} But there isn't any results (not showing any changes). Is there any way to do this? -
Nginx shows requests to endpoints, not in my API, And unknown requests
Nginx works in Docker compose with Django, react, postgress containers Nginx shows requests for PHP, testPHP endpoints with status code 200 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /phpMyAdmin5.2/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /2phpmyadmin/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /wp-content/plugins/portable-phpmyadmin/wp-pma-mod/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:21 +0000] "GET /phpmyadmin4/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /mysql/sqlmanager/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /phpmyadmin2016/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /db/myadmin/index.php?lang=en HTTP/1.1" 200 557 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-" 1.171.112.23 - - [27/Nov/2022:09:37:22 +0000] "GET /sql/websql/index.php?lang=en HTTP/1.1" 200 557 "-" … -
django channels deploying with daphne error Requested setting INSTALLED_APPS, but settings are not configured
Hello I'm following this tutorial https://github.com/mitchtabian/HOWTO-django-channels-daphne to deploy mn django channels app and I'm having problem with starting the daphne. I created the daphne.service so far ; [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django/Petsly/src ExecStart=/home/django/CodingWithMitchChat/venv/bin/python /home/django/CodingWithMitchChat/venv/bin/daphne -b 0.0.0.0 -p 8001 newo.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target after starting the daphne with systemctl start daphne.service , the status of daphne first shows me no error and active after a second it shows this error: ● daphne.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2022-11-28 07:20:24 UTC; 2s ago Process: 122863 ExecStart=/home/django/Petsly/venv/bin/python /home/django/Petsly/venv/bin/daphne -b 0.0.0.0 -p 8001 > Main PID: 122863 (code=exited, status=1/FAILURE) Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Main process exited, code=exited, status=1/FAILURE Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Stopped WebSocket Daphne Service. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Start request repeated too quickly. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'. Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Failed to start WebSocket Daphne Service. and sudo journalctl -u daphne.service v 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]: File "/usr/lib/python3.8/importlib/__init__.py", line … -
Django modelformset_factory: how to create field with constant value
Say I have a bakery which bakes 10 pies in a batch (i.e. all 10 pies go into the same oven). The objective is simply to record the weight (in grams) and cost of each pie (in $). Cost = weight * 0.01. So each pie is modelled as a PieRecord object, which has weight and cost: models.py from django.db import models class PieRecord(models.Model): """this will be in a modelformset """ # pie_name is a dummy field just to play with text input pie_name = models.CharField(max_length=20) pie_weight_grams = models.FloatField() # calculated: cost($) = pie_weight_grams * 0.01 cost = models.FloatField(default=0.0) I use modelformset_factory to generate 10 PieRecord forms at a shot, and surface on the web page (see views.py below). My question is: I would like to attach some fields that are specific to each batch of 10 pies (not each pie), e.g.: cook time (minutes, FloatField) cook name (CharField) cook date (DateField) cook temperature (degC, FloatField) If I simply add these fields to my PieRecord class, this would result in the user having to enter the same values 10 times (e.g. cook_name James baked this batch of 10 pies), which results in a lot more data entry than is needed; … -
How to implement tooltip with django form
I have a model form based on this model: class MyModel(TimeStampedModel): MY_CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = models.IntegerField("P1”, default='1', help_text=‘text1’) p2 = models.IntegerField(“P2”, default=‘1’, , help_text=‘text2’) Parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE) The form itself looks like: class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-CaseForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_tag = False self.helper.help_text_inline = False self.helper.form_show_labels = False self.helper.layout = Layout( Row(Field(PrependedText('p1', ‘field_label1’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend'))), Row(Field(PrependedText('p2’, ‘field_label2’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend’)))) CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = IntegerField( label='field_label1', widget=Select(choices=CHOICES)) p2 = IntegerField( label='field_label2’, widget=Select(choices=CHOICES)) class Meta: model = MyModel fields = ['p1', 'p2’,] And this is displayed as a crispy form in the template: {% crispy panss_form %} I want the user to see some help text when they hover over the fields. This help text could be the help_text from the model, or I am happy to put it somewhere else (although it should go in either the model or the form, not in the template). Any help appreciated. -
How to paginate in django for filtered datas
views.py import datetime from .filters import MyModelFilter from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.db.models import Q from django.utils import timezone import pytz from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger users = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) get_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date)) print(get_records_by_date) filtered_dates = MyModelFilter(request.GET,queryset=get_records_by_date) page = request.GET.get('page', 1) paginator = Paginator(filtered_dates.qs, 5) global users try: users = paginator.get_page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) else: roles = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(roles, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html", {"users": users}) return render(request, "home.html", {"users": users}) filters.py: import django_filters from.models import Scrapper class MyModelFilter(django_filters.FilterSet): class Meta: model = Scrapper # Declare all your model fields by which you will filter # your queryset here: fields = ['start_time', 'end_time'] home.html <!DOCTYPE html> <html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> … -
Django - Display the number of users currently watching a live stream
I'm developing a Django site for a sports streaming service. It is necessary to display the number of users who are currently watching the broadcast. You can watch the broadcast only after authorization. What is the best way to implement this? At the moment I think that the best solution would be to send a js request to the Django server, but I think there is a better way. -
When i use latest version of drf-yasg to doing api documentation but it is not working
enter image description here but I have seen GitHub repository of Drf-Yasg , there is this package enter image description here I have done QuickStart that in its docs . -
I want to create pagination in django
**This is my view.py coding. it was working but when I add pagination then show some error ** def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') paginator=Paginator(categoryid,4) page=request.GET.get('page') try: all_category.paginator.page(page) except PageNotAnInteger: all_category=paginator.page(1) except EmptyPage: all_category=paginator.page(paginator.num_pages) else: all_category = Product.get_all_products() if categoryid: all_products = categoryid.get_all_products_by_id(categoryid) data = {} data['products'] = all_products data['category'] = all_category all_location = location.get_all_location() all_products = Product.get_all_products() all_team = teams.get_all_team_members() data['product'] = all_products data['location'] = all_location data['teams'] = all_team return render(request, 'car.html', data, {'all_category':all_category, 'categoryid':categoryid, 'category':category(), 'page':page}) **This is my pagination.html file ** <div class=""> <span class=""> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class=""> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div> This is my car.html file. <div class="container-fluid py-1 justify-content-between p-2 m-2"> <div class="container"> <h6 class="display-4 text-uppercase text-center mb-5" style="font-size: 40px">Filters</h6> {% for category in category %} <a href="{% url 'car' %}?category={{ category.id }}"> <button type="button" class="btn btn-outline-secondary rounded">{{ category.name }}</button> </a> {% endfor %}<hr> <h1>{% include 'pagination.html' with page=all_category %}</h1> </div> </div> Actually I want to display all cars data by pagination same all cars categories by patination. I am following this … -
How to create a customized printout report (like crystal reports)? I'm using Django and MYSQL
I'm new to django and python. I'm trying to create a Daily Time Record printout. I'm using Django and Mysql as my database. How to create a report? Is there a designer tool like Crystal reports? enter image description here The output should be like the image shown. -
how can i stop to run path with same parameter on continue path
here i send my details how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this i need help to solve this problem views.py def s_index(request): current_url = request.build_absolute_uri() #print(current_url) src = request.POST.get('txt_search') #if request.POST['btn_clear']: # return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page if request.POST['btn_search']: rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q if rec.exists(): rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values() grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city') template=loader.get_template('index.html') output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op')) context ={ 'rec':rec, 'output':output['acc_op__sum'], 'grp_city':grp_city, } return HttpResponse(template.render(context,request)) else : return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page urls.py from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('addacc/',views.add,name='addacc'), path('addacc/addrecord/',views.addrecord,name='addrecord') , path('delete/<int:id>',views.delete,name='delete') , path('update/<int:id>',views.update,name='update'), path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'), path('index/',views.s_index,name='s_index'), #path('',views.form_view,name='mform') ] index.html {% load static %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function printreport(){ //var divtoprint=document.getElementById("maindiv"); var printcontext=document.getElementById("maindiv").innerHTML; var originalcontext=document.body.innerHTML; var nwin=window.open(""); nwin.document.open(); nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>'); nwin.document.write(printcontext); nwin.document.write("</body></html>"); //document.write(printcontext); //document.body.innerHTML=printcontext; //printWindow.document.write(divtoprint); nwin.print(); nwin.document.close(); nwin.close(); } </script> <link rel="stylesheet" href="{% static 'mystyle.css' %}" > <link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for … -
I have written a django querry but need specific user information of particular date
Modles: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1,related_name='Employee') eid = models.IntegerField(primary_key=True) salary = models.IntegerField(null=True, blank=True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) contactno = models.CharField(max_length=10, blank=False) email = models.CharField(max_length=50 ,null=True, blank=True) country = models.CharField(max_length=30) address = models.CharField(max_length=60) def __str__(self): return self.user.first_name + '_' + self.user.last_name class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1,related_name='Attendance') attendance_date = models.DateField(null=True) in_time = models.TimeField(null=True) out_time = models.TimeField(null=True ,blank=True) description = models.TextField(null=True, blank=True) def __str__(self): return str(self.employee) + '-' + str(self.attendance_date) class Breaks(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) break_in = models.TimeField(null=True, blank=True) break_out = models.TimeField(null=True, blank=True) attendance =models.ForeignKey(Attendance, on_delete=models.CASCADE, default=1,related_name='Breaks') def __str__(self): return str(self.employee) + '-' + str(self.break_in) + '-' + str(self.break_out) def detail_attendance(request): attendance_list = Attendance.objects.filter(employee__user_id=request.user.id) counter = Counter() return render(request, 'employee/detail_attendance.html', {'attendance_list': attendance_list, 'counter': counter}) def detail_break(request): break_list=Breaks.objects.filter(employee__user_id=request.user.id ) return render(request, 'employee/detail_break.html', {'break_list': break_list}) Hi Team as I have created a function above for detail breaks . I am getting specific user data but it is giving me the previous data as well . so I need the data for specific data for example in my attendance models I adding attendance of each user . Please let me know what should I change in detail break. -
Display option value and text to select
I have a select field populated from the database table 'Grade'. It displays Grade objects instead of 'Grade 1', 'Grade 2', 'Grade 3' etc. How can I populate the select to display the texts. My codes: models.py class Grade(models.Model): grade_id = models.AutoField(primary_key=True) grade_name = models.CharField(max_length=10, default="") class Meta: db_table = 'grade' class Student(models.Model): student_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50, default="") last_name = models.CharField(max_length=50, default="") grade = models.ForeignKey(Grade, on_delete=models.CASCADE) class Meta: db_table = 'Student' forms.py class CreateStudentForm(forms.ModelForm): class Meta: model = Student fields = ['grade', 'first_name', 'last_name' ] widgets = { 'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}), } views.py def student_action(request): form = CreateStudentForm() return render(request, 'student.html', {'form': form}) -
Enviroment Variables are not loading into Pytest with ini file
For context, if I run pytest --ds="monolith.settings" or DJANGO_SETTINGS_MODULE="monolith.settings" pytest I see the expected behavior but currently I have a pytest.ini (see below) which I run as pytest -c pytest.ini which throws: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've been trawling through different solutions such as using toml format, using envs, have followed the pytest-django instructions, and just about everything else I've found with no luck. This is the envs that exist at runtime: {'NVM_INC': '/Users/me/.nvm/versions/node/v16.13.0/include/node', 'rvm_use_flag': '', 'TERM_PROGRAM': 'iTerm.app', 'rvm_bin_path': '/Users/me/.rvm/bin', 'rvm_quiet_flag': '', 'NVM_CD_FLAGS': '-q', 'GEM_HOME': '/Users/me/.rvm/gems/ruby-3.0.1', 'TERM': 'xterm-256color', 'ASDF_DIR': '/Users/me/.asdf', 'rvm_gemstone_url': '', 'SHELL': '/usr/local/bin/zsh', 'MAKEFLAGS': '', 'TMPDIR': '/var/folders/7g/jdt1bt6n5zq7lykytwwqfdwc0000gn/T/', 'IRBRC': '/Users/me/.rvm/rubies/ruby-3.0.1/.irbrc', 'rvm_docs_type': '', 'TERM_PROGRAM_VERSION': '3.4.12', 'MY_RUBY_HOME': '/Users/me/.rvm/rubies/ruby-3.0.1', 'rvm_hook': '', 'TERM_SESSION_ID': 'w0t0p0:BD1C0A6B-9412-4E13-819C-D802B176C6EF', 'NVM_DIR': '/Users/me/.nvm', 'USER': 'me', 'rvm_gemstone_package_file': '', 'COMMAND_MODE': 'unix2003', 'rvm_path': '/Users/me/.rvm', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.BcOmvUyUOZ/Listeners', '__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0', 'MAKELEVEL': '1', 'rvm_proxy': '', 'VIRTUAL_ENV': '/Users/me/Library/Caches/pypoetry/virtualenvs/mono-RSwW7_xp-py3.10', 'rvm_ruby_file': '', 'MFLAGS': '', 'rvm_prefix': '/Users/me', 'rvm_silent_flag': '', 'PATH': '/Users/me/Library/Caches/pypoetry/virtualenvs/mono-RSwW7_xp-py3.10/bin:/Users/me/.rvm/gems/ruby-3.0.1/bin:/Users/me/.rvm/gems/ruby-3.0.1@global/bin:/Users/me/.rvm/rubies/ruby-3.0.1/bin:/Users/me/.nvm/versions/node/v16.13.0/bin:/Users/me/.pyenv/shims:/Users/me/.local/bin:/Users/me/.asdf/shims:/Users/me/.asdf/bin:/Users/me/.yarn/bin:/Users/me/.config/yarn/global/node_modules/.bin:/Users/me/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin:/Users/me/.rvm/bin', 'rvm_ruby_make': '', '__CFBundleIdentifier': 'com.googlecode.iterm2', 'PWD': '/Users/me/code/labs/mono/services/core', 'POETRY_ACTIVE': '1', 'LANG': 'en_US.UTF-8', 'rvm_sdk': '', 'ITERM_PROFILE': 'me', 'XPC_FLAGS': '0x0', 'PS1': '(mono-py3.10) \\s-\\v\\$ ', 'XPC_SERVICE_NAME': '0', 'rvm_version': '1.29.12-next (master)', 'COLORFGBG': '7;0', 'rvm_script_name': '', 'SHLVL': '3', 'PYENV_SHELL': 'zsh', 'HOME': '/Users/me', 'rvm_pretty_print_flag': '', 'rvm_ruby_mode': '', 'LC_TERMINAL_VERSION': '3.4.12', … -
how to upload image correctly. Django
I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems. In my models.py: FuncionarioPathFoto = models.FileField( "Foto", upload_to = "images/", db_column= "FuncionarioPathFoto", null= False, blank = False ) In my views (I'm using inline forms, so the code is big): def create_funcionario(request): if request.method == "GET": form = FuncionariosForm form_funcionarioadicional_factory = inlineformset_factory(Funcionarios, FuncionarioAdicional, form=FuncionarioAdicionalForm, extra=1) form_funcionarioaux_factory = inlineformset_factory(Funcionarios, FuncionarioAux, form=FuncionarioAuxForm, extra=1) form_funcionarioarquivo_factory = inlineformset_factory(Funcionarios, FuncionarioArquivo, form=FuncionarioArquivoForm, extra=1) form_funcionarioadicional = form_funcionarioadicional_factory() form_funcionarioaux = form_funcionarioaux_factory() form_funcionarioarquivo = form_funcionarioarquivo_factory() context = { 'form': form, 'form_funcionarioadicional': form_funcionarioadicional, 'form_funcionarioaux': form_funcionarioaux, 'form_funcionarioarquivo': form_funcionarioarquivo, } return render(request, '../templates/funcionarios/form_funcionarios.html', context) elif request.method == "POST": form = FuncionariosForm(request.POST) form_funcionarioadicional_factory = inlineformset_factory(Funcionarios, FuncionarioAdicional, form=FuncionarioAdicionalForm) form_funcionarioaux_factory = inlineformset_factory(Funcionarios, FuncionarioAux, form=FuncionarioAuxForm) form_funcionarioarquivo_factory = inlineformset_factory(Funcionarios, FuncionarioArquivo, form=FuncionarioArquivoForm) form_funcionarioadicional = form_funcionarioadicional_factory(request.POST) form_funcionarioaux = form_funcionarioaux_factory(request.POST) form_funcionarioarquivo = form_funcionarioarquivo_factory(request.POST) if form.is_valid() and form_funcionarioadicional.is_valid() and form_funcionarioaux.is_valid() and form_funcionarioarquivo.is_valid(): funcionario = form.save() form_funcionarioadicional.instance = funcionario form_funcionarioaux.instance = funcionario form_funcionarioarquivo.instance = funcionario form_funcionarioadicional.save() form_funcionarioaux.save() form_funcionarioarquivo.save() messages.success(request, "Funcionário adicionado com sucesso!") return redirect(reverse('lista_funcionarios')) else: context = { 'form': form, 'form_funcionarioadicional': form_funcionarioadicional, 'form_funcionarioaux': form_funcionarioaux, 'form_funcionarioarquivo': form_funcionarioarquivo, } return render(request, '../templates/funcionarios/form_funcionarios.html', context) I put this … -
How to hide a field from a serializer in Django rest framework
I want to show only some specific fields in response, showing similar products or related products in the category while am in a product detail page. Eg: If am viewing a single product detail page and in the bottom of page the related products list must be also show there. So while in response of related products, I don;t want extra_images field that is in product serilaizer. #Serializer.py class ProductSerializer(ModelSerializer): product_offer_discount = SerializerMethodField() category_offer_discount = SerializerMethodField() highest_offer_price = SerializerMethodField() extra_images = ProductImages() class Meta: model = Products fields = [ "id", "product_name", "slug", "highest_offer_price", "category_offer_discount", "product_offer_discount", "base_price", "stock", "is_available", "images", "extra_images" ] def to_representation(self, instance): rep =super().to_representation(instance) rep['extra_images'] = ProductImageSerializer(instance.extra_images, many=True).data return rep class RelatedProductSerializer(ModelSerializer): class Meta: model = Products fields = ['product_name', 'slug', 'base_price', 'images'] class ProductDetailserializer(ModelSerializer): product_offer_discount = SerializerMethodField() category_offer_discount = SerializerMethodField() highest_offer_price = SerializerMethodField() description = ProductDescription() extra_images = SerializerMethodField() related_products = SerializerMethodField() class Meta: model = Products fields = [ "id", "product_name", "slug", "highest_offer_price", "category_offer_discount", "product_offer_discount", "description", "base_price", "stock", "is_available", "images", "extra_images", "related_products" ] def to_representation(self, instance): print('INSTANCE', instance) rep = super().to_representation(instance) rep['description'] = ProductDescriptionSerializer(instance.description, many=True).data return rep def get_related_products(self, obj): products= Products.objects.filter(category=obj.category).exclude(id=obj.id) return RelatedProductSerializer(products, many=True, context=self.context).data def get_extra_images(self, obj): images = obj.extra_images.all() return ProductImageSerializer(images, many=True, … -
Django profiles for multiple user types
I am new to Django. My application has three user types who are mutually exclusive.They can be identified using a choice field. Want to understand how to create different user profiles for different user types as each profile will have different properties. Let's say the user types are customer, employee and partner.After googling so many days, Only way I found was to inherit User/Abstract User model and have three different apps for each user type. That's there are will be login page, register page like wise for each user type. I thought I could at least have one app to handle user login and based on the user type from the choice field, to attached the correct user profile. Is this something that can be done. Second I want to provide the correct profile to the user when registering. Is this possible. Thank you in advance. I stated before I tried to have three apps. -
Sending data from Python to HTML in Django
I have a Django project with a form in an HTML file, and I'd like to update the text on the submit button of that form WITHOUT a page reload. Essentially: I click submit on the form Python handles the submit with the form data The button text is updated to say "show result" If I understand correctly, I have to use AJAX for this. The problem is that the form submit relies on an API call in Python, so the HTML essentially has to always be "listening" for new data broadcasted by the views.py file. Here's the code I have (which doesn't work): views.py: def home(request): if request.method == "POST": print("Got form type", request.content_type) return JsonResponse({"text": "show result"}) return render(request, 'home.html') home.html: (form code) <button id="submit" type="submit">Submit</button> (end form) <script type="text/javascript"> function queryData() { $.ajax({ url: "/", type: "POST", data: { name: "text", 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(data) { var text = data['text']; var button = document.getElementById('submit'); button.innerHTML = text; setTimeout(function(){queryData();}, 1000); } }); } $document.ready(function() { queryData(); }); </script> I've imported jQuery with the script <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>. Any idea why this doesn't work in its current state? Thanks! -
Debug the React part of a hybrid React+Webpack+Django in VS Code
I have a hybrid Django + React application: the React frontend is built using Webpack, added to the static files and included in a Django template page (this is based on this tutorial Modern Javascript for Django Developers). Is there a way of easily debugging the React/JavaScript part of the app in VS Code? This question seems close but the breakpoints stay unbound for me despite including the line from its answer. My entry point for React is in ./assets/app.js and the bundled file goes to ./static/js/js-bundle.js. Django serves the website on localhost:8000. webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { mode: 'development', devtool: 'inline-source-map', entry: './assets/app.js', // path to our input file output: { filename: 'js/js-bundle.js', // output bundle file name path: path.resolve(__dirname, 'static'), // path to our Django static directory }, plugins: [ new HtmlWebpackPlugin({ inject: true, filename: path.resolve(__dirname, 'templates', 'app.html'), template: path.resolve(__dirname, 'templates', 'app-template.html'), }), new MiniCssExtractPlugin({ filename: "./css/[name].css", // change this RELATIVE to your output.path! }), ], module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"] } }, { test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }, ] } }; package.json [...] … -
How to iterate through images in a folder from html file with django
These are the images I want to access where the numbers of folder's names are ids 📂 img 📂 1 📄 image1.png 📄 image2.png 📂 2 📄 image2.png 📄 image4.png In views.py I send the img path to the html with this code images_path = os.path.join(STATIC_URL, 'webapp', 'img') # code return render(request, 'webapp/index.html', { 'services': services, 'images_path': images_path }) Then in index.html I have this # code {% for service in services %} # code <div id="imagesCarousel" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> # here I want to access to every image and show it in the carousel </div> </div> {% endfor %} Basically I want to do something like {% for image in os.listdir(os.path.join(images_path, service.id)) %} How can I achieve that? I tried the above code but obviously it doesn't worked -
Error: Cannot read properties of null reading "checked"
Im having trouble fully wiring on my django applications submit button, it seems that the JS function does not understand which checked boxes to look for all the console returns is "cannot read properties of null, reading "checked" Im assuming its something with the function defining but I cannot seem to get it working Heres the code: <html> <head> {% load static%} {% block content%} <link rel="shortcut icon" type="image/png" href="{% static 'IMG/favicon.ico' %}"/> <link rel="stylesheet" href="{% static 'CSS/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'CSS/jquery-ui.css' %}"> <script type="text/javascript" src="{% static 'JS/bootstrap.min.js' %}"></script> <title>Task List</title> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="{% static 'JS/jquery-ui.min.js' %}"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> let _csrf = '{{csrf_token}}'; function submit_delete() { var listItems = $("#list li input"); var checkedListItems = []; listItems.each(function() { if (document.getElementById(this.id).checked) { checkedListItems.push(getTaskId(this.id)); console.log(checkedListItems); } }) $.ajax({ headers: { "X-CSRFToken": _csrf }, type: "POST", url: "/ptm/item_delete", data: { 'deleteList[]': checkedListItems } }).done(location.reload()); } function getTaskId(str) { return str.split('-')[1]; } </script> </head> <body> <div id="logo" class="border-success border border-3 rounded-2" style="width: 61.rem;"> <div class="card-body"> <img class="card-img" src="{% static '/IMG/Logo.png' %}"> </div> </div> <div id="taskList" class="card"> {% if task_list %} <ul class="list-group" id="list"> {% for item in task_list %} <li class="list-group-item" id='tdList'> <input id="check-{{ item.id }}" …