Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object is not iterable in django rest
I have a simple view in DRF that looks like this: class AdminDocumentListUpdateView(generics.ListAPIView, mixins.UpdateModelMixin): queryset = Document.objects.all() serializer_class = AdminDocumentSerializer pagination_class = None def get_queryset(self): user_id = self.kwargs.get('user_id') qs = Document.objects.filter(user=user_id).latest('created_at') return qs But the get_queryset function raises an error 'Document' object is not iterable. This only happens when I add something like latest('created_at') or first() or I try to index the queryset ([0]). Why is this happening? -
DecimalField without defining precision and scale
How to not specify DecimalField with precision and scale? I got many columns with different values and would like to take what is there without specifying specific precision and scale for every column. Can I define somehow DecimalField without specifying precision and scale so data will be taken as it is? In my source database columns are marked either numeric or numeric(x,y). Maybe defining in django just as numeric instead decimalfield? -
how to disappear label after 1 week for django template
lets think you have a blog with entrys. You want that the newly created entry has a label "new" and you want that this "new" label should disappear after 1 week from ceated_date. What kind of way would you follow. I try this in django template. Thank you -
How to get the value of a hidden input in django views
I am working on a django application. In the application, I have a drop-down button in a form. There also is a hidden input field that will hold the value of the drop-down item selected. (I achieved this with jQuery). I want to access the value of the hidden field in the views.py file. Right now when the form is submitted, I am only getting a None value returned. I am not sure what I am doing wrong. This is my code so far HTML template <form method="post" action="{% url 'test_app:get_data' %}"> {% csrf_token %} <div class="dropdown"> <button class="btn btn-primary btn-lg btn-block dropdown-toggle fruit-btn" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Fruit </button> <input type="hidden" name="fruit-name" id="fruit-name" value="" disabled> <div class="dropdown-menu"> <ul class="list-group" role="menu" aria-labelledby="dropdownMenu"> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Apple</a></li> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Banana</a></li> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Mango</a></li> </ul> </div> </div> ... <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button> </form> views.py def test_data(request): if request.method == 'POST': fruit = request.POST.get('fruit-name') print(fruit) return redirect("test_app:root") return render(request, 'test_app/root.html') jquery code to get the value of the button in the hidden input field $(document).ready(function() { $('.dropdown-item').click(function() { $('.fruit-btn').text($(this).text()); $('.fruit-btn').val($(this).text()); $('#fruit-name').val($(this).text()); console.log($('#fruit-name').val()) }) }) This is the output of the jquery … -
How to increment "number" field for each owner(ForeignKey) in Django
Please help ! Here is my model , I want to have a number for each address each owner. Like for owner A he might have address 1 address 2 .. owner B also : address 1 address 2 .. class Address(TimeStamp): number = models.IntegerField(default=0, null=False) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='owner_address') def save(self, *args, **kwargs): if self.pk: for owner in self.owner: self.number += 1 return super(DeliveryAddress, self).save(*args, **kwargs) -
<HaltServer 'Worker failed to boot.' 3> Gunicorn error, log-file shows no errors
So I just set up my Django up on server with Nginx and Gunicorn, and it was working fine with my development settings, however when I added the production settings it stopped working for some reason. Here are the tracebacks. ~/mediabiz$ gunicorn --log-file=- mediabiz.wsgi:application [2020-06-17 11:15:53 +0000] [10691] [INFO] Starting gunicorn 20.0.4 [2020-06-17 11:15:53 +0000] [10691] [INFO] Listening at: http://127.0.0.1:8000 (10691) [2020-06-17 11:15:53 +0000] [10691] [INFO] Using worker: sync [2020-06-17 11:15:53 +0000] [10694] [INFO] Booting worker with pid: 10694 ~/mediabiz$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2020-06-17 11:14:38 UTC; 3min 11s ago Main PID: 10583 (code=exited, status=1/FAILURE) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: self.stop() Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: time.sleep(0.1) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: self.reap_workers() Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers[m Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 systemd[1]: … -
How to give proper path to FFMPEG in Django for using django-video-encoding package?
Hey guys I am using django-video-encoding package, I followed the documentation but it isn't working when I upload videos. I don't know how to properly provide the path for ffmpeg path for django in windows 10. This is what i have given now. VIDEO_ENCODING_FFMPEG_PATH = "c:\\ffmpeg\\bin\\ffmpeg.exe" but it doesn't seem to work and no errors are showing, as the video is getting uploaded, but not getting converted. How to properly provide the path in windows? Thanks -
How to pass data from jquery to views.py django
I Have data in a variable need to pass in views.py in Django. Code: index.html <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <button class="btn graph-btn">View Graph</button> </td> <td> <button class="btn predict-btn">Predict Closing Price</button> </td> </tr> {% endfor %} </tbody> </table> When I click on .graph-btn it will get data from .comp_name.(Here is the code): <script> $(".graph-btn").click(function() { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); }); </script> so here data in text I want to pass in views.py. -
How to manually render django forms and grab the data on submit
I have the codes below from a forms.Form (I don't want to use ModelForm) because i want to manage the look of HTML form and I am unable to see the data that i post on submit. forms class SearchForm(forms.Form): hotel_name = forms.CharField(max_length=40) check_in_date = forms.DateField() check_out_date = forms.DateField() guest_number = forms.IntegerField() views from .forms import SearchForm import datetime def index(request): date_ = datetime.date.today() today = date_.strftime("%Y-%m-%d") if request.method == "POST": form = SearchForm(request.POST) print(form) # me trying to print only the data received on POST else: form = SearchForm() context = { 'form': form, } return render(request, 'hotels/index.html', context) template <table> <tr> <th> <label for="destination">Destination:</label> </th> <td> <input type="search" id="search_name" placeholder=" Where would you like to stay?" name="search" size="40"><br> </td> </tr> <tr> <th> <label for="check_in">Check In:</label> </th> <td> <input id="check-in" name="check-in" type="date" min="{{today}}" onchange="checkInDate(event)"><br> </td> </tr> <tr> <th> <label for="check-out">Check Out:</label> </th> <td> <input id="check-out" name="check-out" type="date" min="{{today}}" onchange="checkOutDate(event)"><br> </td> </tr> <tr> <th> <label for="id_mime">Mime:</label> </th> <td> <input id="guests" name="guests" type="number" min="1" max="5" size="10"><br> </td> </tr> <tr> <td></td> <td><input type="submit"></td> </tr> </table> Is there anything that i am doing wrong? Any help would be helpful. -
How i solve this below issue get authenticate user detals?
** that time i get authenticated user data my condition is not true but when i get not authenticated user data below condition is true so can anyone help me what can i do..................................................................................................................................................................................................................** header.html <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if request.user.is_authenticated%} <a class="navbar-brand" href="">Welcome{{user.get_username}}</a> <!-- Welcome {{ user.get_username}} --> {% else %} <a class="navbar-brand" href="">no</a> {% endif %} **And when i write this code condition is true show username in template what can i do?** <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if not request.user.is_authenticated%} <a class="navbar-brand" href="">Welcome{{user.get_username}}</a> <!-- Welcome {{ user.get_username}} --> {% else %} <a class="navbar-brand" href="">no</a> {% endif %} views.py def registration_view(request): # if this is a POST request we need to process the form data template = 'home/login.html' if request.method == 'POST': print("post") # create a form instance and populate it with data from the request: form = RegisterForm(request.POST) # check whether it's valid: if form.is_valid(): print("okk valid") if User.objects.filter(username=form.cleaned_data['username']).exists(): messages.error(request,'Username already exists') return render(request, template, { 'form': form, 'error_message': 'Username already exists.' }) elif User.objects.filter(email=form.cleaned_data['email']).exists(): messages.error(request,'Email already exists') return render(request, template, { 'form': form, 'error_message': 'Email already exists.' }) elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']: messages.error(request,'Password do not … -
Calling a django function view from an aws lambda function
I want to run my django views on AWS Lambda. For this I had created a lambda function which is calling that view function. The AWS lambda function is something like this -> import app.views as v def functionA_handler(event, context): some_value = v.functionA(event) return some_value The corresponding view in app.views file would be something like this -> from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse @csrf_exempt def functionA(request): request_body = json.loads(request.body) return JsonResponse(request_body, status=200) How can I link the above lambda function to the view function? The view takes an input of the form request which is creating an issue here. Any solution? -
Elastic Beanstalk - Command failed on instance.An unexpected error has occurred [ErrorCode: 0000000001]
First time I'm trying to deploy a django app to elastic beanstalk. The application uses django channels. These are my config files: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard/dashboard/settings.py" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /websockets/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When I run eb create django-env I get the following logs: Creating application version archive "app-200617_112710". Uploading: [##################################################] 100% Done... Environment details for: django-env Application name: dashboard Region: us-west-2 Deployed Version: app-200617_112710 Environment ID: e-rdgipdg4z3 Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.7 running on 64bit Amazon Linux 2/3.0.2 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2020-06-17 10:27:48.898000+00:00 Printing Status: 2020-06-17 10:27:47 INFO createEnvironment is starting. 2020-06-17 10:27:49 INFO Using elasticbeanstalk-us-west-2-041741961231 as Amazon S3 storage bucket for environment data. 2020-06-17 10:28:10 INFO Created security group named: sg-0942435ec637ad173 2020-06-17 10:28:25 INFO Created load balancer named: awseb-e-r-AWSEBLoa-19UYXEUG5IA4F 2020-06-17 10:28:25 INFO Created security group named: awseb-e-rdgipdg4z3-stack-AWSEBSecurityGroup-17RVV1ZT14855 2020-06-17 10:28:25 INFO Created Auto Scaling launch configuration named: awseb-e-rdgipdg4z3-stack-AWSEBAutoScalingLaunchConfiguration-H5E4G2YJ3LEC 2020-06-17 10:29:30 INFO Created Auto Scaling group … -
Can't test uploading file with Django clien.post method
I have problem with testing API method. I have model Game with such field: background = models.ImageField(max_length=255, null=True, blank=True, storage=s3_storage, upload_to='game_back/%Y/%m/%d') Serializer for that model looks like: class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = (<list_of_fields>, 'background') I tried to write test that cat pass image to this model. But i have problem with Djnago test build-in method for post. If i write: file = open('<path_to>/test_image.png', 'rb') content_bytes = file.read() img = SimpleUploadedFile("uni_image.png", content_bytes, content_type="image/png") response = self.client.post( reverse('game_create'), data={'background': img}, format="multipart" ) Django raise an exception UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte on row with client.post I tried to pass base64 encoded data instead of SimpleUploadedFile use, but in this case my API serializer cant validate and save image file. Thanks for reacting! -
Django Rest Framework: Get field name from model definition
Within the Django Rest framework documentation it is suggested to declare the "field" list explicitly to avoid providing the data of new columns just by adding them to the model which may contain sensitive information. The field list is an array of strings, containing the field ids. To avoid declaring field ids, which actually do not exist in the model (e.g. typos or changed models) I tried to declare the list using object references - but always end up with "DeferredAttribute: object has no attribute ". I have read something that meta information is not available in objects and that you could solve that by defininig your own Meta class using Object._meta.get_fields() and store it in the class, but I thought there might be a simpler/more elegant way (and I do now know, how, in detail ;-)). Example: class Samples(models.Model): # Meta data, primarily used in AdminSite. class Meta: verbose_name = _('Samples') verbose_name_plural = _('Samples') samples_boolfield = models.BooleanField samples_textfield = models.CharField(max_length=2000, blank=True) views.py: class SamplesView(viewsets.ModelViewSet): serializer_class = SamplesSerializer queryset = Samples.objects.all() serializers.py: Version 1, which does not show any errors in pyCharm or makemigrations, but calling the API reults in "TypeError at /api/samples/: argument of type 'DeferredAttribute' is not iterable": … -
Django and Amazon Lambda: Best solution for big data with Amazon RDS or GraphQL or Amazon AppSync
We have a system with large data (about 10 million rows in on a table). We developed it in Django framework and also we want to use Amazon Lambda for serving it. Now I have some question about it: 1- If we want to use Amazon RDS (MySql, PostgresSQL), which one is better? And relational database is a good solution for doing this? 2- I read somewhere, If we want to use a relational database in Amazon Lambda, Django for each instance, opens a new connection to the DB and it is awful. Is this correct? 3- If we want to use GraphQL and Graph database, Is that a good solution? Or we can combine Django Rest-API and GraphQL together? 4- If we don't use Django and use Amazon AppSync, Is better or not? What are our limitations for use this. Please help me. Thanks -
Django channels on Elastic Beanstalk - is this config file correct?
Following this guide https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 to deploy a django project which uses channels. In the guide they mention to create the file <PROJECT_DIR>/.ebextensions/01_env.config with the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: <PROJECT_DIR/.../>wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <PROJECT_DIR...CONFIG.FILE> PYTHONPATH: /opt/python/current/app/<PROJECT_DIR>:$PYTHONPATH If my project is called dashboard, is the following correct? option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard/dashboard/settings.py" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH -
Django User and Group model permissions fields as manytomany
In my project, I'm using custom overridden admin templates but I cannot figure out how to change the permissions and groups selector in the User and Group models. I want to change them to how the ManyToMany field handles it or a multi-select. How to I change it? Thank you for reading this. -
'UserDetailView' object has no attribute 'object_list'
everyone! In the user detail page I have user's posts, which I want to paginate(planning to make infinite pagination later on). Trying to to that, I get the error 'UserDetailView' object has no attribute 'object_list'. I was searching a lot for solution, but did not find clear example how to paginate related objects in detail view. Any help on this higly appreciated. This is my DetailView for user: class UserDetailView(DetailView,MultipleObjectMixin): model = CustomUser template_name = 'users/user_detail.html' context_object_name = "user" paginate_by = 5 def get_object(self): id_ = self.kwargs.get('id') return get_object_or_404(CustomUser, id=id_) def get_context_data(self, **kwargs): posts = self.object.posts_set.all().order_by('-created_at') #context['posts'] = self.object.posts_set.all().order_by('-created_at') context = super(UserDetailView, self).get_context_data(posts=posts, **kwargs) context['main'] = Main.objects.get(pk=1) context['supporters'] = CustomUser.objects.filter(team = self.object.team) return context And the error I get : 'UserDetailView' object has no attribute 'object_list' Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/user/1/ Django Version: 3.0.7 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'team.apps.TeamConfig', 'posts.apps.PostsConfig', 'main.apps.MainConfig', 'crispy_forms', 'django.contrib.humanize', 'rest_framework', 'pytils'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Django response with additional headers returns 500
Our application developed in Django needs to pass some additional headers in selected requests. We do so this way: original_response = Response(status=status.HTTP_204_NO_CONTENT) original_response['X-Status-Type'] = 'info' original_response['X-Status-Message'] = 'Il cliente è stato avvertito' return original_response In our method. However, while this works on our local setup, on heroku this generates a 500 error which we cannot figure out. -
Problem connecting to websocket on my django App after deployment on Azure
After deploying the django App on Azure via VS Code, html pages are working fine but seems that I have a problem connecting to the websocket, even though that I enabled the websocket on my azure portal app. Console log: Firefox can’t establish a connection to the server at wss://myapp.azurewebsites.net:8080 The app is running on docker: FROM python:3.7-buster # Define environment variables ENV ACCEPT_EULA=Y ENV PYTHONUNBUFFERED=1 # Expose port EXPOSE 8080/tcp # Create app directory WORKDIR /django_ui # Copy all files to image COPY . . # Install recuired apt packages RUN apt-get update && apt-get install -y --no-install-recommends gcc unixodbc unixodbc-dev build-essential curl # Install microsoft sql driver for debian RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \ curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list && \ apt-get update && \ apt-get install -qq -y msodbcsql17 && \ apt-get install -qq -y mssql-tools && \ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile && \ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc # Install recuired pip packages RUN pip install -r ./req/requirements.txt # Remove requirements RUN rm -rf ./req # Run django websocket server 0 0 0 0 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8080"] The endpoint in my .js file looks like this: // Get endpoint var … -
Django how to import value in request function from another one?
I have the following views function: def stato_patrimoniale(request): now=datetime.datetime.now() last_account_year=float(now.year)-1 #definizione dell'ultimo anno contabile now = now.year if request.method == 'POST': year = request.POST['year'] if year != '': now = year last_account_year = float(now) - 1 context= { 'last_account_year': last_account_year} return render(request, 'stato_patrimoniale/stato_patrimoniale.html', context) Now I want to use the last_account_year value in another views.py. It's possible? -
i got an error. django.urls.exceptions.NoReverseMatch
l am started to learn Django for few days, i got an error. django.urls.exceptions.NoReverseMatch: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']* urls.py path('create_order/<str:pk>/', views.createOrder, name='create_order'), views.py def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': # print('Printing:', request.POST) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'accounts/order_form.html', context) order_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-12 col-md-6"> <div class="card card-body"> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-sm btn-danger" type="submit" value="Conform"> </form> </div> </div> </div> {% endblock %} customer.html <div class="row"> <div class="col-md"> <div class="card card-body"> <h5>Customer:</h5> <hr> <a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a> <a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a> </div> </div> -
Call a pop up delete modal usin g django DeleteView
i am using django generic deleteview for deleting my object. i want to delete object from list of objects. There is a trash icon. If user clicks the trash icon a popup modal will come to ensure whether the user wants to delete the object or not. The popup will have a cancel button and a delete button. If the user choses delete button the object will be deleted forever. But the problem is the listview is in one html and deleted popup modal html is in other html. As i am using django generic class for ListView and DeleteView, I have to keep two separate html. now I dont know how can i connect both htmla and show a popup delete option employe_list.html: this html shows the listview of employees. {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" data-target="exampleModal" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th> <span class="custom-checkbox"> … -
Best way to get all model fileds names
What is the best way to get the list of all fields names of a model: I use: list_of_model_field = Mymodel_meta.get_fields() is there any other way? -
Translate response django geoip2 maxmind
I need localization response geoip GeoLite2 maxmind. The site on django, trying to fasten the location. I do according to the instructions from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() g.city('72.14.207.99') Response: {'city': None, 'continent_code': 'NA', 'continent_name': 'North America', 'country_code': 'US', 'country_name': 'United States', 'dma_code': None, 'is_in_european_union': False, 'latitude': 37.751, 'longitude': -97.822, 'postal_code': None, 'region': None, 'time_zone': 'America/Chicago'} Fine work, but I need to get an answer in another language, for example ru-RU. How to do it? Maybe you need to specify some argument? I would be grateful for any help.