Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error when I push my project django to heroku
I want to deploying my project in heroku so I run heroku login heroku create heroku git:remote -a frozen-ravine-47377 heroku config:set DISABLE_COLLECTSTATIC=1 it's done and when i run git push heroku master I got error: $ git push heroku master Enumerating objects: 278, done. Counting objects: 100% (278/278), done. Delta compression using up to 4 threads Compressing objects: 100% (272/272), done. Writing objects: 100% (278/278), 694.38 KiB | 5.99 MiB/s, done. Total 278 (delta 126), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.8/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python … -
How to check mime type for urls without extension in django
I am trying to find mime type of video urls without extension- I am using mimetypes.guess_type(video_url) for finding mime type if video url has extension .mp4 then I am getting a response video/mp4 otherwise it's returning null. is there a way to find mime type of a video url without extension ? -
How should i make DetailView in Django, gives 404
in file "views.py" i added next code: from django.views.generic import DetailView class NewsDetailView(DetailView): model = Articles template_name = "news/details_view.html" context_object_name = 'article' then in the file urls.py I added to urlpatterns next: path('<int:pk>', views.NewsDetailView.as_view(), name="news_detail"), and created the template "details_view.html". When i write to browser: http://127.0.0.1:8000/news/1 it gives 404 error 404 error in DetailView -
Serving Django static admin files with debug off in Elastic Beanstalk
Per other posts on this subject, I followed the advice at https://bestprogrammingblogs.blogspot.com/2021/03/django-static-files-not-working-when-debug-is-false.html to serve static files when debug is false. The site advises to make changes to Settings and URLs respectively STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in URLs re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), For some reason, my local admin works but the AWS admin site does not. Do I need to tune anything on the AWS side to get this working? My environment variables don't explicitly have any static settings at the moment. -
Bootstap DataTable showing No matching records found Django
I am developing a project in Django where users can share files. I retrieve data(files) from the database and show it in a table on the template and use bootstrap DataTable to implement search functionality in my table But when I search any record from DataTable it shows me No matching records found. Bootstrap CSS CDN <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css"> Javascript CDN <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script> Tamplate <table id="datatable" class="table table-striped table-bordered" style="width:100%"> <thead style="background-color : #607d8b;"> <tr> <th>S.No</th> <th>Uploading Date</th> <th>Branch</th> <th>Subject</th> <th>Download Notes</th> <th>File Type</th> <th>Description</th> <th>Status</th> <th>Action</th> </tr> </th -
Django radio button values in views
I'm using Radio buttons in django forms to record gender fields of object Person, as below. Person Model class Person(models.Model): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) gender = models.CharField(choices=GENDER, null=True, blank=True, max_length=30) My PersonForm class PersonForm(forms.ModelForm): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") email= forms.CharField(label="Email") gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect(),) class Meta: model = Client fields = ['first_name', 'last_name','email','gender'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(PersonForm, self).clean() return cleaned_data Then my create_person_view(() def create_person_view(request): if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): form.save(): return render(request, 'person/view_persons.html') else: form = PersonForm() return render(request, "person/create_person.html", {"person_form": form}) Now, I save the form and saves fine. The problem comes in when getting the saved data from database and passing to templates. Specifically when I do Gender: {{person.gender}} It gives: Gender: <django.forms.fields.ChoiceField object at 0x7fd82ae866a0> I wanna display the real value of gender. Any help? Will be really appreciated. -
How to modify a Django Model field on `.save()` whose value depends on the incoming changes?
I have fields in multiple related models whose values are fully derived from other fields both in the model being saved and from fields in related models. I wanted to automate their value maintenance so that they are always current/valid, so I wrote a base class that each model inherits from. It overrides the .save() and .delete(). It pretty much works except for when multiple updates are triggered via changes to a through model of a M:M relationship. So for example, I have a test that creates 2 through model records, which triggers updates to a model named Infusate: glu_t = Tracer.objects.create(compound=glu) c16_t = Tracer.objects.create(compound=c16) io = Infusate.objects.create(short_name="ti") InfusateTracer.objects.create(infusate=io, tracer=glu_t, concentration=1.0) InfusateTracer.objects.create(infusate=io, tracer=c16_t, concentration=2.0) print(f"Name: {infusate.name}") Infusate.objects.get(name="ti{C16:0-[5,6-13C5,17O1];glucose-[2,3-13C5,4-17O1]}") The save() override looks like this: def save(self, *args, **kwargs): # Set the changed value triggering this update so that the derived value of the automatically updated field reflects the new values: super().save(*args, **kwargs) # Update the fields that change due to the above change (if any) self.update_decorated_fields() # Note, I cannot call save again because I get a duplicate exception: # super().save(*args, **kwargs) # Percolate changes up to the parents (if any) self.call_parent_updaters() The automatically maintained field updates are performed here. Note … -
Facing relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... issue. Can anybody help me?
Recently, I'm working with my Django Portfolio and after successfully deploying on Heroku I faced this error LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... So, this is how complete error is looking like Request Method: GET Request URL: https://shubhajeet-pradhan.herokuapp.com/ Django Version: 3.0.8 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shubhajeet_portfolio', 'base.apps.BaseConfig', 'crispy_forms', 'django_filters', 'ckeditor', 'ckeditor_uploader', 'storages', 'cloudinary_storage'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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') Template error: In template /app/base/templates/base/index.html, error at line 171 relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... ^ 161 : </div> 162 : </section> 163 : 164 : <section class="s1"> 165 : <div class="main-container"> 166 : <div class="greeting-wrapper"> 167 : <h3 style="text-align: center;">Projects</h3> 168 : <div class="blog-wrapper"> 169 : {% include 'base/navbar_blog.html' %} 170 : <div class="post-wrapper"> 171 : {% for post in posts %} 172 : <div> 173 : <div class="post"> 174 : <img class="thumbnail" src="{{post.thumbnail.url}}"> 175 : <div class="post-preview"> 176 : <h6 class="post-title">{{post.headline}}</h6> 177 : <p class="post-intro">{{post.sub_headline}}</p> 178 : <a href="{% url 'post' post.slug %}">Read More</a> 179 : </div> 180 : </div> 181 : </div> Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception … -
drf-spectacular define request schema as JSON Array (like Serializer(many=True))
Is it possible to define "many" serializer schema in drf-spectacular? The request should take this data (JSONArray): MonthlyIncomeSerializer(many=True) Which is a list of objects/dictionaries: [ {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, ] I tried: class PartialDTIPrenajomView(APIView): @extend_schema(parameters=[MonthlyIncomeSerializer(many=True)]) def post(self, request, **kwargs): which doesn't render anything in Swagger. -
Django/Docker: web container not up-to-date code
I use Django docker app and do not manage to apply code update to my web container. I've tried to delete all containers (docker rm -f ID ; docker system prune) and images (docker rmi -f ID ; docker image prune) related to my app and re-build with docker-compose -f docker-comose.preprod.yml build Then I run docker-compose -f docker-comose.preprod.yml up but for some reasons when I connect to my web running container (docker exec -it web sh) and read my updated files, I observe that update are not applied... How should I do to make my update applied? -
Django get count of related objects with value and add it to an annotation
If I want to annotate the number of related objects to each parent object, I would do this: Agent.objects.annotate(deal_count=Count('deal')) If my Deal objects have a closed boolean, how would I annotate the number of deals marked as closed? -
designating/connecting a model to a user - django
Im trying to make a social media site and wanted to connect a user to work experience. My current form is from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterForm(UserCreationForm): it takes in regular registration parameters like email, name, etc. If i was to make a several other models in the models.py does user = models.OneToOneField(User, on_delete=models.CASCADE) act as a connection? I want to connect several models to a certain user, so im assuming i'd have to drop one to one and instead use foreign key to reference the forms. Or is there a better approach to connecting a user with several other models along with ability to edit profiles -
How to use formset to get data from localstorage - DJANGO
i want to get data from local storage (because i don't use database), i use form NOT MODALS. views.py : def homepage(request): form_class = Audio_store form = form_class(request.POST or None) if request.method == "POST": form = Audio_store(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file1(request.FILES['password']) handle_uploaded_file(request.FILES['audio']) return render(request, "homepage.html", {'form': form}) return render(request, "homepage.html", {'form': form}) def song(request): songmp3 = formset_factory(Audio_store) if request.method == 'POST': formset = songmp3(request.POST, request.FILES) if formset.is_valid(): audiomp3 = formset.get.context('audio') pass else: formset = songmp3() return render(request, 'homepage.html', {'formset': formset}) form.py : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) can i use formset to get data from local storage? -
How do I iterate every item in a Django field using the <input type="select">?
I am a newbie in Django and I followed a video and used class Meta in creating the Django form. I wanted to modify the way the fields appear using HTML. Here is my code for Form: class AddForum(forms.ModelForm): class Meta: model = Forum fields = '__all__' labels = { 'post_title': 'Title of your post:', 'post_body': 'Content of your post:', 'author': 'Author:', 'forum_image': 'Attach image:', } def __init__(self, *args, **kwargs): super(AddForum, self).__init__(*args, **kwargs) self.fields['forum_image'].required = False I learned how to use <input> to add the post_title: <input class="for_post_title" type="text" name="post_title" placeholder="Forum Title"> like so. However, the author field as shown in Form must be entered using the dropdown menu. How should I iterate every existing author in the Django database and have it shown using the <select> element? -
Not able to pass post values from views.py to index.html in django
I am trying to show the form data received from the POST request on an HTML table. I have used JavaScript fetch API to submit the form and fetch the data in views.py . I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) context={"options_value":options_value, "value":value} return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </form> <table style="display: table" id="table"> <tbody> <tr> <th scope="row">ProfileUID :</th> <td>{{options_value}}</td> </tr> <tr> <th scope="row">First Nane :</th> <td>{{value}}</td> </tr> </tbody> </table> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val … -
django rendering a search result based on which submit button
when i try to search from the navbar i want a simple query to execute based on an input type="submit" and name="searchInput" when i submit the second form from the searchPage i want a different kind of query to happen and render me the searchPage with the data in it however it keeps redirecting me to the home Page def home(request) : q = request.GET.get('searchInput') if q!=-1: offres = Offre.objects.filter( Q(title__icontains=q) | Q(user__username__icontains=q) | Q(description__icontains=q) | Q(wilaya__name__icontains=q) ) context = { 'offres': offres, } return render(request,'searchPage.html',context) return render(request,'index.html',{}) def is_valid_query_parameter(parameter): return (parameter!='' and parameter is not None) def search(request) : if request.GET['submit'] == 'searchInput': q = request.GET.get('searchInput') if request.GET.get('searchInput') !=None else '' offres = Offre.objects.filter( Q(title__icontains=q)| Q(user__username__icontains=q)| Q(description__icontains=q)| Q(wilaya__name__icontains=q)| Q(category__value=q) ) context = { 'offres':offres, } return render(request,'searchPage.html',context) wilaya = request.GET.get('wilaya') hotel = request.GET.get('hotel') house = request.GET.get('house') land =request.GET.get('land') nbedrooms = request.GET.get('bedrooms') nbathrooms = request.GET.get('bathrooms') minPrice = request.GET.get('minPrice') maxPrice = request.GET.get('minPrice') wifi = request.GET.get('wifi') kitchen = request.GET.get('kitchen') furniture = request.GET.get('furniture') # mustInclude = {'wifi' : wifi, # 'kitchen' : kitchen, # 'furniture' :furniture } # excludeList = [] qs = Offre.objects.all() if is_valid_query_parameter(wilaya) : qs.filter(wilaya__number = wilaya) if not is_valid_query_parameter(hotel) : qs.exclude(category__value = 'hotel' ) if not is_valid_query_parameter(house) : qs.exclude(category__value … -
Django. Star rating multiple form displayed in a grid view not working
I've got a little problem. I have a page that is used to rate ski resorts. They are displayed in a grid view and each resort has a star rating form beneath. The problem is that only the first item in the grid can be rated. I tried to assign each form an unique id but that didn't work. Here is the code: class AddRatingForm(forms.ModelForm): class Meta: model = ResortUserRating fields = '__all__' widgets = { 'resort_rating': forms.RadioSelect() } def __init__(self, pk, *args, **kwargs): super(AddRatingForm, self).__init__(*args, **kwargs) self.pk = pk self.fields['user'].initial = self.pk def clean(self): return self.cleaned_data {% for resort in dashboard_resorts %} <div class = "grid-item"> {% if resort.img %} <img class="card-img-top" src="{{resort.img.url}}" alt ="Card image cap" height="300px" width="380px"> {% endif %} <p> <b>{{resort.name|upper}} </b></p> <p> <b>{{resort.id|upper}} </b></p> <form method="post" action = "{% url 'aplicatie2:rating' %}"> {% csrf_token %} <input type = "hidden" name = "user" value = "{{user.id}}"> <input type = "hidden" name = "resorts" value = " {{resort.id}}"> <div class="rate"> <input type="radio" name="resort_rating" id="rating1" value="1" required /><label for="rating1" title="1"> </label> <input type="radio" name="resort_rating" id="rating2" value="2" required /><label for="rating2" title="2"> </label> <input type="radio" name="resort_rating" id="rating3" value="3" required /><label for="rating3" title="3"> </label> <input type="radio" name="resort_rating" id="rating4" value="4" required /><label … -
django submit multiple forms
have concocted the following so far. pretty sure its sloppy code, but its meant for some crude maintenance and seems to work up to the point i would like it to work. point is i get a long list of forms, i can use Ajax to select them them all or assign them all to the category all at once, that is exactly what i want. what i can not figure out however is to submit all these forms in one go, the code as is works that i can submit 1. but just like the select all and categorize all code, after selecting those i also would like to SUBMIT ALL <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('blockbutton'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } </script> <script language="javascript"> function setDropDown() { var index_name = document.getElementsByName('ForceSelection')[0].selectedIndex; var others = document.getElementsByName('Qualifications'); for (i = 0; i < others.length; i++) others[i].selectedIndex = index_name; } </script> <input type="checkbox" onClick="toggle(this)" /> Toggle All<br/> <select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();"> <option value="" selected="selected">Select Category</option> {% for category in categories %} <optgroup label="{{ category.name }}"> {% for item in category.subcategory_set.all %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </optgroup> {% … -
how to add slug argument to url in django?
i want to add slug in url using django like this <a href="{% url 'tutorials:tutorial' topic.tutorial_category.slug topic.tutorial_topic_category.slug topic.slug %} </a> i dont really know how to pass in triple slug in the url for example: i want to access the programming > html > introduction-to-html like this http://127.0.0.1:8000/tutorial/programming/html/introduction-to-html error Reverse for 'tutorial' with arguments '('', 'html', 'introduction-to-html')' not found. 1 pattern(s) tried: ['tutorial/(?P<main_category_slug>[^/]+)/(?P<topic_category_slug>[^/]+)/(?P<tutorial_slug>[^/]+)$'] topic.html {% for topic in topic %} <a href="{% url 'tutorials:tutorial' topic.tutorial_category.slug topic.tutorial_topic_category.slug topic.slug %}">{{topic.title}} - Start Now</a> {% endfor %} views.py def tutorial(request, main_category_slug, topic_category_slug, tutorial_slug): tutorial_category = TutorialCategory.objects.get(slug=main_category_slug) tutorial_topic_category = TutorialTopicCategory.objects.get(slug=topic_category_slug) topic = Topic.objects.filter(tutorial_topic_category=tutorial_topic_category) tutorial = Topic.objects.get(slug=tutorial_slug) # Getting all topics context = { 'topic': topic, 'tutorial':tutotial, } return render(request, 'tutorials/tutorial.html', context) urls.py path("<slug>", views.tutorial_topic_category, name='tutorial-topic-category'), path("<slug:main_category_slug>/<slug:topic_category_slug>", views.topic, name='topic'), path("<main_category_slug>/<topic_category_slug>/<tutorial_slug>", views.tutorial, name='tutorial'), `` -
How to quickly reset Django DB after changes?
I'm often experimenting around creating different models, changing relations and so forth. This usually happens when starting a new project. At this phase I do not want to create any migrations but instead just get the thing up and running. So i very often do this: rm db.sqlite3 rm -r project/apps/app/migrations/* python manage.py makemigrations app python manage.py migrate app python manage.py createsuperuser bla bla Is there any way to have this "reset" function more quickly? I frustratingly found out, that django does not allow superusers to be created by a shell script. Is there any way to purge the db without removing the users? How do you do this? -
How to send data with Url Django
I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem Image Error View.py def Detail_pem(request, idor): print(idor) return render(request, 'store/detail.html' ) pemby.html <!-- <a href="{% url 'Detail_pem' %}"><button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </a> --> <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> <a href="{% url 'Detail_pem' idor=order.id %}"></a> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> --> <script> var id_order = document.getElementsByClassName('id_order') for (i = 0; i < id_order.length; i++) { id_order[i].addEventListener('click', function(){ var orid = this.dataset.product var ornm = this.dataset.act console.log('orid :', orid) console.log('ornm :', ornm) window.location.href = "{% url 'Detail_pem' %}" }) } urls.py path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'), -
Password encryption in Django's model
I hope you are doing fine, I am currently working on a Django project and it's my first one so I have found lots of problems which I am fixing one by one, but I've really got stuck with this one. It's about Django's password encryption in the database records, it simply doesn't encrypt the password for all the users except the admin. I hope that u can help me and thank you for your time :D models.py from django.db import models from django.db.models import Model from passlib.hash import pbkdf2_sha256 from django.utils.translation import gettext_lazy as _ from .manager import * # Create your models here. class User(Model): id = models.AutoField(primary_key=True, unique=True) email = models.EmailField( _("email"),max_length = 254 ,null=False) password = models.CharField(max_length= 255, null=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects=CustomUserManager() USERNAME_FIELD="email" REQUIRED_FIELDS= ["password"] class Meta: abstract = True verbose_name = _("user") verbose_name_plural = _("users") def __str__(self): return self.first_name + " " + self.last_name def getID(self): return self.id def getEmail(self): return self.email def getPass(self): return self.password def getFirstName(self): return self.first_name def getLastName(self): return self.last_name def checkIfSuperUser(self): return self.is_superuser def checkIfStaff(self): return self.is_staff def checkIfActif(self): return self.is_active def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password) … -
AttributeError: module 'collections' has no attribute 'Iterator' python 3.10 django 2.0
Hello its a clone project but when ı try "python manage.py makemigrations" ım getting this error how can ı fix it? requirements django==2.0 django-ckeditor==5.4.0 django-cleanup==2.1.0 django-crispy-forms==1.7.2 django-js-asset==1.0.0 this error -
Convert a nested dictionary into list of tuples like (date,value)
I have a dict like this: {'2022':{'01':{'20':55,'25':80,'30':70},'08':{'04':14,'10':18}}} and I want convert it to list of tuples or lists like this: [("2022-01-20",55),("2022-01-25",80),("2022-01-30",70),("2022-08-04",14),...] The keys of dict are as year,month and day In other words, the keys must be converted to date -
I want to get different id of multiple select boxes after click on add button in ajax and using POST method send those value in django
When I click on add, then it will be adding and I'm getting same values of select and input boxes but I want the different id's every time for ajax call and change the value dynamically and send those values in django. I have tried 1 solution but after applying that my add functionality stop working. I have tried multiple solution and have been working on it for 2-3 weeks, but I didn't get what I want. $(document).ready(function() { var maxField = 10; //Input fields increment limitation var addButton = $('.add_button'); //Add button selector var wrapper = $('.field_wrapper'); //Input field wrapper var fieldHTML = '<section class="row"><div class="col-md-3 mt-2"><label for="CustomerCity" class="">Select Product</label><select class="form-control selectitem" name="item[]" id="selectitem" required><option selected>Select Item</option></select></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Unit Price</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Unit Price" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Quantity</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Quantity" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Tax Amount</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Tax Amount" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Extended Total</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Extended Total" required></div><div class="col-md-1 mt-2"><a href="javascript:void(0);" class="remove_button btn btn-danger mt-4 p-2 form-control">Delete</a></div></section>'; //New input field html var x = 1; //Initial field counter is 1 //Once add button is clicked $(addButton).click(function() { //Check maximum number …