Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User DictField in combined model serializer in Django DRF
Environment: Django 2.2.16 Django RESTFramework 3.8.2 Let's say, I wan to group my query_set to a specific format and serializer all models at a time. In the past, we used a customized model to grouping the type and then feed to the customize serializer. However, we recently trying to upgrade the Django from 1.11.x to 2.2 and so as DRF. Then, there's an error prompt and I can't fix it. I also find a link, Look like it's a known issue in DRF. AttributeError: 'DictField' object has no attribute 'partial' I defined several models and serializer. class ModelA(models.Model): job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelASerializer(serializers.ModelSerializer) Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelB(models.Model): Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields class ModelBSerializer(serializers.ModelSerializer) Job_id = models.IntegerField() type = models.CharField(max_length=16) ... Some fields ... and many models below I create a customized model to serialize all models to specific format. class CustomizeModel: def __init__(self, Job_id): self.a = {} self.b = {} # In below, I group the query_set by 'type' a_set = ModelA.objects.filter(job_id=job_id) for obj in a_set: if obj.type not in self.a: self.a[obj.type] = [] self.a[obj.type].append(obj) b_set = ModelB.objects.filter(job_id=job_id) for obj in a_set: … -
Django REST Framework How to Efficiently Filter Calculate Model property
I have a model property of is_expired that simply returns True or False by comparing the current time with another field called Saas_expire_date. @ property def is_expired(self): current_time = timezone.now() return current_time > self.saas_expire_date How do i efficiently filter this.. I fear That using For loops will drastically affect response time especial if there is alot of data class StorePublicAPI(APIView): """ Store API for client side """ def get(self, request): """ `Get Stores` """ raw_stores = Store.objects.filter( is_approved=True, is_active=True) stores = [] for store in raw_stores: if not store.is_expired: stores.append(store) serializer = StorePublicSerializer(stores, many=True) return Response(serializer.data, status=status.HTTP_200_OK) or can you help me if finding a more effective way of calculating whether a user has paid or not? when the Saas_expire_date field reaches the current date time -
Multiple Error in view,edit a list of a model
i am trying to view and edit the my customer model- i am doing is when you open the server for first time the list of customer opens as a link . as sson as i press suppose customer 1 . the form appears well pre filled as soon as i make changes and press save button it gives me error- Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/marketing/editcustomer/2250a9b1-5d25-4bce-b426-e3a4abb45abb/POST I also have back button - I get the same error after pressing back button too! Then if I go back to the customerlist(seecustomer) and I again click on the same or any other customer it gives me the following error- Manager isn't accessible via customer instances sometimes it also gives - First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'customer'. my models.py class customer(models.Model): customerid=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) customername=models.CharField(max_length=1000) my views.py def editcustomer(request,customer_pk): global customer customer=get_object_or_404(customer,pk=customer_pk,user=request.user) if request.method=='GET': form=createcustomerform(instance=customer) return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form}) else: try: form=createcustomerform(request.POST,instance=customer) form.save() return redirect('seecustomer') except ValueError: return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form,'error':'Incorrect entry'}) my html form code- <form action="POST" method="POST"> {% csrf_token %} <div id="customername"> <span><label for="customername">Company Name</label></span> <input type="text" id="customername" name="customername" placeholder="Enter Company's Full name" value="{{ customer.customername}}"> </div> <button class="btn btn-primary btn-md" type="submit">Save</button> <br> <input … -
checking hased password in django gives incorrect output
i am checking password of user to give user info.but when i give correct password it throws password not correct error. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email views.py from rest_framework.authtoken.models import Token from django.contrib.auth.hashers import check_password,make_password ## My Login View class LoginView(APIView): serializer_class = CustomTokenCreateSerializer permission_classes = (AllowAny,) def post(self,request,*args, **kwargs): # Cheking email Exists if User.objects.filter(email=request.POST['email']).exists(): user = User.objects.get(email=request.POST['email']) ## check password matches if check_password(request.POST['password'],user.password): ## Creating TOken token, _ = Token.objects.get_or_create(user=user) serializer = UserCreateSerializerCustom(user) return Response({'status':True, "message":"Login SuccessFull", "user_info":serializer.data, 'token':token.key}) else: return Response({'status':False, "message":"Passord is not correct,Check Passsword again"}) else: return Response({'status':False, "message":"User Doesn't Exist,Check Email again"} ) this is login api for my project.i'm using check_password function for checking the password,i can't find a solution for this problem. -
How to get values from another app from the database in Django?
How can I get the value from another app and display that value in the template present in another app of a project in Django? I have this project dir structure:- -News-Scrap - accounts - education - home - news - models.py(The value is present here) - views.py - templates - static - templates - base.html(I want to display a value here which is present in the `news` app) Since the base.html file is out of the app, how can I display any particular value from news app's the database in this page. Here's the models.py(from news app) file:- from django.db import models class PageView(models.Model): hits = models.IntegerField(default=0) #I need this value to be displayed in my `base.html` file Here's the views.py(from news app) file:- def news_list(request, *args, **kwargs): if(PageView.objects.count()<=0): x=PageView.objects.create() x.save() else: x=PageView.objects.all()[0] x.hits=x.hits+1 x.save() context={} context = { 'object_list': queryset, 'page': x.hits } return render(request, 'news_list.html', context) If the base.html file would be inside the news app I could easily get the value by {{object.<id_label>}}, But this is not working when the base.html file is present outside the app. I am a beginner in Django and having a tough time figuring out a way to achieve this. -
How to use <iform> tag to display html page
I created a view to display all the logged in users and also created a URL for it. When I explicitly go that URL path the page works fine. But when I try to display that same page inside another page using it shows an error "Localhost refused to connect". -
How do I populate an editable form field with logged in user name in django?
I am trying to create an e-commerce application using django. The customer logs in and when placing an order he/she has to fill a form which has fields like name, phone number, date etc. Since the user has already logged in how to I pre-populate the name field with username and how do i make the field editable so that if the user wants to change the username to something else. -
How to write django code inside css style tag to link images from static directory
I want to write Django code into CSS style tag in HTML elements in order to get images from static directory. here is my original code <a href="single.html" class="img" style="background-image: url(images/image_1.jpg);"></a> i tried with the below code <a href="single.html" class="img" style="background-image: {% static 'images/image_1.jpg' %};"></a> but this isn't worked for me, how can i solve this problem? NB: i used {% load static %} to load all static files, css and js works fine but i became failed to do this. -
Creating a group through models, forms and view
I am a newbie here to Django. I am practising it for work purposes. What I am trying to achieve is to create a custom Group (adding, deleting, editing). My question is that I have a form.py that takes in a CharField, and how do I extract the particular string (or char) that the user has inputted through form, and create a group. views.py def add_group(request): if request.method == "POST": mem_info_form = MembershipsInfoForm(data = request.POST) if memberships_form.is_valid(): mem_info = mem_info_form.save() else: print(mem_info_form.errors) else: mem_info_form = MembershipsInfoForm() return render(request, 'app_memberships/addmembershipsinfo.html', {'mem_info_form' : mem_info_form }) forms.py class MembershipsInfoForm(forms.ModelForm): memberships_info_form = forms.CharField(widget = forms.TextInput(attrs = {'class' : 'form-control'})) class Meta(): model = MembershipsInfo fields = ('memberships_info') models.py class Memberships(models.Model): membership = models.CharField(max_length = 20) def __str__(self): return self.membership class MembershipsInfo(models.Model): memberships_info = models.ForeignKey(Memberships, related_name = 'memberships_info', on_delete = models.CASCADE) class MyMembership(models.Model): my_membership = models.OneToOneField(Memberships, on_delete = models.CASCADE) def __str__(self): return self.my_membership Would appreciate the assistance! -
Django template inheritance: passing for loop iterable
I am developing a dictionary application using Django. One of the main themes of the app is displaying feeds of definitions. Specifically, I have: an "index" feed where new definitions are listed, a "headword" feed where definitions of a particular headword are listed, and a "tag" feed where definitions tagged with a particular tag are listed. index.html: {% block body %} <h1>Definitions</h1> <ul> {% for definition in definitions %} <li> Headword: {{ definition.headword }} <br> Definition: {{ definition }} <br> Example: {{ definition.example }} <br> Tags: <ul> {% for tag in definition.tags.all %} <li>{{ tag }}</li> {% empty %} <li>No tags.</li> {% endfor %} </ul> </li> {% empty %} <li>No definitions.</li> {% endfor %} </ul> {% endblock %} headword.html: {% block body %} <h1>{{ headword }}</h1> <ul> {% for definition in headword.definitions_headword.all %} // same code as above tag.html: {% block body %} <h1>{{ tag }}</h1> <ul> {% for definition in tag.definitions_tag.all %} // same code as above Clearly, I need a base feed.html template that these three files can share. For the h1 tag no problem. However, how can I pass the name of the iterable variable in the three for loops? I tried nesting a {% block iterable … -
Django-admin-site does not work with webpack
I'm using webpack dev-server to run my static files, and everything works fine, but my django-admin-site does not load styles. My settings.py STATIC_URL = 'http://127.0.0.1:8080/' CRISPY_TEMPLATE_PACK = 'bootstrap4' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "dist") ] webpack.config.js const webpack = require('webpack'); module.exports = { mode: 'development', entry: { main: './static/js/index.js' }, output: { publicPath: 'http://127.0.0.1:8080/' }, resolve: { extensions: ['.ts', '.js' ], modules: ['/static/js/', 'node_modules'], alias: {}, }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) ], module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.(scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.(svg|eot|woff|woff2|ttf)$/, loader: 'file-loader', options: { outputPath: 'fonts' } } ], }, } When I change STATIC_URL to /static/ then my django-admin-site works perfect with styles but my entire app doesn't load styles. Is there any way to make it work together? -
DateTimeField.strftime() replaces the original value
I have a ticket system, where I have tickets with following mode: state = models.IntegerField(default=1, choices=TICKET_STATES) type = models.IntegerField(default=9, choices=TICKET_TYPE) priority = models.IntegerField(default=2, choices=TICKET_PRIORITY) heading = models.CharField(max_length=255, default='Uusi tiketti') description = models.TextField(default='') date_modified = models.DateTimeField(auto_now=True, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) date_closed = models.DateTimeField(null=True, blank=True) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_created' ) modified_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_modified' ) closed_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_closed' ) Now, I made a function that converts an instance to a dict, so I can pass it through API def as_dict(self): data = model_to_dict(self) data['created_by'] = { 'id' : self.created_by.id, 'name' : self.created_by.full_name() } data['state'] = { 'id' : self.state, 'name' : self.get_state_display(), 'color' : self.get_color() } data['priority'] = { 'id' : self.priority, 'name' : self.get_priority_display() } data['type'] = { 'id' : self.type, 'name' : self.get_type_display() } print(type(self)) print(type(self.date_created)) data['date_created'] = self.date_created.strftime('%Y-%m-%d %H:%M:%S') return data However, issue is that if I then try to do anything, I get following complaint: AttributeError: 'str' object has no attribute 'strftime' This makes me think that strftime somehow converts the DateTimeField to str, but this should not be the case? Anyone have an idea what is happening here? -
Pre-populate DateTimeField with specific date in django migration
I want to create and pre-populate DateTimeField with specific date for already existing objects. models.py publish_date = models.DateTimeField(verbose_name=_('publish date')) I try to create a nullable field first, fill it with some data and then remove the null=True from it: migrations.py def set_default_publish_date(apps, schema_editor): MyModel = apps.get_model('myapp', 'MyModel') MyModel.objects.all().update(publish_date=datetime.date(day=1, month=1, year=2019)) class Migration(migrations.Migration): dependencies = [ ('myapp', '0005_auto_20200831_1208'), ] operations = [ migrations.AddField( model_name='mymodel', name='publish_date', field=models.DateTimeField(null=True, verbose_name='publish date'), preserve_default=False, ), migrations.RunPython(set_default_publish_date, migrations.RunPython.noop), migrations.AlterField( model_name='mymodel', name='publish_date', field=models.DateTimeField(verbose_name='publish date'), preserve_default=False, ), ] As a result of running migrations I get an error: django.db.utils.OperationalError: cannot ALTER TABLE "myapp_mymodel" because it has pending trigger events What can I do to fix it? -
Django how to integer field start zero?
(sorry my bad english) i have a integer field my models.py.i use this for phone numbers.and phone numbers start zero(0) or plus(+).and when i write this field:05555555 this will be display:5555555.how i do this i write 05555555 and display 0555555?i tried phone number field but working with problem.here my models.py: from django.db import models from django.contrib.auth.models import User class elan(models.Model): cixis_yeri = models.CharField(max_length=150) catma_yeri = models.CharField(max_length=150) cixis_vaxti = models.DateField() catma_vaxti = models.DateField() elaqe_nomresi = models.IntegerField() sirket = models.CharField(max_length=100,blank=True,null=True) elave_melumatlar = models.TextField(null=True,blank=True) silinme_vaxti = models.DateTimeField() user = models.ForeignKey('auth.User',verbose_name='paylasan',on_delete=models.CASCADE) favorit = models.ManyToManyField(User,blank=True,related_name="favorit") def __str__(self): return self.cixis_yeri class Meta: ordering = ['-id'] forms.py: from django import forms from .models import elan class elanform(forms.ModelForm): class Meta: model = elan fields = [ 'cixis_yeri', 'catma_yeri', 'cixis_vaxti', 'catma_vaxti', 'elaqe_nomresi', 'elave_melumatlar', 'sirket', ] labels = { 'cixis_yeri':"Çıxış Yeri", 'catma_yeri':"Çatma Yeri", 'cixis_vaxti':"Çıxış Vaxtı", 'catma_vaxti':"Çatma Vaxtı", 'elaqe_nomresi':"Əlaqə Nömrəsi", 'elave_melumatlar':"Əlavə Məlumatlar", 'sirket':"Şirkət", } widgets = { 'cixis_yeri': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'Olke-Seher','id':"exampleFormControlInput1"}), 'catma_yeri': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'Olke-Seher'}), 'cixis_vaxti': forms.DateInput(attrs = {'class':'cixis_vaxti','type':'date'}), 'catma_vaxti': forms.DateInput(attrs = {'class':'catma_vaxti','type':'date'}), 'elave_melumatlar': forms.Textarea(attrs = {'class':'form-control kendi','placeholder':'elave_melumatlar(Vacib Deyil)','type':'text','id':'exampleFormControlTextarea1','rows':'6','columns':'2'}), 'sirket': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'(Vacib Deyil)','type':'text','id':'exampleFormControlTextarea1','rows':'6','columns':'2'}), 'elaqe_nomresi': forms.NumberInput(attrs = {'class':'form-control kendi','placeholder':'Elaqe','id':"exampleFormControlInput1"}), } please help me.thanks now. -
Unable to create api for generic relationship in django
I'm trying to create api endpoint for generic relationship but I'm facing error. Here I'm using model viewset. My code is same as describe in django rest frameworks docs https://www.django-rest-framework.org/api-guide/relations/#generic-relationships But I'm facing error. -
Heroku with Django, Celery and CloudAMPQ - timeout error
I am building an online shop, following Chapter 7 in the book "Django 3 by Example." Everything works fine in my local machine. It also works well when I deploy it to Heroku. However, when I try to use Celery and RabbitMQ (CloudAMQP, Little Lemur, on Heroku), the email message the worker was supposed to send to the customer is not sent. The task takes more then 30 seconds and then it crashes: heroku[router]: at=error code=H12 desc="Request timeout" method=POST I have created a tasks.py file with the task of sending emails. My settings.py file include the following lines for Celery: broker_url = os.environ.get('CLOUDAMQP_URL') broker_pool_limit = 1 broker_heartbeat = None broker_connection_timeout = 30 result_backend = None event_queue_expires = 60 worker_prefetch_multiplier = 1 worker_concurrency = 50 This was taken from https://www.cloudamqp.com/docs/celery.html And my Profile is as follows, web: gunicorn shop.wsgi --log-file - worker: celery worker --app=tasks.app Am I missing something? Thanks! -
How to use same JavaScript file on two pages with same element ids?
I have created two django template pages with almost same functionality and therefore may of the elements have same ids.....so I reffered the same javascriipt file in both the templates... but now it doesn't work because I suppose both the pages have similar ids of the elements. What should I do so that the js knows to modify only the element on the page which called the function not the other page which has an element with the same id -
TemplateColumn with button and form only returns name of record not content
I am trying to add a button with some functionality in a table that returns some info to the view using a POST: class ProductTable(django-tables2.Table): Template = (f"""<form action="/product_all/" method="POST">{{% csrf_token %}} <button> <input type="hidden" name="store_id" value="{{ record.get_store_id }}"/>view</button> </form>""") view = TemplateColumn(Template) But when printing the request I get: <QueryDict: {'store_id': ['{ record.get_store_id }'], 'csrfmiddlewaretoken': ['...']}> instead of the value. -
Asking for advice on how to get current form data before .save() in django
I have a model called Class which has a ManyToManyField with Student Model. I also have a form called ClassForm for Class Model. My question is how can I filter the Student Model with the field I select in ClassForm? The code are down below and I will explain more about my question. models.py # Student model class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) year = models.CharField(max_length=50) department = models.CharField(max_length=100) studentID = models.CharField(max_length=50) def __str__(self): return '%s , %s , %s' % (self.studentID, self.department, self.year) # Class model class Class(models.Model): department_choice = ( ('TC', 'TC'), ('GIC', 'GIC'), ('GEE', 'GEE'), ('GIM', 'GIM'), ('OAC', 'OAC'), ('OTR', 'OTR'), ('GCI', 'GCI'), ('GGG', 'GGG'), ('GRU', 'GRU') ) year_choice = ( ('year 1', 'Year 1'), ('year 2', 'Year 2'), ('year 3', 'Year 3'), ('year 4', 'Year 4'), ('year 5', 'Year 5') ) teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) # student class_in_department = models.CharField(max_length=100, choices=department_choice) class_in_year = models.CharField(max_length=50, choices=year_choice) subject = models.CharField(max_length=150) forms.py class ClassForm(forms.ModelForm): class Meta: model = Class fields = ['class_in_department', 'class_in_year', 'subject', 'student'] widgets = {'student': forms.CheckboxSelectMultiple} def __init__(self, *args, **kwargs): super(ClassForm, self).__init__(*args, **kwargs) self.fields['class_in_department'].widget.attrs.update(department_attr) self.fields['class_in_year'].widget.attrs.update(year_attr) self.fields['subject'].widget.attrs.update(subject_attr) self.fields['student'].queryset = Student.objects.filter(department="GIC") As you can see I filtered the student field with department="GIC" (last line). … -
AWS+Django+Nginx Unable to server static files
I am having a hard time getting my static files on the website whenever i run the server its shows ""GET /static/css/agency.css HTTP/1.1" 404 179" I am pretty new to django and trying a basic portfolio app here is my configuration 1. /home/ubuntu/portfolder inside (port folder) portproject inside (django project folder) __init__.py __pycache__ asgi.py settings.py urls.py wsgi.py django.ppk app.sock port_pics logfile manage.py media protappli inside (django app folder) __init__.py __pycache__ admin.py apps.py forms.py migrations models.py templates templatetags tests.py views.py static admin css custom img js mail scss vendor The settings.py file STATIC_URL = '/static/' STATIC_ROOT = '/home/ubuntu/portfolder/static/' '''STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static/'), ]''' nginx config file server { #listen [::]:80; listen [::]:1234; server_name 13.59.57.0 ec2-13-59-57-0.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/portfolder/app.sock; } location /static/ { autoindex on; root /home/ubuntu/portfolder; proxy_pass http://13.59.57.0:8000/home/ubuntu/portfolder/static/; #expires 7d; } location /media/ { autoindex off; root /home/ubuntu/portfolder; expires 7d; } location ~* .(jpg|svg|jpeg|gif|png|ico|css|zip|rar|pdf)$ { alias /home/ubuntu/portfolder/; error_page 404 = 404; } } I have tried doing everything i had referred to 10-12 similar queries from stack overflow but none of them showed any promising results. thanks in advance -
ERROR: Twisted-20.3.0-cp39-cp39-win_amd64.whl is not a supported wheel on this platform
I was installing django channels and I got an error that twisted was not installed. I tried installing it after downloading the package from here https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted. But now I am getting this error. ERROR: Twisted-20.3.0-cp39-cp39-win_amd64.whl is not a supported wheel on this platform. Is there a way to install it properly in windows 10. I am using python 3.8. Thanks -
What is the best way to authenticate the same user from the same database but the different applications (e.g. Django and Node js)?
I have created a registration and login system in Django 3.0 framework. In the backend, I am using the MYSQL database. And it is running on EC2-instance-1. There is a Nodejs script running on the other EC2-instance-2. Connected to MYSQL database which is hosted on EC2-instance-1 So, I have registered a user from the Django app and I also can authenticate that user. But when I try to authenticate the same user from Node js Script connected to the same database it won't work. What is the best way to authenticate the same user from the same database but the different applications (e.g. Django and node js)? -
Get multiple objects in one query in Django
I have 3 models: class Ticket(models.Model): id = models.CharField(primary_key=True, max_length=20, null=False) title = models.CharField(max_length=255, blank=False, null=True) description = models.TextField(blank=False, null=True) class Attachment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) file = models.FileField(blank=True, null=True, upload_to='attachments/') class Comment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) comment = models.TextField(null=False) In my views.py file in want to process all of them, so in order to get them I perform 3 queries: tickets = Ticket.objects.filter(id=ticket_id) attachments = Attachment.objects.filter(ticket=ticket_id) comments = Comment.objects.filter(ticket=ticket.id) I want to hit database just once, so my question is how can I get them in one query? I have read about select_related() method, but Attachment and Comment models are not related directly to each other, so I can't start query from any of them. From the other hand Ticket model doesn't have fields like attachment or comment so I can't start query from it. -
Bootstrap Dropdown appears behind other elements
I have a template that mix bootstrap accordion and dropdown, the problem is that dropdown appears behind the next question card or what is the same, inside your card and is not seen. template.html: <div class="card-body"> <!-- Acordion --> <div class="accordion" id="dlns_faqs_acordion"> {% for element in elements %} <div class="card"> <div class="card-header dlns_faqs_acordion_heading" id="dlns_faqs_acordion_heading_{{ forloop.counter0 }}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#dlns_faqs_acordion_content_{{ forloop.counter0 }}" aria-expanded="false" aria-controls="dlns_faqs_acordion_content_{{ forloop.counter0 }}"> {{ element.question }} </button> </h2> <!-- Options --> <div class="dropdown"> <button class="btn dlns_elements_button" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="fas fa-ellipsis-h"></span> </button> <div class="dropdown-menu dropdown-menu-right text-center" arial-labelledby="option_button"> ... <a>...</a> ... </div> </div> </div> <div id="dlns_faqs_acordion_content_{{ forloop.counter0 }}" class="dlns_faqs_acordion_content collapse" aria-labelledby="dlns_faqs_acordion_heading_{{ forloop.counter0 }}" data-parent="#dlns_faqs_acordion"> <div class="card-body"> {{ element.answer }} </div> </div> </div> {% endfor %} </div> </div> style.css: .dlns_faqs_acordion { border: none; } .dlns_faqs_acordion_heading { border: none; background: transparent; display: flex; flex-wrap: nowrap; justify-content: flex-start; align-items: center; flex-direction: row; align-content: space-between; } .dlns_faqs_acordion_heading button { color: var(--dlns_color_primary) !important; } .dlns_faqs_acordion_heading button.collapsed { color: black !important; } .dlns_faqs_acordion_heading button:hover { text-decoration: none; } .dlns_faqs_acordion_content { color: var(--dlns_color_tertiary); } Here there are some images with the problem: Anybody cloud help me ? Thanks in advance. -
How can i lock some rows for inserting in Django?
I want to batch create users for admin. But, the truth is make_password is a time-consuming task. Then, if I returned the created user-password list util the new users are all created, it will let front user waiting for a long time. So, i would like to do somethings like code showed below. Then, I encountered a problem. Cause I can not figure out how to lock the user_id_list for creating, someone registered during the thread runtime will cause an Dulplicate Key Error error thing like that. So, I am looking forward your good solutions. def BatchCreateUser(self, request, context): """批量创建用户""" num = request.get('num') pwd = request.get('pwd') pwd_length = request.get('pwd_length') or 10 latest_user = UserAuthModel.objects.latest('id') # retrieve the lastest registered user id start_user_id = latest_user.id + 1 # the beginning user id for creating end_user_id = latest_user.id + num # the end user id for creating user_id_list = [i for i in range(start_user_id, end_user_id + 1)] # user id list for creating raw_passwords = generate_cdkey(num, pwd_length, False) # generating passwords Thread(target=batch_create_user, args=(user_id_list, raw_passwords)).start() # make a thread to perform this time-consuming task user_password_list = list(map(list, zip(*[user_id_list, raw_passwords]))) # return the user id and password immediately without letting front user waiting so …