Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
How to save data to user models when using a resume parser in django
I am working on a website whereby users will be uploading resumes and a resume parser script will be run to get skills and save the skills to the profile of the user. I have managed to obtain the skills before saving the form but I cant save the extracted skills now. Anyone who can help with this issue will be highly appreciated. Here is my views file def homepage(request): if request.method == 'POST': # Resume.objects.all().delete() file_form = UploadResumeModelForm(request.POST, request.FILES, instance=request.user.profile) files = request.FILES.getlist('resume') resumes_data = [] if file_form.is_valid(): for file in files: try: # saving the file # resume = Profile(resume=file) resume = file_form.cleaned_data['resume'] # resume.save() # resume = profile_form.cleaned_data['resume'] # print(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) parser = ResumeParser(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) data = parser.get_extracted_data() resumes_data.append(data) resume.name = data.get('name') resume.email = data.get('email') resume.mobile_number = data.get('mobile_number') if data.get('degree') is not None: resume.education = ', '.join(data.get('degree')) else: resume.education = None resume.company_names = data.get('company_names') resume.college_name = data.get('college_name') resume.designation = data.get('designation') resume.total_experience = data.get('total_experience') if data.get('skills') is not None: resume.skills = ', '.join(data.get('skills')) else: resume.skills = None if data.get('experience') is not None: resume.experience = ', '.join(data.get('experience')) else: resume.experience = None # import … -
Problem loading large amount of geoJSON data to Leaflet map
I have geoJSON with more than 5000 objects containing various coordinates, but when they are displayed on the sitemap, the page either crashes or loads the objects for a very long time, but further interaction with the site is impossible. In index.html I have the following code: var mapOptions = { center: [14, 30], zoom: 7 } var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); map.addLayer(layer); var dataurl = '/locdata/'; fetch(dataurl) .then(function (resp) { return resp.json(); }) .then(function (data) { new L.GeoJSON(data, { onEachFeature: function (feature, layer) { layer.bindPopup(feature.properties.name); } }).addTo(map); The code for packing class objects into a JSON file contained in /locdata/ def loc_datasets(request): locations = serialize('geojson', Location.objects.all()) return HttpResponse(locations, content_type='json') The JSON looks like this: {"type": "GeometryCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"name": "00", "lon": 28.676971529668783, "lat": 60.02057178521224, "pk": "133811"}, "geometry": {"type": "Point", "coordinates": [28.676971529668783, 60.02057178521224]}}, {"type": "Feature", "properties": {"name": "41", "lon": 28.844832766965556, "lat": 60.02863347426495, "pk": "142975"}, "geometry": {"type": "Point", "coordinates": [28.844832766965556, 60.02863347426495]}}]} What is the reason that the coordinates cannot be displayed correctly on the Leaflet map on the user page? I'm working on Django, in which the data is displayed correctly in the admin panel. Thanks in … -
Using a React Template with Django (and React)
I am wondering how (or if it is even possible) to use a react template like this one: https://www.creative-tim.com/product/black-dashboard-react with an existing Django app. I have an app setup within a project like this ---project ---migrate.py ---project ---api (django app backend) ---models.py ---urls.py ---views.py ---..... ---frontend (react app) ---here Django a django app along with package.json, babel.config.json, webpack.config.js, and templates, static and src folders. I am wondering how I would integrate a template like the one linked above into this Django app. I am very new to React, I apologize if the question is explained poorly. I have tried replacing my folders and package.json files with the folders and files downloaded with the template. I couldn't get it to work properly. -
Start listening to kafka in a parallel stream when starting a django project
I want to run a file that listens to kafka in a parallel stream with a django project. My manage.py file import asyncio import os import sys import multiprocessing as mt from kafka.run_kafka import run_kafka def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() My run_kafka.py file uses Confluent Kafka Python import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') django.setup() import asyncio from business_logic.settings import KAFKA_CONF, TOPIC_PROD from kafka.kafka_consuners import KafkaConsumerBL async def run_kafka(): """ Запуск прослушивания Kafka на всех топиках на все ответы """ consumer = KafkaConsumerBL(KAFKA_CONF) consumer.indicate_topic([TOPIC_PROD]) await consumer.run_consumer(consumer) if __name__ == '__main__': asyncio.run(run_kafka()) I tried to solve the problem using the threading and multiprocessing libraries. After using any of the libraries, either the django project or kafka is launched. When using the multiprocessing library, one process is started, but not both manage.py ... if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() … -
Django filter query using future date-time
How do I filter a query to contain only the objects that have a date-time field that holds a DateTime in the future? Here is my code that is not working: def matches(request): matches= Match.objects.all().filter(match_date_time > timezone.now() ) context = {'matches': matches} return render(request, 'bookie/matches.html', context) match_date_time is a model field in the Match model but I get an error that it's not defined. -
How can i import custom icons in leaflet Django webapp?
I am unable to import custom icons in my leaflet javascript file (Django webapp) var myicon=L.icon({ iconUrl:Url("icons/dead.svg"), iconSize:[30,40] }); I am trying this method but still unable to import..Any solution??? Please!!!