Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django upload file godaddy hosting
I have a running django on my pc no problem with upload 1 video large file but on godaddy hosting return 413.html to my browser i setting php selector but not work my php setting my page -
Adding accept on Django model FileField
Good day SO. I found this accepted answer on how to add attrs accept for my filefield. This is how I did it on my project. model: curriculum_vitae = models.FileField(upload_to=img_path, validators=[validate_file_extension], null=True, blank=True) Forms: class SomeClass(forms.ModelForm): curriculum_vitae = forms.FileField(label=('Curriculum Vitae'),required=False, error_messages = {'invalid':("Document Files only")}, widget=forms.FileInput(attrs={'accept':'pdf/*,doc/*,docx/*,xlsx/*,xls/*'})) class Meta: ... However, on my template, my fieldfield only has All Files(*,*). Any idea what I did wrong? -
RelatedObjectDoesNotExist at / Accounts has no customer
[enter image description here][1] **strong text** [1]: https://i.stack.imgur.com/XhO71.png The problem arises while creating new users. It says related object does not exist. accounts model class Accounts(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) date_created = models.DateTimeField( verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField( verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # setting username as a key to login. Note: email can also be used in it USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] store model class Customer(models.Model): username = models.OneToOneField( Accounts, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) def __str__(self): return self.name -
How can I expose media folder in django?
I have a running django project on my server's port 8800, while I also expose a static media folder on the same server on port 8000. In this way, I would be able to view the folder/directory listing via HTTP on the web browser. To do the latter (exposing the media directory), I run the below command: python -m http.server -d "D:\media" 8000 My question is how can I incorporate doing both on the same port? Or, how can I expose the target media folder just by running the django project? Any clue or feedback will be much appreciated. Thank you very much. -
Django : Foreign Key to a choice field model
I am relatively new to Python / Django. I am trying to create a relationship between food items and the category (name) they belong: class Category(models.Model): options=( ('vegetable','vegetable'), ('fruit','fruit'), ('carbs','carbs'), ('fish','fish'), ('meat', 'meat'), ('sweet', 'sweet'), ('dairy', 'dairy'), ) name=models.CharField(max_length=10,choices=options,unique=True) def __str__(self): return self.name class Fooditem(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category,on_delete=models.CASCADE) The code above throws error when running migrate: ValueError: invalid literal for int() with base 10: 'vegetable' I created some items in the database, is it the reason? What is the best way to solve this problem? Thank you, D -
django clean_field not reading a form field
I want my code to raise an error if: User selected role=="Other" AND they left field "other_role" blank. I made a clean function, but when I try and reference the field "other_role", it always shows up as None, even when the form is filled. How can I reference another field? PS: I don't want to have to explicitly define that field again in my form class because that will mess up the order my forms are rendered. class AttendeeForm(forms.ModelForm): # birth_date = forms.DateField(widget=forms.TextInput(attrs={ # 'class':'datepicker' #})) class Meta: model = Attendee fields= ('birth_date', 'degrees','area_of_study','role','other_role','institute', 'phone_number') widgets = { 'birth_date': DateInput() } help_texts = { 'degrees': 'List your degrees. Separate with commas.', 'area_of_study': 'List your primary field of study or research. If neither are applicable, write your area of practice.', 'institute': 'Professional Affiliation. If retired, enter your most recent affiliation.' } def clean_role(self): cd = self.cleaned_data print(cd.get("other_role")) if cd['role'] == 'OTHER': if cd.get("other_role") is not False: raise forms.ValidationError("You need to specify your role if you picked 'Other'") return cd['role'] -
TypeError: AuthMiddlewareStack() missing 1 required positional argument: 'inner'
Hi I am trying to build ASGI APPLICATION but I get this error File "/home/marwan/Desktop/Gowd/gowd_project/config/routing.py", line 8, in <module> AuthMiddlewareStack( TypeError: AuthMiddlewareStack() missing 1 required positional argument: 'inner' and this is my routing.py file from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( # URLRouter([...]) # Empty for now because we don't have a consumer yet. ) ) }) -
SQL to Django Translation
This statement works in SQL, I just cannot figure out how to convert it to django. Im sure it uses prefetch_related, Prefetch, or select_related but im still having a hard time understanding those concepts. I do see that prefetch basically has to have the field under that table. My goal: Not all brands have products. All products have brands. Show my only brands with products. I was hoping to implement Brand.objects.[insert-filter-here] Model.py (appended version of actual models.py file) class Product(models.Model): brand = models.ForeignKey(Brand) class Brand(models.Model): name = models.CharField SQL SELECT DISTINCT products_brand.name FROM produts_brand INNER JOIN products_product on products_brand.id=products_product.brand_id; Its 2 tables becuase the products table has many many columns (27), I guess the other option is to just combine them. But I wanted more control over Brand objects for ease of lookup/editing. Many thanks for your help! -
What languages and frameworks are best suitable for complex applications?
I worked on a few projects with python and its web framework django and therefore became very fluent with it. The same applies to php (but without frameworks like laravel, just plain php 3rd party modules). But I found out that python/django might not be good for a lot of traffic/requests and so might abandon incoming requests. But the core of such complex applications lies in the backend: processing a lot of concurrent user requests (database queries, read and write (equal amount of read/write requests)), authentication system and safety, fast template rendering fast time to first byte . . . I know that python is a high level language and therefore might be slower but is there a better language suitable to use as the core stack for the backend (serving both mobile app and web app) being faster reliable and highly scalable? Can you give me examples for which languages and frameworks big apps like instagram, facebook, youtube and co. are using to be high performing even on high amounts -
Once set Username=None. it is not a undo able after migrations + migrate
class User(AbstractUser): name = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username= None status = models.IntegerField(null=True, blank=True, default=2) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] After migrate in this i lost username field and i cannot get this field back also check my migration file operations = [ migrations.RemoveField( model_name='user', name='username', ), ] what should i do? to get back my username field again. Thanks -
modify the field-labels in auth_views.LogInView
I'm trying to make the user log in using email instead of username, thus I have created the following register-view def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) if form.is_valid(): form.instance.username=form.cleaned_data["email"] form.save() messages.success(request, "Your account has been created!") return redirect("login") else: form = UserRegisterForm() return render(request,"users/register.html",context= {"form":form}) which seems to work fine. I have seen people create their own ModelBackEnd classes but I cant see any issues doing it this way (please let me know, if this for some reason does not work?). The problem is, using the LoginView the field says Username and I want to change the saying to Email. Is there a way to do that? -
Retry a Huey task when something fails
Hi we are using Python Huey https://pypi.org/project/huey/1.1.0/ on a django project for running our background task, we are use it as a decorator @task() on some functions. To be more precise we are importing the library the following way: from huey.contrib.djhuey import task So, on our functions, that are executed by this task, in some cases we have database connections. If for some reason this task fails, for example, today we had a database issue that the connections to the database were closing (this is an issue that we have to figure out why this connections were closing). As you may imagine the task doesn't finish it's job due to the database connection. My question is: Is there any way, that we can configure this Huey task to retry the execution. Let's say, retry 5 times with 2 seconds between each retry ? -
How do query a query without getting an empty set in Django/python?
For instance, using Django/python I have queried data from a mysql db to a variable. When the variable is printed out in the terminal I can see the data in the query set. Now I want to run a second query on the first query set that is in the variable, but it returns an empty set. I have tried many things. Any help at all is much appreciated. -
github social login in django
I am trying to do social login through GitHub in Django and everything is working fine. when I click on login with GitHub it redirects to my GitHub login page. when I provide credentials and it redirects me to the home page of my website. Now it should display the username of my github's profile but it is not showing it to me. what could be the problem? I am going to display all of the code which I wrote for social login via github. UserAccounts/views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, logout, login # Create your views here. # @login_required # it is being used here to restrict Anonymous users def home(request): return render(request, 'home_page.html') # @login_required # it is being used here to restrict Anonymous users to access thehome page without being authenticated def github_login(request): if request.user.is_authenticated: return render(request, 'home_page.html') else: return render(request, 'github_auth_login.html') def github_logout(request): return True UserManagement/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('UserAccounts.urls')), path('oauth/', include('social_django.urls')), ] UserAccounts/urls.py: from django.urls import path from django.contrib.auth import views as auth_views # for authentication from . import views as auth_views # importing views from … -
Filter a field not in the model in Graphene?
I have a model GroupCode that has a OneToOne to Rol, and i want to filter rol by one of the fields in GroupCode(GroupCode is the one with the OneToOneField), i have searched a little, but many examples and questions about this seem to mention how to filter found on the model, but not ones defined on the type, like enabled in this case, this is an example of my schema: class RolType(ModelType): class Meta: model = Group interfaces = [graphene.relay.Node] connection_class = CountableConnection permissions = ['security.view_group'] filter_fields = { 'name': ['exact', 'icontains', 'istartswith'] } enabled = graphene.Boolean() def resolve_enabled(self, info): return f"{GroupCode.objects.get(group=self.id).enabled}" class Query(graphene.ObjectType): rol = graphene.relay.Node.Field(RolType) roles = DjangoFilterConnectionField(RolType, enabled=graphene.Boolean()) Does anyone knows how to filter based on this enabled field? -
DRF- Custom User changes never migrate
I made the mistake of not using a custom user model for the first migration and I paid the price by having to delete all the migrations and makemigrations and migrate again as I switched the project to use my custom user. # models.py """ Changes are never picked by makemigrations """ from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class User(AbstractUser): username = models.CharField(max_length=120, unique=True, blank=False, validators=[MinLengthValidator(2)]) email = models.EmailField('Email Address', unique=True, blank=False) FCM_ID = models.CharField(max_length=300, blank=True) def __str__(self): return self.username Everytime I made any changes to the custom user, I have had to delete all migrations related files and apply migrations again just to get past the errors- this SO answer and this. Now I realized that I needed a newer change, but migrations are not detected after changing the User model. The only solution I have is to delete the migrations again! So far I have done this chore like 5 times and I am tired, what am I doing wrong? I have tried python3 manage.py makemigration <app_name>, and of course, the custom user model is defined in settings.py using AUTH_USER_MODEL. -
Populating Two Fields of one model based on fields in another model
I have the following models from django.db import models class Program(models.Model): title = models.CharField(max_length=190) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default="00:00:00") running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default="00:00:00") remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default="00:00:00") def __str__(self): return f"{self.pk} : {self.title}" class Segment(models.Model): program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', #new link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190) length_time = models.TimeField(null=True,default=None, blank=True) length_time_delta = models.DurationField(default="00:00:00") def __str__(self): return f"{self.title}" The form to create a program would allow you to enter a block time, but the other times are calculated based on the segment(s). The form(s) would have a program create/update function, and the segment form would have both the program info, and the ability to add one or more segment(s) on it. So, if I had a program that was an hour long (block_time = 1 hour), and two segments that were 28 minutes, then on the Program screen the Duration would be 1 hour, running time 56:00 min(calculated), and remaining time 4 minutes (calculated). Note at Program creation the user only enters Block Time, so at first the remaining time and the running time will be zero because there are no segments created yet. The Segment section(s) would not only have … -
How to include Parentalkey for django admin?
I have a Clusterable model along with a parental key relationship. The clusterable model is an "Order" model with the parental relationship from "OrderItem". The related name is "items". How can I include it in the django admin panel? For Order model class OrderAdmin(admin.ModelAdmin): fields = ["items"] # from (OrderItem model) but doesn't appear search_fields = ['id', 'user'] list_display = ('user', 'full_name', 'ordered', 'paid', 'total_to_pay') list_filter = ('ordered', 'paid',) -
instance data not loaded in template udpateview fields
This is my models: class User(AbstractUser): """Default user for awesomeinventory.""" is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_associatetoCompany = models.BooleanField(default=False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.user.username class Agent(models.Model): FUNCTIONS = Choices( (1, 'Procurement', _('Procurement')), (2, 'Request_User', _('Request')), (3, 'Receptionist', _('Receptionist')), ) user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) role = models.PositiveSmallIntegerField( choices=FUNCTIONS, default=FUNCTIONS.Request_User, ) def __str__(self): return self.user.email Agent form is: FUNCTIONS = Choices( (1, 'Procurement', _('Procurement')), (2, 'Request_User', _('Request')), (3, 'Receptionist', _('Receptionist')), ) class AgentModelForm(forms.ModelForm): role = forms.ChoiceField(choices=FUNCTIONS, widget=forms.Select, label='Role') class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name', 'role', ) my views.py: class AgentUpdateView(OrganisorAndLoginRequiredMixin, UpdateView): template_name = "agents/agent_update.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent_list") def get_queryset(self): return Agent.objects.all() I'm working on Agent and I've no issue to create an agent, view details of an agent. I'm using crispy form and generic views. My update view template is: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <form form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md">Submit</button> </form> {% endblock content %} In this form all fields stay empty except role. When I look at what … -
"null value in column violates not-null constraint" When saving Django Form
I am getting the following error in my code: "null value in column "bbso_record_id_id" of relation "sos_categorytoolsandequipment" violates not-null constraint DETAIL: Failing row contains (1, 1, , null)." The thing this, the code I have works with SQLlite but since I upgraded to Postgress all of a sudden it breaks and if I go back to SQllite it works again. I realize that the problem is with the OneToOne relationship but I am not sure how to retify it. It seems like my BBSO_Record has to save and get an id to pass to the OneToOne field first. But the problem is it works in SQLlite. This is my code and any assistance will be greatly appreciated. MODELS from django.db import models from django.db.models.deletion import CASCADE from django.core.validators import RegexValidator, MinValueValidator, MaxValueValidator #from django.db.models.enums import choices from django.utils import timezone from django.urls import reverse # page 138 Django for Beginneers from django.conf import settings # from django.utils import timezone from django.utils.timezone import now class BBSO_Records(models.Model): COMPANY_OR_CONTRACTOR = ( ('company', 'Company'), ('contractor', 'Contractor'), ) severityLevel = ( ('1', 'Level 1'), ('2', 'Level 2'), ('3', 'Level 3'), ) severity_level = models.CharField(max_length=6, default= 3 , choices=severityLevel) date_recorded = models.DateField() observer_name_ID = models.ForeignKey(settings.AUTH_USER_MODEL , … -
How to annotate in a model the agregates from other model
I need some help for making queries in my three models. The first is Cyclist, with fields like number (pk), name, birthday, etc. The second model is Classification with id (pk), type of classification, stage number, number(foreign key) and points. The first query I need to make is to get for every cyclist the total points in every stage number. My option is: puntos=Corredor.objects.values('dorsal','etapa').aggregate(total_puntos=Sum('puntos') After that, I have another model for Team. A team is a group of cyclist selected by a client. I want to get for every team the total sum of the points of the cyclists who form that team, but in this case I don't know how to use the query puntos in the new query for annotate. Maybe: team_points=Equipo.objects.annotate(F(Sum(lid__dorsal__puntos))+(Sum(lid2__dorsal__puntos))+...........))) Thanks in advance for the help. These are the models: class Corredor (models.Model): dorsal=models.IntegerField(primary_key=True) tipo=models.CharField(max_length=50) nombre=models.CharField(max_length=50) f_nacimiento=models.DateField(default=1/1/1975) nacimiento=models.IntegerField() categoria=models.CharField(max_length=50) pais=models.CharField(max_length=50) equipo=models.CharField(max_length=50) nombre_equipo=models.CharField(max_length=50) lid=models.BooleanField() gre=models.BooleanField() jor=models.BooleanField() giro=models.BooleanField() tour=models.BooleanField() vuelta=models.BooleanField() abandono_giro=models.IntegerField(default=0) etapa_aban_giro=models.IntegerField(default=0) abandono_tour=models.IntegerField(default=0) etapa_aban_tour=models.IntegerField(default=0) abandono_vuelta=models.IntegerField(default=0) etapa_aban_vuelta=models.IntegerField(default=0) class Meta: ordering=['nombre'] def __str__(self): return self.nombre class Equipo (models.Model): alias=models.CharField(max_length=50, primary_key=True) lid1=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid1", on_delete=models.CASCADE) lid2=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid2", on_delete=models.CASCADE) lid3=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid3", on_delete=models.CASCADE) lid4=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid4", on_delete=models.CASCADE) gre1=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre1", on_delete=models.CASCADE) … -
I can't post in django
-I can't post in django, because when I import an image it doesn't work for me. it tells me that there's no file selected but I selected one. here's my models.py file this is the post model that I created class Post(models.Model): publisher = models.ForeignKey(User,on_delete=models.CASCADE) caption = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now()) image = models.ImageField(upload_to="post_images") def __str__(self): return self.caption -here's the forms.py file for the Post model: from django import forms from .models import Post class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['caption','image'] -here's the Publish function in views.py file wich implements the logic for my publish feature: @login_required def Publish(request): if request.method == "POST": form = CreatePostForm(request.POST,request.FILES) if form.is_valid(): form.publisher = request.user form.save() return redirect("home") else: form = CreatePostForm() return render(request,"posts/publish.html",{ "form":form, }) int the urls.py file: from django.urls import path from . import views urlpatterns = [ path('publish/',views.Publish,name="publish"), path('',views.home,name="home"), ] and here's in html template: {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block title %}create{% endblock title%} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-6 col-md-5 authentification"> <div class="form-header"> <h1> publish </h1> </div> <div class="form-body"> <form method="POST"> <fieldset class="form-group" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-primary … -
Django - database order_id bug
I have a app in Django, that has models.py like that: from django.db import models from django.utils import timezone from django.contrib.auth.models import User import base64 class Order(models.Model): name = models.CharField(max_length=45) #note = models.CharField(blank=True, max_length=45) class Product(models.Model): name = models.CharField(max_length=40) quantity = models.CharField(max_length=32) price = models.CharField(max_length=32) #name = models.CharField(max_length=128, blank=True) #access_to_doors = models.ManyToManyField(Door, blank=True) class Review(models.Model): review_id = models.CharField(max_length=15) review_name = models.CharField(max_length=128) #username = models.ManyToManyField(Users) class Contact(models.Model): email=models.CharField(max_length=200) password=models.CharField(null=True, max_length=32) subject=models.CharField(null=True, max_length=1024) #def __str__(self): # return self.email I delete database, make a new one, run python manage.py migrate/makemigrations/migrate --run-syncdb and it says this Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying building_access.0001_initial...Traceback (most recent call last): File "D:\dev\building_access\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "D:\dev\building_access\myvenv\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "D:\dev\building_access\myvenv\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'order_id' used in key specification without a … -
How can I sort a Django query by user input?
I have a Django website with the following relevant models, views and templates. My question is below, after the relevant bits of code (note the code here is likely longer than what is needed to answer the question). Model: class Article(models.Model): title = models.CharField(max_length=255) comment = models.TextField() entry_date_time = models.DateTimeField(default=timezone.now, null=True) class Meta: ordering = ['-entry_date_time'] score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] fundamental_score = models.FloatField(choices=score_choices, default=0) equity = models.ForeignKey(Equity, on_delete=models.CASCADE, null=True) View: class ArticleListView(ListView): model = Article paginate_by = 50 fields = ('equity', 'entry_date_time', 'fundamental_score', 'sentiment_score', 'source') template_name = 'article_list.html' context_object_name = 'object_list' equity_query="" date_query="" start_query="" industry_query="" broker_query="" def get_queryset(self): if self.request.method == 'GET': if self.request.GET.get('equityQuery') is None: self.equity_query = "" else: self.equity_query = self.request.GET.get('equityQuery') if self.request.GET.get('dateQuery') is None: self.date_query = "" else: self.date_query = self.request.GET.get('dateQuery') if self.request.GET.get('startQuery') is None: self.start_query = "" else: self.start_query = self.request.GET.get('startQuery') if self.request.GET.get('industryQuery') is None: self.industry_query = "" else: self.industry_query = self.request.GET.get('industryQuery').title() if self.request.GET.get('brokerQuery') is None: #new self.broker_query = "" #new else: #new self.broker_query = self.request.GET.get('brokerQuery').title() #new self.equity_query = self.equity_query.upper() articles_list = Article.objects.filter(Q(equity__equity_name__contains=self.equity_query) & Q(entry_date_time__contains=self.date_query) & Q(equity__industry__contains=self.industry_query) & Q(source__contains=self.broker_query)) Equity.objects.all().filter(industry=industry) return articles_list Template: {% extends 'base.html' %} {%block title %}Entries{% endblock title %} {% block … -
Django - Ldap setting issue
import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType Baseline configuration. AUTH_LDAP_SERVER_URI = 'ldap://sub.domain.com' AUTH_LDAP_BIND_DN = 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com' AUTH_LDAP_BIND_PASSWORD = 'passwrd' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'OU=XXX,DC=users,DC=yyy,DC=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)', ) AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,OU=XXX,DC=users,DC=yyy,DC=com" AUTH_LDAP_GROUP_BASE = "OU=XXX,DC=users,DC=yyy,DC=com" AUTH_LDAP_GROUP_FILTER = 'member={0}' Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( AUTH_LDAP_GROUP_BASE, ldap.SCOPE_SUBTREE, AUTH_LDAP_GROUP_FILTER, ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='CN') Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = 'CN=enabled,OU=XXX,OU=groups,DC=users,DC=yyy,DC=com' AUTH_LDAP_DENY_GROUP = 'CN=disabled,OU=XXX,OU=groups,DC=users,DC=yyy,DC=com' Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', 'is_staff': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', 'is_superuser': 'CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com', } view.py user_obj = authenticate(request, username='userid', password='passwrd') user_detail = login(request, user_obj, backend='django.contrib.auth.backends.ModelBackend') I'm getting the below error, 'AnonymousUser' object has no attribute '_meta' I tried the below code also, conn = ldap.initialize('ldap://sub.domain.com') result = conn.search_s('CN=Bind Account,CN=Users,DC=ad,DC=users,DC=com',ldap.SCOPE_SUBTREE, '(objectClass=*)') For the above code, I got a different error, NO_SUCH_OBJECT at / {'msgtype': 101, 'msgid': 1, 'result': 32, 'desc': 'No such object', 'ctrls': [], 'matched': 'DC=ad,DC=users,DC=com', 'info': "0000208D: NameErr: DSID-03152973, problem 2001 (NO_OBJECT), data 0, best match of:\n\t'DC=ad,DC=users,DC=com'\n"}