Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't get a queryset from GenericForeignKey
How to fix this error FieldError at /movies/ Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. This is a class for getting user activity by queryset from typing import Dict, Any from django.db.models.base import ModelBase from django.db.models.query import QuerySet from specifications.serializers import ActivitySerializer class UserActivity(object): def __init__(self, user) -> None: self.user = user def get_activity(self, model: ModelBase, query: QuerySet) -> Dict[str, Any]|None: if model._meta.model_name == "comment": objects = model.objects.filter(user=self.user, comment__in=query) serializer = ActivitySerializer(objects, many=True) else: objects = model.objects.filter( user=self.user, content_object__in=query ) serializer = ActivitySerializer(objects, many=True) return serializer.data I have a view for getting movies class MovieListView(APIView): def get(self, request): movies = Movie.objects.all() paginator = PageNumberPagination() paginator.page_size = 10 page = paginator.paginate_queryset(movies, request) serializer = MovieListSerializer(page, many=True) user_activity = UserActivity(request.user) data = { "movies": serializer.data, } if request.user.is_authenticated: user_activity = UserActivity(request.user) activity = { "user": { "ratings": user_activity.get_activity(Rating, page), "watchlist": user_activity.get_activity(WatchList, page) } } data.update(activity) response = Response(data) response['X-Total-Count'] = paginator.page.paginator.count response['X-Page-Size'] = paginator.page_size response['X-Page'] = paginator.page.number return response I have 2 models (movie, rating) class Movie(models.Model): ... comments = GenericRelation(Comment) ratings = GenericRelation(Rating) watchlist = GenericRelation(WatchList) class Rating(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, … -
Azure web app hosting React frontend & Python Django Backend Issues
I am attempting to host this website on Azure on behalf of my team, I have had issues. The current issue has me stumped; Azure says the website is hosted & is running. I can see that Azure is hosting it, but when I go to the website, there is nothing there. I do not know if I need to have something on our end connect to the link azure provides us, the website can run locally, as when we run it, it will host on localhost, and we can navigate it and the locally hosted database. When I attempt to run the website, on azure it says that it is running, but if I go to the link azure provides, it is the default azure website. Here is the GitHub if you want to take a look, any pointers or potential fixes would be greatly appreciated. I'll be more than happy to elaborate on any information anyone needs. -
Django_tables2 only shows the default table
So, I am creating a small app where I need to show an HTML table from the database entries. So I am using Django and the best solution for it was Django_tables2. And for the default setting, where all the fields from the model are being displayed it works ok. But I needed to add another column for a button and that's when I ran into a problem. I cannot add/delete a column or anything in the table. The changes I make in the Table class are rejected and the default settings are being still used. I tried removing the template or the model from the View class, but nothing worked. I tried editing the Table class again, but nothing. I tried switching the View class from SingleTableView to SingleMixinView, but that just breaks it even more. This is my Table class: class InsertTable(tables.Table): class Meta: model = Insert template_name = "list.html" fields = ['id', 'name', 'phone', 'description', 'date', 'done', 'edit'] edit = tables.TemplateColumn(template_name="edit.html", verbose_name="edit", orderable=False) This is my view class: class List(SingleTableView): model = Insert table_class = InsertTable template_name = "list.html" -
Function(instance, filename)
I,m working with my first project in Django, And I have a model like that: def get_image_path(instance, filename): category_name_path = instance.category.category_name return f"{category_name_path}/{filename}" class Gallery(models.Model): description = models.TextField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) image = ResizedImageField(size=[1920, 1920], upload_to=get_image_path) def __str__(self): return '%s %s %s' % (self.category, self.image.url, self.description) It works but I cannot understand how the 'filename' argument is passed to the function? How it works? ;) -
Executing the bat file before starting the iis site
My django application uses environment variables that must be set via a bat file. How to do it via python (for example via subprocess) I do not know because when executing a bat file via python, a new process is created in which environment variables are set, but when the process ends, all environment variables disappear and they are not reflected in the creator process. My django server is running on IIS. Perhaps you should configure IIS somehow so that it executes first .bat file and then launched my django project and this django project inherited all the environment variables that it created .bat file. -
I am getting MultiValueDictKeyError at /gf/ 'name'
Error ImageI am getting following error. I have no option to set name property(before same error pop up but resolved by changing name) since I am using form then how to resolve it. MultiValueDictKeyError at /gf/ 'name' Request Method:GETRequest URL:http://127.0.0.1:8000/gf/?age=28&csrfmiddlewaretoken=0NribXMzevzOMqH3YoYiK65wqODRNRj3oiKBT50X5NK4BTi7j87UhMTRndTpz8S5Django Version:4.2Exception Type:MultiValueDictKeyErrorException Value:'name' Code: views.py from django.shortcuts import render from django.shortcuts import render from .forms import * def name_view(request): form=Nameform() return render(request,'name.html',{'form':form}) def age_view(request): form=AgeForm() name=request.GET['name'] request.session['name']=name return render(request,'age.html',{'form':form}) def gf_view(request): form=GFForm() age=request.GET['age'] request.session['age']=age return render(request,'gf.html',{'form':form}) def result_view(request): gf=request.GET['gf'] request.session['gf']=gf return render(request,'result.html') forms.py from django import forms class Nameform(forms.Form): name=forms.CharField() class AgeForm(forms.Form): age=forms.IntegerField() class GFForm(forms.Form): gf=forms.CharField() name.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Name Registration Form</h1><hr> <form action="{%url 'age'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit Name"> </form> </body> </html> age.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Age Registration Form</h1><hr> <form action="{%url 'gf'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit Age"> </form> </body> </html> gf.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>GF Registration Form</h1><hr> <form action="{%url 'result'%}" > {{form}} {%csrf_token%}<br><br> <input type="submit" name="" value="Submit GF's Name"> </form> </body> </html> result.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {%if request.session%} <h1>Thanks for … -
Having trouble sorting a table by column header that is populated by Django Pagination
I'm making a SaaS application using Django that displays a table where each row represents a loan, and each column represents information about that loan (name, date, amount, rate, etc.). In my first version of the software, I passed all of the loans in the database into the table, and then used Javascript to sort the table on the client side. The table was sorted alphabetically by name as default, but the user could click any of the column headers to resort the table by that column. The user could click the same column a second time to reverse the sort order of that column (i.e. click once to sort by amount ascending, twice to sort by amount descending). This worked well but when I decided to add more loans to the database, I realized I needed Pagination. In my current version, I have changed the application so that I'm using Django's Pagination and sorting the data in my views.py file before passing it to the HTML template. I hadn't done Pagination before in Django so I used ChatGPT to help but I now have a solution that sort of works, but I'm not quite sure how to debug what's … -
django forms 'tuple' object has no attribute '_meta'
`I am getting this error when i post the data in django forms 'tuple' object has no attribute '_meta'` Views.py def user_ajax_info(request): if request.method == "POST": req_type = request.POST.get('type') if req_type == "Personalinfoform": empId = request.POST.get("employee_id") user_obj = User.objects.get(username=empId) print(user_obj,'user object') additional_info_obj = PersonalInfo.objects.get_or_create(employee=user_obj) form = AssociatePersonalInfoForm(request.POST, instance=additional_info_obj) if form.is_valid(): additional_info_obj = form.save(commit=False) additional_info_obj.employee = request.user form.save() return JsonResponse({"status": "success"}, status=200) else: return JsonResponse({"status": "failure"}, status=400) return redirect('user:profile') This is my forms forms.py I added filters in this form class AssociatePersonalInfoForm(forms.ModelForm): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female') ] MARITAL_CHOICES = [ ('Married', 'Married'), ('Single', 'Single'), ('Widowed', 'Widowed'), ('Separated', 'Separated'), ('Divorced', 'Divorced') ] MEDICAL_CHOICES = [ ('Self', 'Self'), ('Spouse', 'Spouse'), ('Children', 'Children'), ('Parents', 'Parents'), ] Relation_CHOICES = [ ('Father', 'Father'), ('Mother', 'Mother'), ('Spouse', 'Spouse'), ] gender = forms.ChoiceField(widget=forms.Select(attrs={'required': 'required'}), choices=GENDER_CHOICES) nationality = forms.ModelChoiceField(queryset=Nationality.objects.all().order_by("nationality_name"), empty_label="Select") email = forms.EmailField(max_length=254) caddressfile = forms.ModelChoiceField(queryset=CurrentAddressProoff.objects.all().order_by("rent_receipt"), empty_label="Select") # per_addressfile = forms.ModelChoiceField(queryset=PermentAddressProoff.objects.all().order_by("adharcard"), empty_label="Select") # maritalstatus = models.CharField(max_length=20, choices=MARITAL_CHOICES, null=True, blank=True) # alpha version # child_info = forms.ModelChoiceField(queryset=Employee_childDetails.objects.all().order_by("child_name"), empty_label="Select") # medicalinsurance_preferencee = forms.ChoiceField( choices=MEDICAL_CHOICES) # emergency_relations = forms.ChoiceField( choices=Relation_CHOICES) approved_status = forms.CheckboxInput() class Meta: model = PersonalInfo fields = ('employee','fullname','preffered_name','gender','nationality','contactnum','alternate_num','email','alternate_email', 'fathername','father_dob','mothername','mother_dob','maritalstatus','spousename','spouse_dob','cline1','cline2','carea','ccity','cdistrict','cstate','cpincode','caddressfile','pline1','pline2','parea','pcity','pdistrict','pstate','pstate','ppincode','per_addressfile','child_info','medicalinsurance_preferencee','emergencycontactname1','emergency_relations','emergencycontactnumber','emergencycontactnumber2') ) This my models class PersonalInfo(models.Model): MARITAL_CHOICES = [ ('Married', 'Married'), ('Single', 'Single'), ('Widowed', 'Widowed'), ('Separated', 'Separated'), … -
What class instance should be used for request of authenticate()?
I have backend which uses the Ldap class MyLDAPBackend(LDAPBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("Try ldap auth") print(type(request)) # <class 'django.core.handlers.wsgi.WSGIRequest'> user = LDAPBackend.authenticate(request, username, password,kwargs) This shows the error like this, 'WSGIRequest' object has no attribute 'settings' So, I checked the source code in [django-auth-ldap][1] library. class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): if username is None: return None if password or self.settings.PERMIT_EMPTY_PASSWORD: ldap_user = _LDAPUser(self, username=username.strip(), request=request) user = self.authenticate_ldap_user(ldap_user, password) else: logger.debug("Rejecting empty password for %s", username) user = None return user It expect the instance which has access to settings.py, however framework pass the <class 'django.core.handlers.wsgi.WSGIRequest'> to authenticate. How can I solve this? -
Access Microsoft Graph API in Django Project
I have a Django project that uses django-microsoft-auth for user authentication and I would like to know how I could go about get users' profile pictures from the Microsoft Graph API if they are logged in. I know from the documentation that I need to use https://graph.microsoft.com/v1.0/me/photo/$value to get the picture data then I can encode it as Base64 then I can use a context processor to pass it to my base.html template and put it in an image as seen in this stackoverflow post. What I don't know how to do is implement getting the data from the API. I know I need an access token, but I'm not sure how to get that since all of the authentication is handled by the django-microsoft-aith package. -
How can I annotate a django queryset with more than one values
I have an application that scrapes some eshops every day, and I record the Price of every Item. A simplified version of my models looks like this: class Item(models.Model): name = models.CharField(max_length=512, blank=True) class Price(models.Model): item = models.ForeignKey("Item", on_delete=models.CASCADE) timestamp = models.DateTimeField(blank=True) per_item = models.FloatField(blank=True) And my tables can look like this: # Item id | name ----------- 1i | item-1 2i | item-2 3i | item-3 # Price id | item | timestamp | per_item -------------------------------------- 1p | i1 | 2023-04-10 | 10.0 2p | i2 | 2023-04-10 | 2.0 3p | i3 | 2023-04-10 | 14.5 4p | i1 | 2023-04-11 | 11.0 5p | i3 | 2023-04-11 | 12.5 6p | i2 | 2023-04-12 | 2.0 7p | i3 | 2023-04-12 | 14.5 8p | i1 | 2023-04-13 | 12.0 9p | i2 | 2023-04-13 | 3.5 10p | i3 | 2023-04-13 | 15.0 Note that not all Items exist every day, some of them may be present today, missing tomorrow and back again on the day after, and so on. What I want to do I'm trying to write a query that for a given day it will give me the last 2 Prices for every … -
The user is not added to the group. Django Forms
I have a form to create an employee, and in this form there is a "groups" field. When submitting the form, a user is created but not added to the selected group froms class CreateEmployeeForm(auth_forms.UserCreationForm): class Meta: model = user_model fields = [ 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'phone_number', 'gender', 'groups', 'middle_name', ] views My View accepts 3 arguments.(form_class, template, success_url) class DirectorCreateEmployeeView(CreateView): template_name = 'director/create_employee_director.html' form_class = CreateEmployeeForm success_url = reverse_lazy('director_list_employee_view') def user_registered_callback(sender, user, request, **kwargs): group_name = request.POST['group_id'] or None if group_name: try: g = Group.objects.get(name=group_name) except Group.DoewNotExists: g = None if g: g.user_set.add(user) html in html I used a custom crispy form <form action="" method="post"> { % csrf_token % } < div class = "card-body" > < h6 class = "card-title" > Creation empl < /h6> < div class = "row" > < div class = "col-md-6" > < div class = "form-group" > { { form.first_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.last_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.middle_name | as_crispy_field } } < /div> < div class = "form-group" > { { form.password1 | as_crispy_field } } … -
Vercel Django Deployment Error : 500: INTERNAL_SERVER_ERROR. Unable to import module 'backend.settings'
I have created a Django Project which I wanna use as backend for my React project. In the root of the project there are two folders : backend for django and frontends for react. Also I have provided a screenshot of the directory tree of my project: screenshot I added requirements.txt and vercel.json with all required stuff below is the code snippets for both. Also I have added vercel to allowed domains according to the documentation. But when I deploy the app through GitHub in vercel, deployment process finishes but when I visit the website I get 500 INTERNAL_SERVER_ERROR which further says 'FUNCTION_INVOCATION_FAILED' So then I go to vercel and check Runtime Logs and I get to see the following error printed multiple times: [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'backend.settings' Traceback (most recent call last): So the error is not probably due to missing dependencies in requirements.txt but with the import error of my project files. In this case the settings.py. I don't really understand what's causing the import error since I gave correct paths of wsgi.py in vercel.json requirements.txt asgiref==3.6.0 Django==4.2 djangorestframework==3.14.0 python-dotenv==1.0.0 pytz==2023.3 sqlparse==0.4.3 tzdata==2023.3 vercel.json { "builds": [{ "src": "backend/backend/wsgi.py", "use": "@vercel/python", … -
django admin cannot carryover object from one page to another admin page
I have two models(candidate and panelists) in my Django app, i have a link(for all candidate objects) in candidate admin page, when i click on it, it is redirecting to the panelists admin page, but I'm unable to see from which candidate object the panelists page has redirected. if I'm able to see from which candidate obj(or the candidate id) then I can filter panelists based on the candidate attributes. class Candidate(models.Model): id = models.IntegerField(auto_created=True) name = models.CharField(max_length=255) class panelist(models.Model): id = models.CharField(primary_key=True,max_length=7,unique=True) name = models.CharField(max_length=255) here is the candidate admin class CandidateAdmin(admin.ModelAdmin): list_display = ['id','name''view_panelist'] model = Candidate def view_panelist(self,obj): return format_html('<a href= "/admin/ttt/panelist/" class = "default"> View Panelist </a>') -
User errror django
[[[[enter image description here](https://i.stack.imgur.com/d4uWG.png)](https://i.stack.imgur.com/9lWEh.png)](https://i.stack.imgur.com/M5PPH.png)](https://i.stack.imgur.com/envOh.png)] I am doing a simple user posting clone project in django in user field i am need the current active user but instead i am getting all the user in database -
How can i make a language switch button for my blog?
What py files should I modify? (models/admin ect) I need a button in the home page which would allow to switch language into english/german/spanish I tried running this: rom django import template register = template.Library() @register.filter def new_lang_code(current_lang_code): if current_lang_code == ‘en’: return ‘ja’ else: return ‘en’ @register.filter def new_lang_name(current_lang_code): if current_lang_code == ‘en’: return ‘日本語’ else: return ‘English’ But I don't get where should I put this part of code: % load language_selector %} ⋮ <form action=“{% url ‘set_language’ %}” method=“post” id=“form_{{ LANGUAGE_CODE|new_lang_code }}” > {% csrf_token %} <input name=“next” type=“hidden” value=“{{ redirect_to }}” /> <input name=“language” type=“hidden” value=“{{ LANGUAGE_CODE|new_lang_code }}” /> </form> <button class=“btn btn-sm btn-outline-primary” type=“submit” form=“form_{{ LANGUAGE_CODE|new_lang_code }}” value=“Submit”>{{ LANGUAGE_CODE|new_lang_name }}</button> -
There are several packages installed in my virtual environment but pip list doesn't show anything
I've created a new Django project since almost 1 month. I have several packages installed. As I'm using virtual environment I can find all these packages in this directory F:\newEnironment\Lib\site-packages enter image description here Now when I activate my environment and go on my project pip command doesn't do anything. I want to use pip lists and pip freeze. Both returns nothing. Some of the project abilities won't work if these packages aren't installed. I can successfully run the project on my machine and that's why I'm quite sure this packages are installed. For instance when I write pip list in CMD it shows me that pillow isn't installed globally on my machine. As you see in the picture above it includes in site-packages directory which means I have it installed locally. Not only that, my projects pictures are works correctly because of pillow. -
How to exclude certain items from query ordering but still keep them in the query in Django?
I want to send a list of IDs to my API of items which should always appear at the top of the query disregarding the ordering. For example, if I send ids=3,4 to the API and I have 5 objects in the DB and I order by created_at, I would like to receive them in order: 3 4 1 2 5 or if I order by -created_at then 3 4 5 2 1. I tried to do this # Apply the default ordering first queryset = super().filter_queryset(request, queryset, view) if "ids" in request.query_params: first_ids = request.query_params["ids"].split(",") queryset = queryset.order_by(Case(When(id__in=first_ids, then=0), default=1)) return queryset This works when I order by created_at for example, but fails for -created_at. -
how to change an existing char field to a foreign key in Django
I had this model class Order(models.Model): ... discount_code = models.CharField() but at some point in development we decided to move from text only discount_codes to a Model with code, percentage, start and end dates etc. Which meant we had to update to a foreign key class Order(models.Model): ... discount_code = models.ForeignKey(to=DiscountCode, on_delete=models.PROTECT, null=True, blank=True) during this time a few hundred orders were generated and naturally some had discount codes. When it came to running migrations we werent able to, simply because char is not a foreign key. So I decided to update the migration to handle moving from char to an object but it still fails. Here's the migration file # Generated by Django 3.2 on 2022-09-20 05:13 from django.db import migrations, models import django.db.models.deletion from datetime import date def create_discount_objects(apps, schema_editor): Order = apps.get_model('orders', 'Order') DiscountCode = apps.get_model('orders', 'DiscountCode') # Get a list of unique discount codes from the existing orders discount_codes = Order.objects.exclude(discount_code=None).order_by('discount_code').values_list('discount_code', flat=True).distinct('discount_code') # Create new Discount objects for each discount code discount_objects = [] for code in discount_codes: if code is not None: discount_objects.append(DiscountCode(code=code, percentage=10.0, start_date=date(2023,4,20), end_date=date(2023,4,20))) DiscountCode.objects.bulk_create(discount_objects) # Update the existing orders to link them to the corresponding Discount objects for order in Order.objects.all(): if … -
Join query in Django ORM with multiple joins against same table
I need multiple joins against same table. My Models: class Goods(models.Model): art = models.CharField(max_length=20, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) class PriceGroups(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) goods = models.ForeignKey(Goods, on_delete=models.CASCADE,) pricegroup = models.ForeignKey(PriceGroups, on_delete=models.CASCADE) This SQL works: SELECT goods.id, goods.art art, goods.name name, price_deal.price deal, price_up_200.price price_up_200, price_100_200.price price_100_200, price_50_100.price price_50_100, price_20_50.price price_20_50, price_deal.price + 2.95 deal_up, price_up_200.price + 2.95 price_up_200_up, price_100_200.price + 2.95 price_100_200_up, price_50_100.price +2.95 price_50_100_up, price_20_50.price + 2.95 price_20_50_up FROM price_goods AS goods LEFT JOIN price_price AS price_deal ON goods.id = price_deal.goods_id LEFT JOIN price_price AS price_up_200 ON goods.id = price_up_200.goods_id LEFT JOIN price_price AS price_100_200 ON goods.id = price_100_200.goods_id LEFT JOIN price_price AS price_50_100 ON goods.id = price_50_100.goods_id LEFT JOIN price_price AS price_20_50 ON goods.id = price_20_50.goods_id WHERE price_up_200.pricegroup_id = 8 AND price_deal.pricegroup_id = 5 AND price_100_200.pricegroup_id = 7 AND price_50_100.pricegroup_id = 9 AND price_20_50.pricegroup_id = 6 ''' No idea how to do in Django ORM....any way to do this? -
drf serializers, passing request to serializer context not working
this is the error I'm getting django.db.utils.IntegrityError: null value in column "user_id" of relation "recipes_recipe" violates not-null constraint DETAIL: Failing row contains (24, testtest, test1234, 20, L, , f, null). I understand the error but I don't get why it's happening. When I try do this it doesn't work # views.py class RecipeViewSet(viewsets.ModelViewSet): serializer_class = RecipeSerializer queryset = Recipe.objects.all() def get_serializer_context(self): return {"user_id": self.request.user.id} # serializers.py class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = [ "id", "user", "title", "description", "duration", "cost", "reference_link", "is_public", ] extra_kwargs = {"user": {"read_only": True}} def create(self, validated_data): return Recipe.objects.create( user_id=self.context["user_id"], **validated_data ) but when I Do this, it works! # views.py class RecipeViewSet(viewsets.ModelViewSet): serializer_class = RecipeSerializer queryset = Recipe.objects.all() def perform_create(self, serializer): serializer.save(user_id=self.request.user.id) # serializers.py class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = [ "id", "user", "title", "description", "duration", "cost", "reference_link", "is_public", ] extra_kwargs = {"user": {"read_only": True}} can someone explain? -
LDAPBackend.authenticate returns `Rejecting empty password for XXXX`
I am useing django-auth-ldap, overriding LDAPBackend.authenticate like this, class MyLDAPBackend(LDAPBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("Try ldap auth") print(username) print(password) user = LDAPBackend.authenticate(self, username, password) Both username and password have value. username = ldaptest password = ldappass hoever it returns the error message like this , Rejecting empty password for ldaptest My settings.py is here. I also set the ldap admin password. AUTHENTICATION_BACKENDS = [ "defapp.backends.MyLDAPBackend", "defapp.backends.MyAuthBackend" ] AUTH_LDAP_SERVER_URI = "ldap://myexmaple.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=myexample,dc=com" AUTH_LDAP_BIND_PASSWORD = "adminpasswd" AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=people,dc=myexample,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": "logging.StreamHandler"}}, "loggers": {"django_auth_ldap": {"level": "DEBUG", "handlers": ["console"]}}, } Where am I wrong? where should I check ? -
How to return related translation of a field in Django rest framework?
I have trasnlated fields in database model like below class Property(models.Model): title_en = models.CharField title_fa = models.CharField title_ar = models.CharField Right now instead of returning all the above fields in response, I use SerializerMethodField for returning related translation based on user language like below. And for updating or creating I must include those field names with their postfix. class PropertySerialzier(serializer.ModelSerialzier): title = serializers.SerializerMethodField() class Meta: model = Property fields = ( 'title', 'title_en', 'title_fa', 'title_ar', ) @staticmethod def get_title(instance: Property): return getattr(instance, f'title_{get_language()}') How can I write something general that I can use for other models and serializers? Because the project will be going to have a lot of translated fields. And also how to include these fields in the fields variable for updating or creating instances without returning in response? Maybe something like overriding methods in ModelSerialzier class in the Django-rest library? -
how can I avoid duplicating django sql queries when recursing
How to avoid duplicates during recursion in Django. Django shows 12 duplicates with recursive sql queries, how do I avoid them, the code attached from below. Еhe task of the tag is to return the nested menu class Menu(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True, db_index=True) parent = models.ForeignKey( 'self', related_name='kids', blank=True, null=True, on_delete=models.CASCADE ) class MenuView(TemplateView): template_name = 'main/menu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['main_menu'] = kwargs.get('slug', None) return context @register.simple_tag() def draw_menu(slug): menu = Menu.objects.filter(slug=slug).prefetch_related('kids') if slug \ else Menu.objects.filter(parent=None).prefetch_related('kids') return menu {% extends 'base.html' %} {% block title %}{{ title }}{% endblock%} {% block content %} {% load draw_menu %} {% draw_menu main_menu as menu %} <ul> {% for item in menu %} {% include "inc/menu_by_menu.html" %} {% endfor %} </ul> {% endblock %} <li> {% if item.kids %} <a href="{{ item.slug }}">{{ item.title }}</a> <ul> {% for kid in item.kids.all %} {% with item=kid template_name="inc/menu_by_menu.html" %} {% include template_name %} {% endwith %} {% endfor %} </ul> {% else %} <a href="{{ item.slug }}">{{ item.title }}</a> {% endif %} </li> -
The 'rec_file' attribute has no file associated with it. django
I am working on a project where user is uploading a file and will be able to save the same but i found the below mentioned error Html <tr role="row" class="odd"> {%for list in resource_list%} <td>{{list.resource_name}}</td> <td> <a href="{{list.rec_file.url}}" download><img style="max-width: 22px" src="{% static 'img/file.png' %}" ></a> </td> View.py def add_resources(request): title="Add Resources" requesturl = request.get_full_path title = 'Create Clinic' if request.method == "POST": resource_name = request.POST.get('resource_name') resource_file = request.FILES.get('resource_file') resource_instances = Resources.objects.create( resource_name = resource_name, rec_file = resource_file ) resource_instances.save() return render(request, 'add_resources.html',{'title':title, 'requesturl':requesturl}) def index(request): title="Resources List" requesturl = request.get_full_path() resource_list = Resources.objects.all() # FILES = Resources.objects.get(rec_file = request.rec_file) return render(request, 'resources_list.html', { 'title':title, 'requesturl':requesturl, 'resource_list':resource_list, # 'resource_list1':FILES }) error The 'rec_file' attribute has no file associated with it. thanks