Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: best way to write product characteristics in models if there are more than one categories
I am new django developer. I was trying to make ecommerce website. All things was going alright, but when I started coding product-details, I faced a problem with adding characteristics of product. So, how can I get characteristics if there are more than one category. I tried just adding textField and print it as a characteristics. But, it's not getting as a list and it is just printing as a text. models.py class Product(models.Model): name = models.CharField(max_length=200, verbose_name="Название продукта") category = models.CharField(max_length=300, choices=TOTAL, verbose_name="Категория") subcategory = models.CharField(max_length=300, choices=SUBPRODUCT) price = models.FloatField(verbose_name="Цена") description = models.TextField(max_length=5000,blank=True, verbose_name="Описание:") image = models.ImageField(null=True, blank=True, verbose_name="Изображение") novinki = models.BooleanField(default=False, verbose_name="Новинки") popularnye = models.BooleanField(default=False, verbose_name="Популарные") def __str__(self): return self.name class Meta: verbose_name = 'Продукты' verbose_name_plural = "Продукты" @property def imageURL(self): try: url = self.image.url except: url = '' return url templates <div class="u-product-control u-product-desc u-text u-text-default u-text-2"><!--product_content_content--> <p>{{product.description}}.</p><!--/product_content_content--> </div><!--/product_content--><!--product_button-- So, what can I do? What do you recommend me to do? Please help? I can not solve this problem for a week So, Can you tell me ways to do that? Please, help? -
Django Jquery Autofill data from models
i want make autofill form like this : http://www.tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Overridding_Default_Select_Action.php what i already know is to get list of cities form models : views.py def autofill(request): if 'term' in request.GET: qs = Citi.objects.filter(cities__icontains=request.GET.get('term')) citys = list() citys = [city.cities for city in qs] return JsonResponse(citys, safe=False) return render(request, 'part/test.html',) jquery : <script> $(document).ready(function() { var zipCode = { Chicago: 60290, California: 90001, Chennai: 600040, Cambridge:02138 , Colombo:00800 }; $('#autoSuggest').autocomplete({ source: "{% url 'autofill' %}", select: function(event, ui) { $('#zipCode').val(zipCode[ui.item.value]); } }) }); </script> while i still don't understand how to get zipCode data from models, and pair it with city ? Thanks -
Django + Angular = Global Variable
I have a Django backend that generate, using its settings, a frontend settings.js with variable inside. This "global" contains, for example, the backend URL to allow Angular Frontend to contact. Es. settings.js var backend_url = "https://mydomain/mysite/rest/api" I my Angular frontend I need a way to read it. Unfortunally I cant simply using it becase the "symbol" is not known. Es. app.component.ts ngOnInit() { this.base_server_url = backend_url; <<---- error TS2304: Cannot find name 'backend_url'. } backend_url exists at runtime but Angular/Typescript doesn't know it. I read something about creating a global.d.ts to create a global placeholder but I cant figure out how to use. -
django AttributeError: 'tuple' object has no attribute 'rsplit'
Running python manage.py check throws an error AttributeError: 'tuple' object has no attribute 'rsplit'. Traceback (most recent call last): File "/home/mieltn/django_projects/batch/manage.py", line 22, in <module> main() File "/home/mieltn/django_projects/batch/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/mieltn/django_projects/batch/unesco/models.py", line 4, in <module> class Category(models.Model): File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 320, in __new__ new_class._prepare() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 333, in _prepare opts._prepare(cls) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/options.py", line 285, in _prepare pk_class = self._get_default_pk_class() File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/options.py", line 238, in _get_default_pk_class pk_class = import_string(pk_class_path) File "/home/mieltn/.virtualenvs/django3/lib/python3.9/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: 'tuple' object has no attribute 'rsplit' I saw similar thread about such error and it doesn't seem to be the case. The problem is supposedly connected … -
Complex filtering Django Model based on array inside JSONField
I read all the questions that had anything related to what I am trying to achieve, but still no luck. The one that did help me a little is this one How to filter JSON Array in Django JSONField but I still need something extra. I need to return the Profiles that provide a certain service (filtered by service_id) within a price range. This is the model: class Profile(models.Model): tagline = models.CharField(null=True, blank=True, max_length=40) experience_years = models.IntegerField(null=True) experience_description = models.CharField(null=True, blank=True, max_length=500) services_offered = models.JSONField(null=True) the services_offered attribute has an array of JSON objects, like this: "services_offered": [ { "noOfPets": 1, "hasDogWalk": "N", "pricePerPet": 27, "petServiceId": "2", }, { "noOfPets": 1, "hasDogWalk": "N", "pricePerPet": 30, "petServiceId": "1", }, ] I can filter profiles that offer a certain service (not using the price to do anything here) with this: Profile.objects.filter(services_offered__contains=[{'petServiceId': query_params['service_id']}) But how can I filter the profiles that offer a certain service within a price range? In other words, I need to find the JSON object of that service by the ID and then check the price (using lte and gte) for that service. I have tried this as well, but it returns nothing (price_max was set very high, just … -
Need multiple vendors registered under one business in django-oscar
I am trying to build an Oscar application where: A user can register their store and start selling under pre-defined categories. I want user to have access to dashboard in limited manner such as adding product, stock and product related attributes. Have seen some strategies, but not sure how to start. Any help is very much appreciated, I am trying to build an ecomm site which can help the underprivileged by let them create shops without any hustle. -
Access a variable in Django cron.py from other modules
I defined a variable in urls.py which will be updated every 10 seconds from views.py. I am trying to access this variable in cron.py, I need the updated value when I called from cron.py but I am getting the intialised value but not the updated one. -
How do I rearrange the cards in ascending order django
I have a page where the customer name in the cards is not rearrange in ascending order via alphabetical order Ex: B,M,S. How do I make it to arrange in alphabetical order so that the cards with the customer name Bangkok airways will appear first follow by the cards with malaysia airlines will appear next and so on? views.py def outgoinggallery(request): user = request.user category = request.GET.get('category') if category == None: alloutgoinglru = OutgoingLRU.objects.filter(category__user=user) else: alloutgoinglru = OutgoingLRU.objects.filter(category__name=category, category__user=user) # if query: # return OutgoingLRU.objects.filter(title__icontains=query) categories = Category.objects.filter(user=user) context = {'categories': categories, 'alloutgoinglru': alloutgoinglru} return render(request, 'Outgoing/outgoinggallery.html', context) outgoinggallery.html {% extends "logisticbase.html" %} {% block content %} <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; border-radius: 15px; } .image-thumbail { height: 200px; object-fit: cover; } .list-group-item a { text-decoration: none; color: black; } </style> <br> <div style="padding-left:16px"> <div class="row"> <div class="col-md-9"> <div class="row"> <h5>View Outgoing LRU</h5> <div class="col-md-7"> </div> <br> <div class="col-md-9"> <div class="row"> {% for OutgoingLRU in alloutgoinglru %} <div class="col-md-4"> <div class="card my-4"> <img class="image-thumbail" src="{{OutgoingLRU.image.url}}" > <div class="card-body"> <small>Customer Name: {{OutgoingLRU.category.name}}</small> <br> <small>Delivery Order: {{OutgoingLRU.Deliveryor}}</small> </div> <a href="{% url 'viewlruphoto' OutgoingLRU.id %}" style="width:265px" class="btn … -
How to avoid duplicate key error with django allauth?
I have made some changes to my user model and as a result it seems that when a new user tries to sign up they receive the error: IntegrityError at /accounts/signup/ duplicate key value violates unique constraint "users_user_username_key" I am not sure what is causing the error This is the forms.py: from django.contrib.auth import get_user_model, forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ User = get_user_model() class UserChangeForm(forms.UserChangeForm): class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) settings.py # django-allauth # ------------------------------------------------------------------------------ ACCOUNT_ALLOW_REGISTRATION = env.bool( "DJANGO_ACCOUNT_ALLOW_REGISTRATION", True ) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "username" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "mandatory" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "pharmhand.users.adapters.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = ( "pharmhand.users.adapters.SocialAccountAdapter" ) # Your stuff... # ------------------------------------------------------------------------------ ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserCreationForm' And the models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ class User(AbstractUser): # First Name and Last Name Do Not Cover Name Patterns # Around the Globe. name = models.CharField( … -
Rendering charts using local Chart.js in overriding Django templates
I am trying to add charts to Django admin form with Chart.js. I would like to run my Django website completely offline. Therefore, I downloaded (i.e., copy/past the Chart.js script from the internet and saved the script locally) the js script and saved it in the "templates" folder where I put my overridden Django html pages. Originally, if I directly quote the JS script like other people do, I am able to render the Chart correctly in my Django admin form. Like the code below <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script> However, if I trying to quote the local JS script, I will not get any chart. Like the code below <script src="Downloaded_CHART_JS_script.js"></script> But if I do not rendering the html page from Django, I can see my chart rendering normally. I tried to search through Django reference for several days, but can't find solution so far. Thank you. -
TypeError: expected str, bytes or os.PathLike object, not tuple in bash console of pythonanywhere.com [closed]
I am using Django for a project. I am getting this error -->TypeError: expected str, bytes or os.PathLike object, not tuple here is my settings.py in vscode settings.py in vscode and this is the image of settings.py on pythonanywhere.com where i am trying to upload my website settings.py on pythonanywhere.com and this is the image of bash console of pythonanywhere.com where i am trying to collect all my static files bash console of pythonanywhere.com any suggestions? -
How to separate decimal value with commas in python? [duplicate]
I want to separate decimal value with commas in the following format. value = 1079149.00 Using f'{value:n}' returns 1,079,149.00 But The output I want is : 10,79,149.00 First separate with 3 then afterward separate by 2 . How can I do this ? In django I only find to change the format in the templates only but not in views. So can I do this with pure python ? -
Making the user active when tapping a button in html, and using a DetailView (Django)
I'm trying to make a user active when I tap a button, and I'm using a DetailView. views.py from .models import Model from django.contrib.auth.models import User from django.shortcuts import redirect class UserInspectView(DetailView): model = Model template_name = 'user-inspect.html' # Make the user is_active = True def accept (request, pk): user = User.objects.get(id=pk) user.is_active return redirect('home') ... urls.py from django.urls import path from . import views urlpatterns = [ path('inspect/<slug:slug>/', views.UserInspectView.as_view(), name='user-inspect'), path('inspect/<int:pk>/accept/', views.accept, name="user-accept"), ... ] user-inspect.html {% extends 'base.html' %} {% block title %} <title>User Inspection</title> {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="container d-flex flex-column"> <div class="ms-5 ps-5" > <h3><strong>User:</strong> {{model.user}}</h3> <br> <h3><strong>Name:</strong> {{model.name}}</h3> </div> </div> </div> <br><br><br> <div class="d-flex justify-content-center"> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2 me-5 pe-5" role="group" aria-label="First group"> <form method="post" action="{% url 'user-accept' model.user.pk %}"> {% csrf_token %} <button type="submit" class="btn btn-primary">Accept</button> </form> </div> <div class="btn-group me-2 me-5 ps-5" role="group" aria-label="First group"> <a href="" type="button" class="btn btn-secondary">Back</a> </div> </div> </div> {% endblock %} models.py from django.db import models from django.contrib.auth.models import User class Model(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) Before my accept view looked like this def accept (request, … -
Method that show error message if name field is not provide
I create a Django form to create a template (that is an object) with some attributes. The user that want to create this template, obviously, should give a name to template. I write clean name() method that checks if a template with that name already exists but now I want to create a method that shows an error message if the user does not provide a name for the template that he's creating. How can I do? This is the django model for the templateForm with his fields: class TemplateForm(BaseForm): enabled_parameters = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(label=_("name *")) sport = forms.CharField(label=_("sport"), widget=forms.TextInput(attrs={"readonly": "readonly"})) owner = forms.CharField(label=_("owner"), widget=forms.TextInput(attrs={"readonly": "readonly"})) visibility = forms.ChoiceField(label=_("visibility"), choices=Template.VISIBILITIES, widget=forms.RadioSelect()) last_update = forms.CharField(label=_("last update"), widget=forms.TextInput(attrs={"readonly": "readonly"})) def clean_name(self): """check if template's name is unique""" name = self.cleaned_data.get("name") template_num = 0 if self.template.pk and name == self.template.name: template_num = 1 if Template.objects.filter(name=name, team=self.template.team).count() != template_num: raise ValidationError(_("A Template named {} already exists.".format(name))) return name -
Form URL Error :Reverse for 'printReports' with no arguments not found. 1 pattern(s) tried
I am currently running into the above error when trying to access my reportsHome page. It seems to be a problem with the 'HREF' section of the form where the code is href="{% url 'printReports' reports_pk %}" The templates , views and URLs are listed in the below code: reportsHome.html : {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> <div class="list-group"> <a href="#" class='list-group-item active'>Print Single Complex's</a> {% for x in model %} <a href="{% url 'printReports' reports_pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a> {% endfor %} </div> {% endblock %} printPDF.html : <title>PDF Outuput - TrialBalance</title> {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> </div> <br> <br> <div class="table-container"> <table style="width: 100%"> <th >Account</th> <th>Description</th> <th>Debit</th> <th>Credit</th> {% for arr_trbYTD in arr_trbYTD %} <tr> <td>{{ arr_trbYTD.Description }}</td> <td>{{ arr_trbYTD.Account }}</td> <td> {%if arr_trbYTD.Debit > 0%} {{arr_trbYTD.Debit}} {%endif%} </td> <td> {%if arr_trbYTD.Credit > 0%} {{arr_trbYTD.Credit}} {%endif%} </td> </tr> <tr > {% endfor %} <td> <b>Totals</b> </td> <td> </td> {% for xDebitTotal in xDebitTotal %} <td><b>R {{ xDebitTotal }}</b></td> {% endfor %} {% for xCreditTotal in xCreditTotal %} <td><b>R {{ xCreditTotal }}</b></td> {% endfor %} </tr> </table> </div> <br> <br> <br> {% endblock %} Views.py : … -
Combine 2 django models based on multiple columns without using select_related
I have 2 models where both of them contain 2 columns which can be treated as keys and a third column which is the value The goal is to inner join both the models but somehow I'm having trouble doing that I tried following this link but I don't think in my case I would want the columns to foreign key to the other so I can't use "select_related" My Models are as follows: class AssetReturnTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) return = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "return" class AssetWeightTs(models.Model): data_date = models.DateTimeField() asset = models.ForeignKey(Asset, on_delete=CASCADE) weight = models.DecimalField(max_digits=19, decimal_places=10, null=True) class Meta: db_table = "weight" I want to do a query such that I join the AssetReturn and AssetWeight on data_date and asset_id The end goal is to then do a weighted sum of the return. Currently I'm querying both separately and converting them to pandas and merging them. It looks like this: asset_return_ts = AssetReturnTs.objects.get_returns(start_date, end_date, asset_list).values(*columns_required) asset_weight_ts = AssetWeightTs.objects.get_weights(start_date, end_date, asset_list).values(*columns_required2) # Convert to df # Use pd.merge() and then compute weighted sum Any solution which reduces 2 separate queries to one and helps compute the weighted sum would be greatly … -
Reorder UserCreationFrom fields from django.contrib.auth and allauth
I am trying to reorder fields in a user sign up form using django.contrib.auth. There seem to be, however, some fields (username, email and password) that I cannot reorder that I think may be coming from django allauth. settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserCreationForm' forms.py class UserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) first_name = forms.CharField(max_length=12, min_length=4, required=True, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(max_length=12, min_length=4, required=True, widget=(forms.TextInput(attrs={'class': 'form-control'}))) email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.', widget=(forms.TextInput(attrs={'class': 'form-control'}))) password1 = forms.CharField(label=_('Password'), widget=(forms.PasswordInput(attrs={'class': 'form-control'})), help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label=_('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}), help_text=_('Just Enter the same password, for confirmation')) username = forms.CharField( label=_('Username'), max_length=150, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={'unique': _("A user with that username already exists.")}, widget=forms.TextInput(attrs={'class': 'form-control'}) ) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) I am able to reorder first and last name fields but these always come below username, email, and password. -
Recording user activity in django?
I have a project in which some user can perform CRUD activities. I want to record who did what and when. Currently, I am thinking of making a model class UserAction(models.Model): user_id = models.CharField(max_length=100) action_flag = models.CharField(max_length=100) class_id = models.CharField(max_length=100) action_taken_at = models.DateTimeField(default=datetime.now()) and making a function that fills my UserAction table. Is there any better way to do this? -
How to queue requests in Django?
I manage a physical locker with Django (DRF). Users fill out a form, authenticate via link sent to their e-mail, authorize via a pin displayed on the locker. My view should handle three cases: If user authenticates and authorizes successfully, pin displayed on the locker is replaced with a generic message and the locker opens. (Already implemented) If the user fails to authorize within 3 minutes, locker pin is replaced with a generic message. If a new authorization request is made by user Foo, while authorization for user Bar is still incomplete, stack the request in a queue and wait for case 1. or case 2. to complete. How can I: Implement a request queue, such that the pin displayed on the locker does not get overridden/replaced when a new request comes in? How can I wait 3 minutes for authorization to be completed before processing the next request? View as is, in case it is useful: if request.method == 'POST': form = ConfirmationForm(request.POST) if form.is_valid(): if pin == form.cleaned_data['pin']: open_bay(jwt_token=jwt[1], pin=pin) display_generic_message(jwt_token=jwt[1]) lock_bay(jwt_token=jwt[1], pin=pin) return render(request, 'static/pages/request-success.html') else: pass else: form = ConfirmationForm() return render(request, 'static/pages/confirmation.html', {'form': form}) -
How to apply paging in Django's formview?
my view.py class Formtestview(FormView): template_name = 'test.html' form_valid(self, form): 'my code to search' => 'result is object_list' page = self.request.GET.get('page','1') paginate = Paginator(object_list, 10) page_obj = paginator.get_page(page) return render(self.request, 'test.html', {'form':self.form_class, 'object_list':object_list, 'page_obj' = page_obj}) As in the code above, input is received through form_valid, paged, and then sprayed on the same html template. Results and paging are also displayed normally, but if you go to another page like ?page=2, only the basic template without all the results is shown. Is there a way to paginate the form and search results in one template? -
How to improve my Django PWA push notification process?
I'm learning to do push notifications in Django PWA -app. I've chosen to use fcm-django library for the job in the back end but I'm unsure about the process and if I'm about to do it correctly. This is how I imagine I would build the process, please correct me if there's something wrong. Please also note that I'm more a back end person and don't know that much of the front end side: Get permission from the user for the notifications in front end (service worker). This is the JS -library I think I'll use for the front end job Get the token in the front end and save it to the database with device and user info. For this I first thought I'd need to build some custom view in my Django back end, but researching more revealed that I can use fcm-django built in classes like FCMDeviceViewSet and FCMDeviceAuthorizedViewSet. Send push messages to the user. This will include custom views and logic in the back end to get the users and send the notifications to them when some criteria is met (for example datetime). I would be really grateful to get some feedback and suggestions if I've … -
Update search content in HTML table in django
I want to update the search content in the HTML table under the column hostname and want to display the IP address of the hostname under IPv4 and IPv6 column this is my views.py from django.shortcuts import render import dns import dns.resolver def index(request): if request.method == 'POST': search = request.POST.get('search') ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() -
GET request 404 error (not found) this is the error that i am getting when i am calling a file present in same folder
This is the javascript code in which I am using the get method. [This is the directory in which both the files are present, the html file that the js code is part of and also the text file.[][This is the image of the console with errors.[][2]2[2]]3 -
How to get id of selected row in table using javascript
Current student information list is being printed. Then, by selecting the checkbox and clicking the "Add Teacher" button, a function has been added so that the currently logged in name is added to the teacher column. Here, I want to apply an event to all selected rows by passing multiple values to the parameter when multiple checkboxes are selected. I've been looking for it, but I can't find a solution, so please help. urls.py path('student/add_teacher/<int:id>/', views.add_teacher) views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr class="text-black tr-hover table-link text-center student" student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_function.js $(function () { $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("업데이트하시겠습니까?"); if (updateTeacher) { window.location.href = 'student/add_teacher/' + studentID + '/'; } }); }); -
Can i make sfu webrtc in django for live broadcasting of stream to many people ? any source code or tutorial?
I wanna connect upto 10 people in live stream where they are sharing there video and audio with each other. And this stream should be capable to seen by million people on the internet.I wanna make it with django(webrtc), i know about p2p connection, i found some tutorials on net about it but it wasn't efficient for 10 peers(because it uses more cpu). so i wanna use SFU. Your suggestion will be helpful. WebRTC - scalable live stream broadcasting / multicasting