Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 }}" … -
Is it ok to have two or more Django forms in one HTML form?
I know it's possible to have more than one Django form in one HTML form, even formsets, and standard forms combined and it works perfectly fine. I want to know if it is a good practice and how this can impact security if it will at all? I couldn't find any information about those cases but in tutorials, I saw both (multiple Django forms in one HTML and every Django form in a separate HTML form) in some cases is necessary since the two forms can do different things like update and delete for example. In my case, all forms POST data to different models, and then all are combined in one model. Please take a look at the example (This is a simple example and not the actual code) below: <form action="" method="POST"> {% csrf_token %} {{ form.field1 }} {{ form.field2 }} {{ form.field3 }} {% for field in dates_form %} {{ field.Loading_date_from }}{{ field.Loading_time_from }}{{ field.Loading_date_to }}{{ field.Loading_time_to }} {% endfor %} {% for field in dates_form2 %} {{ field.Loading_date_from }}{{ field.Loading_time_from }}{{ field.Loading_date_to }}{{ field.Loading_time_to }} {% endfor %} {{ form.field4 }} {{ form.field5 }} <input type="submit"> </form> -
Why is it industry standard to run JS frameworks like Vue.js and React with conjuction of Node.js? [duplicate]
I have seen number of existing projects: where frontend is served from node.js server. backend server (non node.js) is providing some REST API. Clients communicate with this server the rest of the time. So nodejs is needed just for initial request. I see that frontend nodejs server does not much, but provides some static resources and js dependencies. Having frontend provided by django or even by nginx (if no server side rendering required) seems more simple. It feels like an overkill to have an extra nodejs server in your environment. We don't need to maintain extra node.js server. What am i missing here? What advantage gives this frontend node.js server? -
How do I override a template-tag for the "pinax" application in Django?
Unfortunately for me, the "pinax" application for Django does not seem to have stayed up with the times – in one specific way: the shorttimesince template-tag still refers to the tzinfo object which has been deprecated. The message is this: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'pinax.templatetags.templatetags.shorttimesince_tag': No module named 'django.utils.tzinfo' In my project, I have a overrides/pinax/templatetags directory which contains both __init__.py and shorttimesince_tag.py which contains the updated code. But it does not seem to be referenced. Whereas, the same project contains an overrides/pinax/notifications/backends/email.py which, so far as I know now, is being correctly referenced and which still appears to work. The 'TEMPLATES:DIRS' settings do now contain: os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', 'overrides/pinax'), ... which is what I assume causes the other override to be recognized. But apparently the "templatetag" override is not being seen. -
how to sand list of dict JSON response
i want to sand list of JSON is it possible to sand data like that or i should use serialize-rs dis = [{'name': 'iteam1', 'instock': 12}, {'name': 'iteam2', 'instock': 13}, ] # dis_s= serializers.serialize('json',dis) dis_d = dict(dis) diss = dict(name='iteam0', instock=100) if request.method == 'GET': print(type(dis_d), "successfully called GET") return JsonResponse(dis_d) -
Dynamically using select2 in django formset
I am able to add multiple forms successfully with formset. I am using select2 in the product name part of the form. But as I mentioned below, I manually enter the form ids. $(document).ready(function() { $('#id_store_house_id').select2(); $('#id_product_id').select2(); etc.. }); But it doesn't work because the form id changes dynamically every time I add a new form. I am bad at javascript. I have tried similar threads and solutions on stackoverflow but without success. my form and java script like this : form : <div class="row"> <div class="col-md-6 offset-md-3"> <h3 align="center">Add New Task</h3> <hr> <form id="form-container" method="POST"> {% csrf_token %} {{user_task_form | crispy }} {{ formset.management_form }} {% for form in formset %} <div class="tasksources-form"> {{form | crispy}} </div> {% endfor %} <button id="add-form" class="btn btn-success">+Add More Product</button> <br> <br> <button type="submit" class="btn btn-outline-info">Add New Task</button> </form> </div> </div> my js : <script> let tasksourcesForm = document.querySelectorAll(".tasksources-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = tasksourcesForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = tasksourcesForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } </script> Thanks for your help. I tried this : How do I use Django Dynamic … -
Problem in debugging django project using VS code
I have a problem while debugging a django project using VS code, the problem that nothing happened when I click to debug button, I can launch my script just by tapping in terminal python manage.py runserver. Here is my launch.json file, and note please that I tried a lot of examples, and still the same problem: { "version": "0.2.0", "configurations": [ { "name": "Django", "python": "C:/Users/msekmani/Desktop/dashboard_project/venv/Scripts/python.exe", "type": "python", "request": "launch", "program": "C:/Users/msekmani/Desktop/dashboard_project/IPv2/src/manage.py", "console": "internalConsole", "args": ["runserver"], "django": true, "justMyCode": true, }, ] } I am using python version 3.6 and for the OS is Windows. I hope that someone can help me, Thanks in advance :) -
Why when I try to search for a product, nothing comes up?
I've created an ecommerce website using Django, though the search results aren't coming up when I try to search for a product. For example, when I try to search for part of a product title, like throat spray, nothing comes up even though there is a throat spray in the database. I tried using the Post and Get methods though it didn't really make any difference between the two. I checked to make sure the url for the show_product page works and it does. I'm expecting search results for what I searched for. Though, the search page goes through, nothing comes up as the search results. Instead I get a /search/?searched=throat-spray My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products}) My search.html: <center> {% if searched %} <h1>Search Results for {{ searched }}</h1> <br> {% for product in products %} <a href="{% url 'epharmacyweb/show-product' product.title %}">{{ product }}</a> {% endfor %} </br> {% else %} <h1>You haven't searched anything yet...</h1> {% endif %} </center> My urls.py: path('search/', views.search, name='search'), path('search-error/', views.search_error, name='search_error'), path('show-product/', views.show_product, name='show-product'), My show_product.html: <div class="col"> <div class="card shadow-sm"> <img class="img-fluid" alt="Responsive image" src="{{ product.image.url … -
Django prevent duplication of two foreign keys in one model
I have two foreign key fields that point to the same model. I would like to prevent them from having the same value. Here is my code that does not work class Match(models.Model): team_a = models.ForeignKey(Team, related_name='team_a', on_delete=models.CASCADE) team_b = models.ForeignKey(Team, related_name='team_b', on_delete=models.CASCADE) match_date_time = models.DateTimeField(validators=[validate_matchdate]) winner = models.CharField(choices=CHOICES, max_length=50, blank=True, null=True) def clean(self): direct = Match.objects.filter(team_a = self.team_a, team_b=self.team_b) reverse = Match.objects.filter(team_a = self.team_b, team_b=self.team_a) if direct.exists() & reverse.exists(): raise ValidationError('A team cannot be against itself')