Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template does not exist?
When I am trying to deploy to railway my project, i get the error mentioned above. This is one log that could give more insight? django.template.loaders.filesystem.Loader: /app/client/client/public/index.html (Source does not exist) Here is my project.settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'game-api', 'HOST': 'localhost', 'PORT': 5432 } } ROOT_URLCONF = 'project.urls' STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' project.views.py file: from django.shortcuts import render def index(request): return render(request, 'build/index.html') My files: -
get chosen dropdown option from Django filter
I am new to the Django and searched a lot about my problem, but could not use any of the solution. I am using Django filter to select some of the options available and use them to recreate and show my table in the HTML output. I have created the databse and the query, and it partially works. Whenever I try to run the app, I get the IDs of the values from the database and actual values are not returned. I am using Django 2.2.16 filters.py import django_filters from .models import * class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = '__all__' model.py `from django.db import models class CodeName(models.Model): code_name = models.CharField(max_length=200, null=True) def __str__ (self): return self.code_name class FileName(models.Model): file_Name = models.CharField(max_length=200, null=True) def str (self): return self.file_Name class Order(models.Model): codename = models.ForeignKey(CodeName, null=True,on_delete = models.SET_NULL) filename = models.ForeignKey(FileName, null=True,on_delete = models.SET_NULL) ` views.py def stats1(request): import pandas as pd data = { "calories": [420, 380, 390], "duration": [50, 40, 45] } #load data into a DataFrame object: NoneConceptsTable1 = pd.DataFrame(data) myFilter = OrderFilter() print(df) print('stats') print(len(NoneConceptsTable1)) if len(NoneConceptsTable1)>0: print("Yes, the lenght of NoneConceptsTable1 was geater than 1") pos = NoneConceptsTable1.Frequency.values codeName_instance = list(NoneConceptsTable1.Name.values) # print(codeName_codeName_instance[i]instance) % I … -
Django, how to get current request method? request is not working in my views.py
I'm new to Django. I'm trying to get my current request method to see if it is "POST" method. But I got error message says: Unresolved reference 'request' I tried to import request, but I don't know which one is correct. import choices Thanks for your help! Kind regards, Xi -
How to get data from both sides of a many to many join in django
Let's say I have the following models: class Well(TimeStampMixin, models.Model): plate = models.ForeignKey(Plate, on_delete=models.CASCADE, related_name="wells") row = models.TextField(null=False) column = models.TextField(null=False) class Meta: unique_together = [["plate", "row", "column"]] class Antibiotic(TimeStampMixin, models.Model): name = models.TextField(null=True, default=None) class WellConditionAntibiotic(TimeStampMixin, models.Model): wells = models.ManyToManyField(Well, related_name="well_condition_antibiotics") volume = models.IntegerField(null=True, default=None) stock_concentration = models.IntegerField(null=True, default=None) dosage = models.FloatField(null=True, default=None) antibiotic = models.ForeignKey( Antibiotic, on_delete=models.RESTRICT, related_name="antibiotics" ) In plain english, there are a set of wells and each well can have multiple and many different types of antibiotics. I'm trying to fetch the data of a given well and all of the antibiotics contained inside it. I've tried WellConditionAntibiotic.objects.filter(wells__id=1).select_related('antibiotic') which gives me this query: SELECT "kingdom_wellconditionantibiotic"."id", "kingdom_wellconditionantibiotic"."created_at", "kingdom_wellconditionantibiotic"."updated_at", "kingdom_wellconditionantibiotic"."volume", "kingdom_wellconditionantibiotic"."stock_concentration", "kingdom_wellconditionantibiotic"."dosage", "kingdom_wellconditionantibiotic"."antibiotic_id", "kingdom_antibiotic"."id", "kingdom_antibiotic"."created_at", "kingdom_antibiotic"."updated_at", "kingdom_antibiotic"."name" FROM "kingdom_wellconditionantibiotic" INNER JOIN "kingdom_wellconditionantibiotic_wells" ON ( "kingdom_wellconditionantibiotic"."id" = "kingdom_wellconditionantibiotic_wells"."wellconditionantibiotic_id" ) INNER JOIN "kingdom_antibiotic" ON ( "kingdom_wellconditionantibiotic"."antibiotic_id" = "kingdom_antibiotic"."id" ) WHERE "kingdom_wellconditionantibiotic_wells"."well_id" = 1 This gives me all of the antibiotic data, but none of the well data. So I tried Well.objects.filter(pk=1).select_related(['well_condition_antibiotics', 'antibiotic']).query which errored. How can I generate a django query to include all well data and all well antibiotic data? -
Combing two querries using Q objects in Django?
I have defined following view: class SearchListView(ListView): template_name = "movies/search_list.html" # overwriting the get_queryset function to customize the queryset def get_queryset(self) -> list: query = self.request.GET.get("q") if query: movies = list( filter( lambda x: unidecode(query.lower()) in unidecode(x.title).lower(), Movie.objects.all(), ) ) actors = list( filter( lambda x: unidecode(query.lower()) in unidecode(x.name).lower(), Actor.objects.all(), ) ) # use the chain function to combine the querysets return list(chain(movies, actors)) else: # return an empty list if no query is provided return [] And it is working as I want it to, however I have been trying to combine the querries into one querry using Q objects, but did not succeed. Do you think it's even possible in this case? -
"ImproperlyConfigured at /plan-a-trip/ Empty static prefix not permitted" error in Django
So I was trying to add a form webpage to my Django application, but I got this error: ImproperlyConfigured at /plan-a-trip/ - Empty static prefix not permitted I have absolutely no idea what this means, but these are what my files look like: urls.py: from django.conf import settings from django.conf.urls.static import static from django.urls import path, include from itineraries.views import * from .views import * urlpatterns = [ path('admin/', admin.site.urls), path('sights/', include('sights.urls')), path('', index, name="index"), path('plan-a-trip/', createItinerary.as_view(), name="create-itinerary") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig' ] MIDDLEWARE = [ '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 = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) WSGI_APPLICATION = … -
Django looping through model data but need to pass additional list data
I am posting data from database using Model, which displays fine. But I am now need to pass an additional list (POST.getlist) variable "mylist" along with the model object data, but I dont know how to dynamically loop through it as the "mylist" requires an index number such as "mylist.0", "mylist.1" and so on. html page {% for employee in employees %} <tr> <td>{{ mylist.X }}</td> <td>{{ employee.USER }}</td> <td>{{ employee.MATERIAL }}</td> <td>{{ employee.C }}..... models.py from django.db import models class Materials(models.Model): ID = models.AutoField(primary_key=True) USER = models.CharField(max_length=30) MATERIAL = models.CharField(max_length=30) C = models.FloatField(max_length=5) MN = models.FloatField(max_length=5) V = models.FloatField(max_length=5) CR = models.FloatField(max_length=5) P = models.FloatField(max_length=5) S = models.FloatField(max_length=5) AL = models.FloatField(max_length=5) CU = models.FloatField(max_length=5) SI = models.FloatField(max_length=5) MO = models.FloatField(max_length=5) NI = models.FloatField(max_length=5) CO = models.FloatField(max_length=5) NB = models.FloatField(max_length=5) TI = models.FloatField(max_length=5) W = models.FloatField(max_length=5) PB = models.FloatField(max_length=5) SN = models.FloatField(max_length=5) MG = models.FloatField(max_length=5) AS = models.FloatField(max_length=5) ZR = models.FloatField(max_length=5) B = models.FloatField(max_length=5) FE = models.FloatField(max_length=5) class Meta: db_table = "materials" view.py def selection(request): current_user = request.user boxlist = request.POST.getlist('selectbox') weightlist = request.POST.getlist('weight') mylist = list(filter(None, weightlist)) employees = Materials.objects.filter(USER=current_user, ID__in=boxlist) return render(request,"selection.html",{'employees':employees, 'mylist':mylist}) -
how to find available quantity of products Django ORM
Inaccurate results using Django ORM for calculating available quantity of products. I'm facing a problem in finding the available quantity of products using the Django ORM. I've written a code that uses the ORM to annotate the queryset with the quantity produced, quantity sold and available quantity fields, but the results are inaccurate. However, when I use raw SQL to perform the same calculations, the results are accurate. I need help understanding why the ORM code is not working as expected and how to fix it. Django ORM code for finding quantities of products: def get_queryset(self): queryset = super().get_queryset() queryset = queryset.annotate(Quantity_Produced=Sum(F('production__qunatity_produced'))) queryset = queryset.annotate(Quantity_Sold=Sum(F('sales__qunatity_delivered'))) queryset = queryset.annotate(Quantity_available=Sum(F('production__qunatity_produced')) - Sum(F('sales__qunatity_delivered'))) return queryset The Output (Inaccurate): { "product_id": 1, "product_name": "Product 1", "weight": 10.0, "Quantity_Produced": 6300.0, "Quantity_Sold": 2600.0, "Quantity_available": 3700.0 } ORM's Raw SQL method for finding the available quantity of products: def get_queryset(self): queryset= models.Products.objects.raw(''' SELECT *, (SELECT SUM(q.qunatity_produced) FROM production q WHERE q.product_id = p.product_id) AS Quantity_Produced , (SELECT SUM(s.qunatity_delivered) FROM Sales s WHERE s.product_id = p.product_id) AS Quantity_Sold, sum((SELECT SUM(q.qunatity_produced) FROM production q WHERE q.product_id = p.product_id) -(SELECT SUM(s.qunatity_delivered) FROM Sales s WHERE s.product_id = p.product_id))as Quantity_available FROM products p group by Product_id order by Product_id ''') return … -
How can I replace a substring with a string in django nested in a JSONField?
If I have a model: class MyModel(Model): properties = JSONField() And I have instances where the properties look like this: {"a": {"b": ["some text A"]}} {"a": {"b": ["some other text A"]}} {"a": {"b": ["some text A"]}} How do I bulk-update these model instances, replacing the string "A" with "B"? I would assume it would be something like this: MyModel.objects.update( properties=Func( F("properties"), Value("{a,b,0}"), Replace(F("a__b__0"), Value("A"), Value("B")), function="jsonb_set", ) ) It doesn't quite work though. I think I'm just missing a proper reference to the field (F("a__b__0") is invalid). -
How can I filter the value selected in a Django model form based on a certain data condition?
Good day! I have a model table in order to add data to this model. [Citizen_2] I would like users to enter their country of residence first, it's like a simple one-field form. And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field. For example, I have users added three countries there. Then they add the cities - for those respective countries. In the drop-down form field, select a country and write down your city there. And send the data to the model table. It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form. This is then used in the form to fill in the data. By country and its corresponding city in the main form. How can I make it in the form of a model [Citizen_2] the city of the corresponding country was chosen. From data previously filled in by users? Any information or help would greatly save me, please. Citizen_2 class Country(models.Model): name_country = models.CharField(max_length=150, db_index=True) def __str__(self): return self.name_country class … -
Creating An Application To Generate Files For eSignature
I'm currently working on a phone app an done of the features I need to create is the ability to generate a PDF that will need to be emailed to another person for them to eSign it. Is there a library for this? I'm using React Native on the frontend and Django/Python on the backend. Any suggestions would be appreciated. Thank you -
why can i not add object into field rest_framework
I want to add some pebbles but I am getting this error from the serializer { "user": [ "Incorrect type. Expected pk value, received str." ] } Of course, I read the documentation about serializers and relation but I still don't understand.. newbie in django Here my models class UserData(AbstractUser): username = None name = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=100, unique=True) date_joined = models.DateTimeField(auto_now_add=True) pseudo = models.CharField(max_length=200,unique=True) hashtag = models.CharField(max_length=200, unique=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) objects = UserManager() USERNAME_FIELD = "pseudo" REQUIRED_FIELDS = ['name','hashtag','email'] def __str__(self): return self.name class Pebbles(models.Model): image = models.CharField(max_length=200) user = models.ForeignKey(UserData, related_name="pebbles",on_delete=models.CASCADE) class Meta(): unique_together = ["id","user"] I can get a list of pebbles from that view it works. class PebblesView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] serializer_class = PebblesSerializer def get_queryset(self): return Pebbles.objects.all() def create(self, request): serializer = PebblesSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) I can register a user with my UserSerializer. I have the same logic for pebbles but it doesn't work. In the Django shell, I can add pebbles just like this. class UserSerializer(serializers.ModelSerializer): pebbles = serializers.StringRelatedField(many=True) class Meta: model = UserData fields = ["id", "pseudo", "hashtag","email", "name", "password","pebbles"] def create(self, validated_data): user = UserData.objects.create( … -
How to annotate the age of a person based on their date of birth - Django
I am trying to annotate a simple Person object with both the users date of birth and their age to keep the data normalised. I am wishing to later perform some filtering with this annotation so a model property will not work. I have found this blog article (last example) which seems to state what I'm wanting to do is possible, however whenever I actually execute this age is always None I am unsure what is going wrong here, logically it looks sound to me.. models.py class Person(AbstractUser): email = models.EmailField(unique=True) date_of_birth = models.DateTimeField(default=date.today()) views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer permission_classes = [permissions.IsAdminUser] def get_queryset(self): queryset = self.queryset.annotate( age = ExpressionWrapper( ExtractDay( ExpressionWrapper( Value(datetime.now()) - F("date_of_birth"), output_field=DateField(), ) ) / 365.25, output_field=IntegerField(), ) ) return queryset -
Deploy Django Project on Hostgator shared hosting
I am currently delving into the world of Django and have aspirations to bring my small project to fruition by deploying it. I have secured a cloud hosting plan with Hostgator for one year, which is a shared hosting option. Although my budget is currently limiting me from utilizing more advanced hosting solutions such as AWS or DigitalOcean. I reached out to Hostgator's customer support team for guidance, but was informed that while they could assist me with deploying the app on the server, they would not be able to provide further support. As a novice, I am still on the hunt for resources that can guide me through the deployment process in a comprehensive manner. I would be immensely grateful for a roadmap that can guide me through this process and any recommendations for online resources that are tailored for beginners such as myself, who are eager to learn. Thanks -
Dynamic url rendered by Django as an api response, but not by frontend
I'm using Django + Angular, and I have a dynamic url which works for first time when load my product page. I specified as a dynamic url in Django too, so the url look like this "product/home/:productName/:productId". Everything definitely works but as a response when I reload my page, it gets plain API response from Django and the host is changed to the backend one. Why it's happening? I was searching around didn't found anything. url.py path('product/home/<str:handle>/<int:id>', ProductGet) view.py @csrf_exempt def ProductGet(request, handle, id): product = Product.objects.get(id=id) serializer = ProductSerializer(product, many=False) return JsonResponse(serializer.data, safe=False) So, this code works for first time, but then when I reload seems it changes host to Django and I'm getting as a response, my API response. -
Error when using comment form on website: (1048, "Column 'comment_post_id' cannot be null")
I'm trying to implement a comment section below each blog on my site. I've got the form rendering but when I try to post a comment I get the following error: (1048, "Column 'comment_post_id' cannot be null") I cannot see what I'm doing wrong, I've also followed a tutorial step by step, although it is 2 years old. here's my code: sorry if I missed any, please ask if you require more. models.py: class BlogPost(models.Model): blog_title = models.CharField(max_length=100, null=False, blank=False, default="") blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.blog_title) super().save(*args, **kwargs) def __str__(self): return self.blog_title class blogComment(models.Model, ): comment_post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) comment_name = models.CharField(max_length=100) comment_text = models.TextField(max_length=1000) comment_date = models.DateTimeField(auto_now_add=True) comment_status = models.BooleanField(default=True) class Meta: ordering = ("comment_date",) def __str__(self): return '%s -- Name: %s'%(self.comment_post.blog_title, self.comment_name) views.py: def viewBlog(request, slug): try: blog = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("ViewBlog with this slug does not exist") blog = None comments = blog.comments.filter(comment_status=True) user_comment = None if request.method == 'POST': comment_form = commentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.blog = blog user_comment.save() return HttpResponseRedirect('/' + blog.slug) else: comment_form … -
Django - BaseSerializer.is_valid() takes 1 positional argument but 2 were given
This project was working before, but then Heroku took away free tier so I have been trying to deploy somewhere else, but now all of a sudden I cannot even create a user locally even though I could before... Now when I create a user I get the error mentioned in the title. serializers folder common.py file from xml.dom import ValidationErr from rest_framework import serializers from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.hashers import make_password User = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) def validate(self, data): password = data.pop('password') confirm_password = data.pop('confirm_password') if password != confirm_password: raise ValidationErr({ 'confirm_password': 'Does not match the password'}) password_validation.validate_password(password) data['password'] = make_password(password) return data class Meta: model = User fields = ('id', 'username', 'email', 'password', 'confirm_password') views.py file from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.exceptions import PermissionDenied from django.contrib.auth import get_user_model import jwt User = get_user_model() from datetime import datetime, timedelta from jwt_auth.serializers.common import UserSerializer from django.conf import settings class RegisterView(APIView): def post (self, request): create_user = UserSerializer(data=request.data) try: create_user.is_valid(True) create_user.save() return Response(create_user.data, status=status.HTTP_201_CREATED) except Exception as e: print(str(e)) return Response(e.__dict__ if e.__dict__ else str(e), status=status.HTTP_422_UNPROCESSABLE_ENTITY) class LoginView(APIView): def post(self, request): password = request.data.get('password') username … -
UnicodeEncodeError: 'charmap' codec can't encode character DJANGO
I am getting this error: UnicodeEncodeError: 'charmap' codec can't encode character '\u064f' in position 3583: character maps to <undefined> while running command: python manage.py makemessages -all can anybody help me what's wrong here? run : py manage.py makemessages -all then it should add all strings which are calling _() method should be added to .po file. -
Django TemplateDoesNotExist error - wrong path to templates folder
I am currently watching the Django lecture from CS50W and was coding along with Brian just fine. But now I keep getting the same error no matter what I do. I want to render the simple HTML5 page with Django and even though I have specified the correct path to the templates folder and index.html. from Django.shortcuts import render from datetime import datetime # Create your views here. def index(request): now = datetime.now() return render(request, 'newyear/index.html', { 'newyear': now.month == 1 and now.day == 1 }) And I get an error as stated below Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /home/gaba/cs50w/week3-Django/lecture3/hello/templates/newyear/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/admin/templates/newyear/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/auth/templates/newyear/index.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gaba/cs50w/week3-Django/lecture3/newyear/views.py", line 8, in index return render(request, 'newyear/index.html', { File "/usr/local/lib/python3.10/dist-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.10/dist-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/usr/local/lib/python3.10/dist-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /newyear/ … -
How to call a function in django view.py
I need to call the function get_context_data in my VacanciesView. Code views.py: def VacanciesView(request): navigate_results = Navigate.objects.all() context_vac = { 'navigate_results': navigate_results} get_context_data(self, **kwargs) return render(request, 'main/vacancies.html', context_vac) def get_context_data(self, **kwargs): context = super(VacanciesView, self).get_context_data(**kwargs) context['vacancies'] = sorted(get_vacancies(), key=lambda item: item["published_at"][:10]) return context I try to do it by get_context_data(self, **kwargs), but it takes: name 'self' is not defined -
I want to integrate LDAP authentication in Django, but missing some configuration I guess
I want to integrate LDAP authentication in Django, but even authentication is not happening i.e even after providing the correct LDAP credentials the user details in the Django admin panel the user details are not getting stored in the Django user model. Here's my setttings.py file in Django AUTH_LDAP_SERVER_URI = 'ldaps://xxxxxx:636' AUTH_LDAP_BIND_DN = 'CN=xxxxx,OU=Service,OU=Accounts,OU=SF_SAP,DC=sf,DC=priv' AUTH_LDAP_BIND_PASSWORD = 'xxxxxxxx' AUTH_LDAP_USER_SEARCH = LDAPSearch('OU=User,OU=Accounts,OU=SF_SAP, DC=sf,DC=priv',ldap.SCOPE_SUBTREE, '(CN=%(user)s)') AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "username": "uid", "password": "userPassword", } AUTH_LDAP_PROFILE_ATTR_MAP = { "home_directory": "homeDirectory" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) Can someone please point out what am I missing? -
Zabbix events.api giving HTTP Error 500: Internal Server Error in django for selected time range
I am new to usage of zabbix api. I am trying to fetch the events using zabbix events.get() api in postman as below I am pretty sure this is correct, because I am getting values for other time range except this range i.e October 1st to 31st. Any idea? -
Set Extra Fields In Django Generic Many to Many Relationship
Wondering how I could set a generic many to many relationship including additional fields through a post request. Note that I removed some irrelevant fields to make it easier to read. I have only included one of the objects (message) that can have these labels for simplicity. Models class Message(models.Model): text = models.CharField(max_length=250, default='text') labels = GenericRelation(to=Label) class Tag(models.Model): color = serializers.Charfield() class Label(models.Model): tag = models.ForeignKey(to=Tag, on_delete=models.CASCADE) # Generic foreign key object_id = models.PositiveIntegerField() content_type = models.ForeignKey(to=ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey() confidence = models.IntegerField() section = models.IntegerField() class Meta: indexes = [ models.Index(fields=["content_type", "object_id"]), ] Serializers class LabelSerializer(ModelSerializer): class Meta: model = Label fields = ['id', 'confidence', 'level'] class MessageSerializer(serializers.ModelSerializer): labels = serializers.ManyRelatedField( child_relation=LabelSerializer(), required=False) class Meta: model = Message fields = ['id', 'text', 'labels'] The idea would be to have the following post request which would set the relationship between tags and messages, using the custom through table Labels with the additional fields confidence and section set. { 'text': 'Message Text', 'labels': [ { 'tag': 1, 'confidence': 0.9, 'section': 1 }, { 'tag': 2, 'confidence': 0.7, 'section': 1 } ] } -
Can't install whitenoises library on my django project
I am using the conda environment and I cannot load the white noise library, but it says that the library is installed. enter image description here enter image description here[[[[enter image description here](https://i.stack.imgur.com/QcVTw.png)](https://i.stack.imgur.com/PXIy9.png)](https://i.stack.imgur.com/6qMSC.png)](https://i.stack.imgur.com/TNOYx.png) I try all, but i can't fix this error -
Django-filters resets after using the UpdateView
I have a Model with a lot of entries, so I'm using django-filters to filter the model, I initially load an empty table and from there I use the filter to view the items. Everything works fine, the page loads initially with no entry, after I filter, django shows the correct items. The Url gets a parameter: /retetabloc/?acordcadru=532(532 is the filter) but when I try to update an entry, the filter resets(the parameter is still in the URL) and the whole db is loaded. I don't quite understand how to pass the filter parameter to the RetetaBlocUpdate, so that after the update is done it returns to the filtered items like in the ListView. views.py class RetetaBlocListview(LoginRequiredMixin, CoreListView): model = RetetaBloc def get_queryset(self, *args, **kwargs): pdb.set_trace() acordcadru = self.request.GET.get("acordcadru") queryset = RetetaBloc.objects.filter(acordcadru=acordcadru) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = RetetaBlocFilter(self.request.GET, queryset=self.get_queryset()) pdb.set_trace() return context class RetetaBlocUpdate(LoginRequiredMixin, AjaxUpdateView): model = RetetaBloc form_class = RetetaBlocForm Thank you.