Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't make drf router work in a certain way
router = BulkRouter() router.register(r'', InventoryViewSet, basename='inventory') router.register(r'temporary/items', TemporaryInventoryViewSet, basename='temporary-inventory') this is part of my urls.py file the thing is I want to register route like this r'temporary' but it returns detail: not found in postman. but whenever I request "temporary/pk", I get desired item. The problem is, I can't make route "temporary" list all the objects. ('temporary/items' list all objects just fine, and 'temporary/items/pk' works great as well) I wonder what should I change to get the desired output -
Pagination button not highlighting the current page
So I'm trying to make a button which highlights as active when the page is the same as page number, but it does not work, It only highlights page 1, When I go to page 2 then page 1 is still highlighed, index function handles the page I'm talking about. views.py from django.shortcuts import render from .models import Listing from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator # Create your views here. def index(request): listings = Listing.objects.all() paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) params = {'listings':paged_listings} return render(request, 'listings/listings.html', params) def listing(request, listing_id): return render(request, 'listings/listing.html') def search(request): return render(request, 'listings/search.html') listings.html {% extends 'base.html' %} {% block content %} {% load humanize %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> Browse Listings</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ listing.photo_main.url }}" alt=""> <div class="card-img-overlay"> <h2> <span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span> </h2> </div> <div class="card-body"> <div class="listing-heading text-center"> <h4 … -
Heroku Build succeeded but "application error" {Django app}
heroku log: 2021-02-11T09:33:17.289297+00:00 app[web.1]: ModuleNotFoundError: No module named 'ivytasks' 2021-02-11T09:33:17.289983+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-02-11T09:33:17.306006+00:00 heroku[web.1]: State changed from starting to up 2021-02-11T09:33:17.429342+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Shutting down: Master 2021-02-11T09:33:17.429457+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-11T09:33:17.511921+00:00 heroku[web.1]: Process exited with status 3 2021-02-11T09:33:17.647676+00:00 heroku[web.1]: State changed from up to crashed 2021-02-11T09:33:18.929260+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ivytasks.herokuapp.com request_id=1d65f0f2-d28b-4f75-a02b-3f55c4d2ae2a fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https 2021-02-11T09:33:19.373547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ivytasks.herokuapp.com request_id=36c5d48e-3181-4cf0-9f55-655dad447156 fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https you can check the project repo link: github.com/osamamhd/ivyTasks -
Django queryset regex filter gives (3692, 'Incorrect description of a {min,max} interval)
Using Django 2.2 and MySQL database. I have a field (info) in the table containing stringified JSON data. I want to filter the data matching the regular expression. The example data in the info field is [{"type":"button","data":{"link":"https://example.com","label":"Click Here","tracking":{"id":"E3s06x","tag":"btn1"}}}] Where I want to match the expression "tracking":{"id":"(\S+)","tag":"(\S+)"} I tried using the regex filter in the Django ORM query = query.filter( info__iregex=r'"tracking":{"id":"(\S+)","tag":"(\S+)"}' ) But it is giving an error django.db.utils.OperationalError: (3692, 'Incorrect description of a {min,max} interval.') -
How to find the class index of a clicked element using javascript?
I have a tab-based website where tabs are created dynamically by cloning the default tab view, however, without knowing the index number of each element there is no way to perform logic on each tab. function search(){ window.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); alert(click) var input = document.getElementsByClassName("myTextInputID")[click].value; if (input.includes("https://www.amazon.co.uk/")) { document.getElementsByClassName("prodcont")[click].style.display = "block" document.getElementsByClassName("imgcont")[click].innerHTML = '<img class="image" src="https://www.needforseat.de/media/image/22/15/b3/MAXNOMIC-R-_LVL_Edition_Pro_YkaFLtIVOgbL1_320x463.jpg">'; document.getElementsByClassName("h1")[click].innerHTML = prodName; document.getElementsByClassName("containFORM")[click].style.backgroundColor = "white" } else { URLerror.appendChild(urlerror); var cont = document.getElementsByClassName("containFORM")[click]; cont.insertAdjacentElement("afterend", URLerror); setTimeout(function() { URLerror.remove(); }, 2000); } } }); } The only solution I've managed to come up with is by iterating through all the classes and givingibng them a name that matches their class number then whenever the tab button is clicked it returns its name. However this only works for the first 2 tabs and only goes up to an index number of one however when I add an alert for the value of clicked it shows the right value but the code runs on class index [1] which is very confusing. <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" id="default" onclick="openPage('0', this, 'red'); buttonOnclick(this.name);"></button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center">+</button> </li> </ul> </ul> </div> … -
Django-smart-select with a through model on manytomany field
I am trying to implement django-smart-selects but my situation is not covered in the Docs. They cover two scenarios - those being class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ForeignKey**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) and class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) However, my scenario looks like this - there is an additional through model; class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent, through='CountryToContinent") name = models.CharField(max_length=255) class CountryToContinent(models.Model): continent = models.ForeignKey(Continent) name = models.ForeignKey(Country) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) in django admin I have registered the Location model and I have a tabular inline with continent and country fields but as there is the through model, the chained select does not work. Any guidance or hint would be appreciated. -
Django set auto-user from context, user field not be null, JWT
In my case,I use JWT authentication, and when I create new "Post"(my model), I want automatically set author to user that request it.But when I do it, I got an error { "author": [ "This field is required." ] } I know,I'm not passing user, but I want to set it automatically, and I dont know how. I just want to know how to avoid error, because when I pass value, that allows me to go ahead, the user is set automatically from context. Serializer class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = ('title','content',author','category','likedBy') expandable_fields = { 'category': ('blogApi.CategorySerializer', {'many': True}), 'comments': ('blogApi.CommentSerializer', {'many': True}), 'likedBy': ('blogApi.LikedBySerializer', {'many': True}), } def create(self, validated_data): user = self.context['request'].user post = Post.objects.create( author=user, title=validated_data['title'], content=validated_data['content']) post.category.set(validated_data['category']) return post My create view class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated] Model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ManyToManyField(Category, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likedBy = models.ManyToManyField(User, related_name='posts', blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title and when I create -
Related_name is returning an attribute error (NoneType) from a Django Forms. I'm trying to create a dynamic filter within forms
I'm using Django 3.1.4 with Python 3.7.8. I wanted to have form field for my ProductForm to automatically filter Category and Subcategory. I followed the suggest from https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. However I keep getting an AttributeError, saying NoneType object has no attribute list. I used Django shell to see if my related_name would work. It the error keeps popping up. Here is my models.py: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField( default=slugify(name), unique=True ) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="list_of_subcategories" ) class Meta: verbose_name = 'Subcategory' verbose_name_plural = 'Subcategories' def __str__(self): return self.name Here is my forms.py: class ProductForm(ModelForm): class Meta: model = Product fields = [ 'sku', 'name', 'category', 'subcategory', 'short_description', 'description', 'price', ] def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['subcategory'].queryset = SubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields('subcategory').queryset = Category.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['category'].queryset = self.instance.category.list_of_subcategories.order_by('name') Here is my views.py: def loadSubcategory(request): category_id = request.GET.get('category') subcategories = SubCategory.objects.filter(category_id=category_id).order_by('name') return render(request, 'product/subcategory_drop_down.html', {'subcategories': subcategories}) def createProduct(request): if request.method == "POST": form = ProductForm(request.POST) if form.is_valid(): product_form = form.save(commit=False) product_form.company = request.user.company product_form.save() return redirect('dashboard:my_store') else: product_form = ProductForm() … -
Is it possible to deploy django + react app on digitalocean app platform?
I deployed my django app using digitalocean app platform(guide). I used js/jquery. And now I want to refactor my code and start using React. Is it possible to deploy django + react using app platform? -
django imagekit processors: changing Spec dependind on image dimensions
I want to generate thumbnails, whose bigger dimension is, say, 150px. Something like this: #models.py picture = models.ImageField(verbose_name=_('Image'), upload_to = "images") if image.width > image.height: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**width**=150)], format='JPEG', options={'quality': 100}) else: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**height**=150)], format='JPEG', options={'quality': 100}) Please give me an advice how to do it in django and imagekit (or, at least, other image processing package). Think that I need somehow get image field properties in my model... -
I want to change the default model of Token. I have added authentication.py file and while importing that on settings.py it shows an import error
ImportError: Could not import 'Token.custom_token.authentication.MyOwnTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'Token.custom_token'. Project Name: Token App name: custom_token Inside app-> authenticate.py file from .models import MyOwnToken class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken In settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'project_name.app_name.authentication.MyOwnTokenAuthentication', ] } In models.py class Organisation_User(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) organisation_id = models.CharField(max_length=10) organisation_name = models.CharField(max_length = 20) class MyOwnToken(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) organisation = models.OneToOneField( Organisation_User, related_name='auth_token', on_delete=models.CASCADE, verbose_name="Organisation_User" ) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(MyOwnToken, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key -
continue next codes after end of "if", no loop or while here
I have some codes about profile edit in Django views.py def account_edit(request): if not request.user.is_authenticated or request.user.is_staff or request.user.is_superuser: return redirect("/account/login") elif request.method == "POST": new_username = request.POST['username'] new_email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone_number = request.POST['phone_number'] location = request.POST['location'] if not new_username == request.user.username: if User.objects.filter(username=new_username).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.username = new_username user_edit.save() ctx = {'message_good':'aaa'} elif not new_email == request.user.email: if User.objects.filter(email=new_email).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.email = new_email user_edit.save() ctx = {'message_good':'aaa'} else: ctx = {} else: username = request.user user = get_object_or_404(User, username=username) ctx = {'user':user} return render(request, "account/account_edit.html", ctx) But after user_edit.username = new_username user_edit.save() Codes become stop, I want after finishing first if, Codes continue to work and save others -
How to reload configurations in Django (Python)
I'm new to Django. I made a URL shorter website like bitly for a test, and when users upload new URL, my program upload data to DB. The problem is that Django doesn't reload urls.py. So if users upload their URL, data is saved in DB, but urls.py doesn't reload, so 404 shows because urls.py is not reloaded, because there are no data about new URL in urls.py. I've searched in Google, I almost visited every website searched, but I couldn't find the answer. How do I reload Django configurations without turning off and on the django server? -
How can I change this code to upload multiple files in django and python?
My English is not good.. Hope you understand that.. I(beginner) use django and python, and I try to upload multiple files. finally i find working code but It is difficult to apply to the original code What am I doing wrong? (form.py, model.py is same each other) working ex code(views.py) def a(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) files = request.FILES.getlist("files") if form.is_valid(): for f in files: file_instance = Upload(file_upload=f) file_instance.save() return render(request, 'single_pages/about_me.html', {'form':form,}) # return HttpResponse(" File uploaded! ") else: form = UploadFileForm() return render(request, 'single_pages/about_me.html', {'form': form}) my Spaghetti code(views.py) def a(request, pk): if request.method == 'POST': comment_form = CommentForm(request.POST, request.FILES) files = request.FILES.getlist('files') if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() for f in files: file_instance = Comment(file_upload=f) file_instance.save() return redirect(comment.get_absolute_url()) else: return redirect(post.get_absolute_url()) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = {'content', 'file_upload', 'head_image'} files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() head_image = models.ImageField(upload_to='blog/images/%Y/%m/%d/', blank=True) file_upload = models.FileField(upload_to='blog/files/%Y/%m/%d/', blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.author}::{self.content}' def get_absolute_url(self): return f'{self.post.get_absolute_url()}#comment-{self.pk}' def get_file_name(self): return os.path.basename(self.file_upload.name) def get_file_ext(self): return self.get_file_name().split('.')[-1] What should I do.. thank … -
Django create nested model
I want to create a Model in which I can store the same models as for example in a folder there can be several folders. I tried like this: class Service(models.Model): name = models.TextField(default="") price = models.IntegerField(blank=True, null=True) def __str__(self): return self.name class ServiceType(models.Model): services_types = models.ManyToManyField(ServiceType, null=True, blank=True) services = models.ManyToManyField(Service, null=True, blank=True) name = models.TextField(default="") But it didn't work. How can this problem be solved? -
Insert data on OneToOneField using django-rest-framework
I am new to this django-rest-framework, my problem is how am I going to insert a data with one-to-one relationship in the views.py. I can do the normal way of inserting data like the one below, def post(self, request,format=None): p = Person() p.firstname = "John" p.middlename = "K" p.lastname = "Rambo" p.save() e = Employee() e.code = "emp-002" e.person_id = p.id e.save() I cannot do the approach above because I want to learn more about DRF. To give you more idea please see below : I have this model class Person(models.Model): firstname = models.CharField(max_length=150, default="") middlename = models.CharField(max_length=150, default="") lastname = models.CharField(max_length=150, default="") class Employee(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE,primary_key=True) code = models.CharField(max_length=100, default="") I have this serializer class PersonSer(serializers.ModelSerializer): class Meta: model = Person fields = ( 'id', 'firstname', 'middlename', 'lastname',) class EmployeeSer(serializers.ModelSerializer): person = PersonSer() class Meta: model = Employee fields = ('code','person') I have this view class SaveData(APIView): @transaction.atomic def post(self,request, format=None): p = PersonSer(data=request.data) if p.is_valid(): p.save() request.data['person'] = p.data['id'] request.data['code'] = "Emp-"+str(p.data['id']) """ I expect request.data now equal to { 'person' : 102, # we assume the newly created person id == 102 'code' : 'Emp-102', 'firstname' : 'John', 'middlename' : 'K.', 'lastname' : 'Rambo' } … -
How to add custom field to auth_permission model in django?
I am working with auth_permission model and to add extra fields in this model. class Permission(models.Model): name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) Extra field I wanted to add is application_id = models.ForeignKey(ApplicationTbl, db_column='application_id', on_delete=models.CASCADE, blank=True, null=False) Can someone tell the work around to add it to auth_permission model. -
Send the response to user from other file instead of views.py form DRF
I am working on DRF in which I have created multiple pythons and importing that file into views.py but when I am trying to send the response to the user from another file it is not working I understand the behind the reason but is there any way to send the response to the user from other than view.py. view.py Structure #restframework view and all from concurrent.futures import ThreadPoolExecutor import other as o call FileView(APIView): #parseclass def post(self,request): o.func(d) Other.py from rest_framework.response import Response from rest_framework.status import status from django.conf import setting def func(d): return Response({"A":"OK"}) but Response is not coming to the user end. is there any way to send a response from other.py to the user instead of getting value and then send the response from the view.py? I am also implementing multithreading in my DRF. -
ModuleNotFoundError: No module named 'Productpages'
I m working on a Django project this is my first project so i don't understand Django well I create a app called pages and add it to settings.py I add a home view to views.py And I added it to url prattens But i got this error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Productpages' from django.shortcuts import render # Create your pages here. def home(request, *args, **kwargs): return render(request, 'products.html', {}) Here is my view.py it is … -
Error while creating forms on latest django version, ModelForm has no model class specified
I'm trying to make forms models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='restaurant') name =models.CharField(max_length=500) phone =models.CharField(max_length=500) address =models.CharField(max_length=500) logo =models.ImageField(upload_to='restaurant_logo/', blank=False) def __str__(self): return self.name forms.py from django import forms from django.contrib.auth.models import User from foodtaskerapp.models import Restaurant from django.forms import ModelForm class UserForm(forms.ModelForm): class meta: model = User fields = ("username","password","first_name","last_name","email") class RestaurantForm(forms.ModelForm): class meta: model = Restaurant fields = ("name", "phone","address", "logo") I'm getting this error: ValueError at /restaurant/sign-up ModelForm has no model class specified. -
Best way for writing validation code in django
For understanding purpose I will simplify my overall design. Suppose I have a table. ___________________________________ | id | start | end | ---------------------------------- | 1 | 2021-01-12 | 2021-01-30 | ----------------------------------- | 2 | 2021-01-11 | 2021-01-14 | ----------------------------------- | 1 | 2021-01-12 | 2021-01-15 | ___________________________________ In my views.py file I queried the table and got all row with id=1. And passed it as context to my html page. class BuyTicket(generic.ListView): template_name = "movie_user/buyticket.html" model = SetMovie def get_context_data(self, **kwargs): movies = MovieMaster.objects.filter(setmovie__isnull=False) context = super().get_context_data(**kwargs) idd = self.kwargs['pk'] set_movie = SetMovie.objects.filter(id=idd) #getting all rows with specific id from above table context['data_set'] = set_movie return context I am looping over the data (context['data_set']) from my views in my buyticket.html file. <div> {% for data in data_set %} <form method="POST"> {% csrf_token %} <label>Start Date:</label> <input type="text" readonly value="{{data.start_time}}"> <label>End Date:</label> <input type="text" class="" readonly value="{{data.end_time}} "> <input type="date" class="form-control" name="datee"> <input type="submit" class="btn btn-success" value="book"> </form> {% endfor %} </div> What I want to do is add validation to my only form field. <input type="date" class="form-control" name="datee"> This is a date input and it must lie between <input type="text" readonly value="{{data.start_time}}"> <input type="text" class="" readonly value="{{data.end_time}} "> Even If … -
How to do attribute filter in django models queryset
I have one model which I inherit in two other models class KycModel(models.Model): file_name = models.TextField(blank=True, null=True) class Pan(KycModel): pan_number = models.CharField(max_length=15, null=True) class Aadhar(KycModel): aadhar_no = models.CharField(max_length=15, null=True) I have to find total objects count in Pan and Aadhar models one way I can do with: Pan.objects.count() Aadhar.objects.count() but is there any way, to get all KycModel objects and apply filter or use Count annotation. a = KycModel.objects.all() pan_to = 0 aadhar_to = 0 for i in a: if hasattr(i, "pan"): pan_to += 1 if hasattr(i, "aadhar"): aadhar_to += 1 if I loop and apply hasattr(obj, "pan")...this will work but any better solution. -
How to show all the posts of America users if user is selected America ( In CharField Choices )
I am Building a BlogApp and I am stuck on a Problem. I want to show all the Post of U.S.A if request.user is selected U.S.A in CharField There's a one attribute named 'location' it have two choices 'America' and 'Australia'. I want it to shows only 'America Posts when user selects America'. When user selects 'America' then I want to show the all posts of only users that are selected America. if user selects 'Australia' then it finds all the users which are selected 'Australia' and show the posts of Australia users. views.py def showing_post(request,user_id): profiles = get_object_or_404(Profile,user_id=user_id) you = request.user shows = 'none' show = 'none' if profiles.location == 'America': show = Profile.objects.order_by('location') elif profiles.location == 'Australia': shows = Profile.objects.order_by('location') context = {'shows':shows,'show':show,'profiles':profiles} return render(request, 'opens.html', context) models.py country = [ ('America', 'America'), ('Australia',"Australia"), ] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) location = models.CharField(max_length=30,choices=country,default='') opens.html {% if profiles.location == 'India' %} {% for p in show %} {{ p.location }} {% endfor %} {% endif %} The Problem When i check in the Page then it is showing all the users which selected the location of America and Australia, All are showing. What i am trying to do … -
How to generate 6 digits multiple OTP and insert into database at once with Django
I am generating 6 digits random OTP in my views.py and I just want to insert those many OTPs to be inserted into my Table at once using single QuerySet. Here is my code: home.html <form class="" action="" method="post"> {% csrf_token %} <div class="" style="text-align: center:"> Mobile : <input type="text" name="mobile" value=""> <input type="submit" name="submit" value="Generate OTP"> </div> </form> models.py class otpModel(models.Model): mobile = models.CharField(max_length=30, blank=False, null=True) otp = models.CharField(max_length=50, blank=False, null=True) def __str__(self): return self.mobile views.py import random from app_name.models import otpModel def registerOTP(request): if request.method == 'POST': mobile = request.POST['mobile'] for i in range(100): otp = random.randint(100000, 999999) otp = otpModel.objects.create(mobile=mobile, otp=otp) if otp: messages.info(request, 'OTP is saved!!!') return render(request, 'app_name/otp.html') else: return render(request, 'studentexams/otp.html') Here whenever I enter the Mobile number in the HTML form then only 1 OTP is inserted in the Table. Is there any solutions that I can insert multiple OTPs at a time using single QuerySet Please give the Code snippet for achieving this task to be done -
Making Django query if my class consists of a function? How do make a query which will return the sum of available_count for a particular device
class Magazine(models.Model): device = models.ForeignKey(RUDevice, on_delete=models.CASCADE, null=False, blank=False, related_name='ru_magazine', help_text="Select Device for magazine") magazine_number = models.PositiveIntegerField(_("Magazine Number"), default=0, help_text='Magazine number for selected Remote Unit') product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product_type', help_text="Select product type") max_capacity = models.PositiveIntegerField(_("Maximum Capacity"), default=0, help_text='Select Maximum Capacity') def available_count(self): /*some code*/ return available_product I have tried: Magazine.objects.filter(device='some_device').aggregate(sum=Sum('available_count()')['sum']