Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch data for my website from 3rd party website in Django
I wanted to learn, how to fetch any kind of integer value from any website (with a particular given link). suppose if I search by today's temperature in google, it shows like this: I prefer to use Django. How can I fetch the value of temperature from this page? I mean what should be the views.py look like for this? I am totally new to this type of data fetching, having zero knowledge of this, please suggest to me some tutorial link or blog if you prefer. -
get_next/prev_by after searching django
I have trouble after trying to use get_next_by_FOO/ get_previous_by_FOO after searching. For example, Search result gives 10 differences results. if I click the first, It shows information. Then I click next, it won't show the second result in 10 results, shows the next value in data. I know where is the issue In my code, contract get data from Model Contract, not from search result, that is why I click next it doesnt show the result, but I dont know to fix in views.py #def show contract information def contract_detail(request, contract_id=None): contract = get_object_or_404(Contracts, contract=contract_id) try: the_next = contract.get_next_by_created_at() except: the_next=None try: the_prev = contract.get_previous_by_created_at() except: the_prev=None context = { "contract": contract, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail.html", context) #def show list contract after seaching and pagination def list_contract(request): context = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) results= Contracts.objects.filter(lookups_contract,lookups_name).distinct() contract_posts=results CONTRACT_POSTS_PER_PAGE = 10 CONTRACT_POSTS_PER_PAGE = request.GET.get('CONTRACT_POSTS_PER_PAGE', CONTRACT_POSTS_PER_PAGE) or 10 #pagination cho query search page = request.GET.get('page', 1) contract_posts_paginator = Paginator(contract_posts, CONTRACT_POSTS_PER_PAGE) try: contract_posts = contract_posts_paginator.page(page) except PageNotAnInteger: contract_posts = contract_posts_paginator.page(CONTRACT_POSTS_PER_PAGE) except EmptyPage: contract_posts = contract_posts_paginator.page(contract_posts_paginator.num_pages) context['contract_posts'] = contract_posts return render(request, "customer.html", context) … -
Unable identify mistake in URL pattern
I have 3 apps inside django project (leadmanager) leads, frontend, accounts Everything is working fine if I dont include accounts.urls (from accounts app) in leadmanager.urls but as soon as I include accounts.urls I getting the following error (all of these apps are registered in settings.py): $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Danial Ahmed\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Danial Ahmed\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) … -
django get count of 'children' of related_name field (and do this in template?)
I am trying get the list of HQ (Head Quarter) Field Manager and count of Animal and Agent under Field Manger. Each foreign code has a related name. Models are class Fm(models.Model): hq = models.ForeignKey(Hq, on_delete=models.SET_NULL,null=True) fm = models.CharField(max_length=50) class User(AbstractBaseUser): email = models.EmailField(max_length=255,) fm = models.ForeignKey(Fm,on_delete=models.SET_NULL,related_name="agents") class Animal(models.Model): agent = models.ForeignKey(User,on_delete=models.SET_NULL,related_name="animals") farmer = models.CharField(max_length=50') View def print_table(request): fms = Fm.objects.all() context = {'fms':fms} return render(request, 'fm.html',context) Template {% for fm in fms %} <tr> <td>{{fm.hq}}</td> <td>{{fm.fm}}</td> <td>{{fm.agents.animals.all.count}}</td> (Error here) <td>{{fm.agents.all.count}}</td> </tr> {% endfor %} Expected OutPut HQ FM_Name Animal_Count Agent_Count HQ1 Any Name 10 (Not Working) 2 Current Output HQ FM_Name Animal_Count Agent_Count HQ1 Any Name 2 This is listing count of Animal but I need sum of all {% for x in fm.agents.all %} <div>{{x.animals.all.count}}</div><br> {% endfor %} Anyone Please Help Me -
How to add new Foreign Key objects in a Form in Django?
I have a blog that uses Django and currently I am building a page for creating new posts. In my Post model I have a Foreign Key field that is linked to a ImageField. When rendering the page using a generic class view, the field is displayed as a drop-down as expected, but I would like to add new thumbnails, not only selecting the existing ones, similar to the behavior of the admin page when there is a Foreign Key field, where: There is a plus sign next to the drop-down When clicked, shows a pop up where I can upload the image After uploading the image, return to the main page, where the new option is created in the drop-down How can I have a behavior similar to the admin's in my page? I tried to implement it as a widget, but the end result is very messy, as it just redirects to the admin page and I have to go back to my post creation page and reload to show the new option. Alternatively I could just replace the the Foreign Key drop-down with a field to upload a file, but I don't know how, as the foreign … -
unique constraint with objects.get_or_create
I've a unique constraint error : django.db.utils.IntegrityError: UNIQUE constraint failed: wikis_article.title this is my code: def Article_Edit(request, articleid): article = Article.objects.get(pk = articleid) form = EditForm(instance=article) if request.method == "POST": article_form = CreateForm(request.POST) if article_form.is_valid(): Article.objects.get_or_create( title=article_form.cleaned_data["title"], content=article_form.cleaned_data["content"], ) messages.success(request, 'article successfully added') return HttpResponseRedirect(reverse("Article_List")) return render(request, 'wikis/article_create.html', {"form": form}) with my model: class Article(models.Model): title = models.CharField( max_length=512, null=False, blank=False, unique=True,verbose_name=_("title")) content = MarkdownxField(blank=True, verbose_name=_("article contents")) created = models.DateTimeField( auto_now_add=True, verbose_name=_("created"), ) modified = models.DateTimeField( auto_now=True, verbose_name=_("modified"), help_text=_("Article properties last modified"), ) I know that if I delete my unique constraint on tile, I think this will work. But I need to maintain this constraint. I don't understand which get_or_create does not see that I M on editing an existing instance. thanks for helping -
django-tenants example 404 error, run through the tutorial video twice and keep getting the same error
This is from the tutorial video from Tom - I ran through it twice : http://t1.dtdemo.local:8000/ Request Method: GET Request URL: http://t1.dtdemo.local:8000/ Raised by: customers.views.TenantView http://t1.dtdemo.local:8000/admin Page not found (404) Request Method: GET Request URL: http://t1.dtdemo.local:8000/admin http://t1.dtdemo.local:8000/admin/ Page not found (404) Request Method: GET Request URL: http://t1.dtdemo.local:8000/admin/ Raised by: django.contrib.admin.sites.index Settings.py """ Django settings for dtdemo2 project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'customers' ] TENANT_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'myclientapp' ] INSTALLED_APPS=list(set(SHARED_APPS + TENANT_APPS)) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', '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', ] ROOT_URLCONF = 'dtdemo2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': … -
How to change message when save model in django?
When save model on browser. django will showing message "The ...... was added successfully.".I tried to change message at get_queryset() it look like too complicate. I want to know the best way how to change this message? and Where is to change? -
Django-filter field not showing after adding lookup expressions - django-filter lib
I'm trying to implement a search field for my website, I decide to use django-filter I was able to create a search field and search the records by typing the exact record name in the search field. (default it provides exact field lookup) And it worked fine. Then I decide to add more field lookup so the search experience improves. But after adding some field lookups the search form field stopped appearing in the template. I go through the documentation couple of times and also tried to google the issue but unable to solve it. Test: By the way, hard cording the field lookups(icontains) to the queryset worked. And also the query set works fine. So here's my context processor which handles the search field(search field is in the base.html) context_processor.py from django.db.models import Prefetch from django.shortcuts import render from store.filters import ProductFilter from store.models import Product, ProductImage, Wishlist def include_search_bar(request): queryset = Product.objects.order_by('name').prefetch_related( Prefetch( 'productimage_set', ProductImage.objects.filter(place='Main Product Image'), to_attr='main_image' ), ) product_filter = ProductFilter(request.GET, queryset=queryset) products = product_filter.qs context = { 'product_filter': product_filter, 'products': products, } return context filters.py import django_filters from .models import Product class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = { 'name':['icontains'] } # fields … -
Django + Jinja/css vs Django + React
I'm trying to develop a simple neat website using Django with a second page that has a python application. If you use React to cover the front end, can you avoid having to use the combination of Jinja/css? Thanks, Sad_man -
Modify login view in django crispy form
I am doing authentication using crispy forms in Django. I would like to modify labels username and password in login view, but I can't find any solution to do it (I think that I have to create my own login form, but maybe it is possible to extend it). urls.py path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] login.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Login {{ form|crispy}} </legend> </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-info">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Don't have an account? <a class="ml-2" href="{% url 'register' %}">Register</a> </small> </div> </div> {% endblock content %} -
Page not found (404) error while searching through search page Raised by: blog.views.blogpost
i am unable to search and get 404 error same problem occur in sitemap views for creating static xml file, it does not return the url for static file and now have this problem with search as it is unable to find search .html gives this Page not found (404) error while searching through search page Raised by: blog.views.blogpost error. my Search Views myposts = Blogpost.objects.all() query = request.GET['search'] if len(query)>78: myposts = Blogpost.objects.none() else: post_title = Blogpost.objects.filter(Q(title__icontains=query)) posts_content = Blogpost.objects.filter(Q(content__icontains=query)) posts_slug = Blogpost.objects.filter(Q(slug__icontains=query)) myposts = post_title | posts_content | posts_slug if myposts.count() == 0: messages.warning(request, "No search results found. Please enter again.") context = {'myposts': myposts,'query':query} return render(request, 'blog/search.html', context) My url urlpatterns = [ path('', views.index, name='bloglist'), path('<slug:post>/', views.blogpost, name='blogpost'), path("contact/", views.contact, name="contact"), path("search/", views.search, name="search") ] My Search.html {% for post in myposts %} <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <h3 class="mb-0"><a href="{{ post.get_absolute_url }}">{{post.title}}</a></h3> <div class="mb-1 text-muted"></div> <strong class="d-inline-block mb-2 text-primary"><a>{{post.author}} | {{post.created_on}}</a></strong> <p class="card-text mb-auto">{{post.content|safe}}</p> <a href="{{ post.get_absolute_url }}" class="stretched-link">Continue reading</a> </div> Project urls from blog.sitemaps import StaticViewsSitemap from blog.sitemaps import BlogSitemap sitemaps ={ 'blogpost': BlogSitemap(), 'static': StaticViewsSitemap(), } urlpatterns = [ … -
Django: use model_formfactory with @property model field
I have this Django model: # models.py class MyModel(models.model): _foo = models.CharField(max_length=200) foo_link = models.Charfield(max_length=250) @property def foo(self): return self._foo @foo.setter def foo(self, value): self._foo = value self.foo_link = "https://foobar.com/{}".format(value) I want foo to be a property, so that foo_link changes accordingly whenever I change it. So far, this works as expected and as described in tutorials such as this one. Except when I try to use modelform_factory with this property: # views.py from django.forms import modelform_factory def edit_foo(request, foo_id): mymodel = get_object_or_404(MyModel, pk=foo_id) FooForm = modelform_factory(MyModel, fields=("foo",)) if request.method == "POST": form = FooForm(request.POST, instance=mymodel) if form.is_valid(): form.save() else: form = FooForm(instance=mymodel) return render(request, "myapp/editfoo.html", {"form": form}) It fails with the error django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel. What did I do wrong here? -
MongoDB database. Error "Select a valid choice. That choice is not one of the available choices."
I have installed MongoDB in my Django project. Because is the first time I use Mongo, I decided to try how it works and I created a simple program in order to store data ( price and quantity in my case). The project is called "exchange" and it has 2 folders: exchange and app. This is the file models.py from 'app' folder: from django.db import models from djongo.models.fields import ObjectIdField, Field from django.contrib.auth.models import User class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) price = models.FloatField() quantity = models.FloatField() #ips = models.Field(default=[]) #subprofiles = models.Field(default={}) This is the file admin.py from django.contrib import admin from .models import * admin.site.register(Profile) admin.site.register(Order) This is how I set the database in the file settings.py of exchange folder DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'engine', } } So after made the migrations and create the superuser, I run the server, I went in the section Admin, than in Profile, and I created a profile choosing the only option available (my superuser). At this point I created an order in the Orders section: so I chose in the "profile" field … -
Custom fields in user model Django
I am using normal User model in Django to save my users. I would like to add first_name and last_name field, but I don't know how to extend my model and make it work. First and last name should be added in in register form (I use crispy forms). register view if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() # save user to database username = form.cleaned_data.get('username') messages.success(request, f"User {username} succesfully created! You can login now!") return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) register form def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) self.fields['password1'].label = "Hasło" self.fields['password2'].label = "Powtórz hasło" email = forms.EmailField() name = forms.CharField( label="Imię", required=True, max_length=30, ) surname = forms.CharField( label="Nazwisko", required=True, max_length=30, ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'name', 'surname'] labels = { 'username': 'Nazwa użytkownika', } -
How to pass full data as it is without getting converted via GET?
I'm trying to manipulate my form's action via js with the following code: form.action = "{% url 'search.html' phrase='developer' %}" The problem is, it converts my data to weird signs instead of passing it as it is. http://localhost:8000/%7B%%20url%20'search.html'%20phrase='developer'%20%%7D? How can I avoid this convertion ? -
Getting Error AttributeError: type object 'Student' has no attribute 'Objects'
i am getting error AttributeError: type object 'Student' has no attribute 'Objects' when i try to run 'python manage.py makemigrations' in django Here is my models.py file #-*- coding: utf-8 -*- from django.db import models class Subject(models.Model): subject_name = models.CharField(max_length=200) chapter_title = models.CharField(max_length=200) class Student(models.Model): student_name = models.CharField(max_length=254) student_teacher = models.ManyToManyField(Subject) my Serializers.py file # -*- coding: utf-8 -*- from rest_framework import serializers from .models import Subject, Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' my views.py File # -*- coding: utf-8 -*- from django.shortcuts import render from rest_framework import viewsets from .serializers import StudentSerializer, SubjectSerializer from .models import Subject, Student class StudentViewSet(viewsets.ModelViewSet): queryset = Student.Objects.all().order_by('student_name') serializer_class = StudentSerializer class SubjectViewSet(viewsets.ModelViewSet): queryset = Subject.Objects.all().order_by('subject_name') serializer_class = SubjectSerializer I have similar application but i am not getting error there. Please help -
Django server-side and client-side pagination with Datatables
This might sound like a stupid question so apologies in case I'm wasting your time. I have a tons or results coming from my data in my Django project. It's a table with many columns and almost 4000 rows. I am using Datatables for pagination, filtering, horizontal scrolling, sorting the columns. Client-side I am also using django-filter for querying the database. My problem is that the loading of the initial data (non filtered via django-filter) takes a lot of time. Shall I implement pagination on the client-side? If so, how does this work with Datatables? Will Datatables paginate/display only the (first page of) paginated data coming from the server-side query? Is there a way for the two to work together? Thanks. -
How to pass parameter to javascript from Django template while using for loop
I am creating a quiz application using django. I am facing a problem in sending paramter to my javascript function from django template. Html Code. {% for qts in page %} <input type="button" id ="btn-1" name="grp" value="{{qts.opt1}}" class="btn btn-outline-primary mt-3" onclick = "check(this,{{qts.answer}})"> Javascript Code function check(btn,answer) { var user_ans_id = btn.id; var user_ans = document.getElementById(user_ans_id).value; console.log(answer); } Is there any other solution -
passing instance to Django modal form
I want to do edit on a modal pop up form, edit is working but cant see the existing instance, how I can do it? any help is appreciated. Here I have passed the form as below class DomainListView(ListView): model = Domain template_name = 'super_admin/domain_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = DomainEditForm(self.request.POST or None) context['form'] = form return context and the template is as follows <div class="modal fade" id="domain-edit-{{ item.pk }}"> <div class="modal-dialog" role="document"> <form class="form-valide" action="{% url 'domain_edit' item.pk %}" method="POST" id="" enctype="multipart/form-data"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Edit Domain </h5> <button type="button" class="close" data-dismiss="modal"><span>&times;</span> </button> </div> <div class="modal-body"> <div class="basic-form"> <div class="form-group"> {% csrf_token %} {{ form.errors }} {{ form | crispy }} </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">submit</button> </div> </div> </form> </div> </div> this is inside for loop along with list items, I tried to fetch the instance as follows in get context data override, but it gives key error def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = get_object_or_404(Domain, kwargs={'pk': self.kwargs['pk']}) form = DomainEditForm(self.request.POST or None, instance=obj) context['form'] = form return context -
Page not found (404) djano project
Here is my code i tried it but i get a error 'accounts/register' could not be found index.html {% load static %} {% static "images" as baseUrl %} <!doctype html> <!-- Website Template by freewebsitetemplates.com --> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mustache Enthusiast</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/mobile.css' %}" media="screen and (max-width : 568px)"> <script type="text/javascript" src="{% static 'js/mobile.js' %}"></script> </head> <body> <div id="header"> <a href="{% static 'index.html' %}" class="logo"> <img src="{% static 'images/logo.jpg' %}" alt=""> </a> <ul id="navigation"> <li class="selected"> <a href="{% static 'index.html' %}">home</a> </li> <li> <a href="{% static 'about.html' %}">about</a> </li> <li> <a href="{% static 'accounts/register' %}">register</a> </li> <li> <a href="{% static 'contact.html' %}">contact</a> </li> </ul> </div> <div id="body"> <div id="featured"> <img src="{% static 'images/the-beacon.jpg' %}" alt=""> <div> <h2>the beacon to all mankind</h2> <span>Our website templates are created with</span> <span>inspiration, checked for quality and originality</span> <span>and meticulously sliced and coded.</span> <a href="{% static 'blog-single-post.html' %}" class="more">read more</a> </div> </div> <ul> {% for cate in categos %} <li> <a href="{% static 'gallery.html' %}"> <img src="{{cate.img.url}}" alt="" style="width:240px;height:200px;"> <span>{{cate.name}}</span> </a> </li> {% endfor %} </ul> </div> </body> </html> register.html {% load static%} <!doctype html> <!-- Website Template by … -
Condition setting problem over custom build decorator in Django
I am trying to make a custom build decorator in Django. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) def __str__(self): return self.username class Inspector(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nid = models.IntegerField(blank=False, unique=True) inspector_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name Now I want to build a decorator that will allow the user to pass by satisfying the following 3 conditions: user is active and logged in is_Inspector value is True inspector_varified's value is also True (inspector_varified is in under Inspector class) my decorators.py: def inspector_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='app2:request_login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_Inspector, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator It is maintaining conditions 1 & 2, but condition-3 is not satisfied by it. How can I code for it also? -
AttributeError: 'list' object has no attribute 'order_by' Python
I was trying to combine two queryset objects data by itertools chain python predefine function and sorting this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'. If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. try: qs = ChatMessage.objects.filter( Q(from_user=user, to_user=to_user) | Q(from_user=to_user, to_user=user) ) except: raise ValidationError({"message":"bad request"}) data = UserChatMessageSerializer(qs, many=True, context={'request': request}).data # qs.update(read_status=True) for record in data: data1 = record['conversation'] data2 = record['files'] print(data2) from itertools import chain all_results = list(chain(data1,data2)).order_by('created_on') -
Django DayArchiveview is not detected in urls.py
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/01 the views will be displayed, http://127.0.0.1:8000/blog/archive/2021/01/07 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<int:month>/', views.PostMonthArchiveView.as_view(month_format='%m'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' … -
Django + html/css/Jinja vs Django + React
I'm trying to develop a simple neat website with a second page that has a python application. So far, I'm using Django with html/css/Jinja to make the website. The application works fine, but I'm finding simple styling things like making a nav bar and even anchoring internal links incredibly difficult. I find the combination of Jinja with CSS overly complex, and most the time things don't work for me. Definitely a case of me needing to study more into django, but I feel it shouldn't be this difficult to get simple things to work. Opinion of jinja/css aside, if I use React to cover the front end is it possible to avoid using the jinja/css combo? Should I invest my time to struggle through the css/jinja stuff, or would React knowledge be more valuable? Thanks, Sad_man