Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djanga admin custom list_diplay
In the Django admin panel, how do I change admin.py so that each staff can see only their data in the list_display. For example, there is a news site. 2 staffs will add news to the site. A separate account is opened for each staff. Only the news added by that staff should appear in the list of added news. This is how it is done in list_display? Please help. -
How to test registration form in django?
I have a test to check if registration form works correctly but user doesn't create. I don't understand why. For example if in test I use assertEqual(Profile.objects.last().user, 'test1'), it is said that it's Nonetype object. If I check response's status code, it is 200. So I can be sure that page works. And finally If I go to this register page and create a user with the same information by myself it will be created successfully. What is the problem and how can I solve it? Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=36, blank=True) phone = models.IntegerField(blank=True) verification = models.BooleanField(default=False) quantity_posts = models.IntegerField(default=0) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('information', args=[str(self.pk)]) Form: class RegisterForm(UserCreationForm): city = forms.CharField(max_length=36, required=False, help_text='Город') phone = forms.IntegerField(required=False, help_text='Сотовый номер') class Meta: model = User fields = ('username', 'city', 'phone', 'password1', 'password2') View: def register_view(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() city = form.cleaned_data.get('city') phone = form.cleaned_data.get('phone') Profile.objects.create( user=user, city=city, phone=phone, ) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) part of main urls: path('users/', include('app_users.urls')) part of app urls: path('register/', … -
How to post file and parameter with Ptyhon requests?
I am creating a project with Django. I want to post a file and a parameter (sector) with python-requests. I created a function for that but I cannot add a parameter. Here is my code: def mytestview(request): form = PDFTestForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): pdf = form.save() sector = "default" file_address = ("C:/user/otc/"+pdf.pdf.name) url = 'https://api.myaddress.com/pdf' files = {'upload_file': open(file_address, 'rb')} values = {'upload_file': file_address} r = requests.put(url, files=files, data=values, headers={'Authorization': 'Bearer my_token'}) print(r) # <Response [415]> else: messages.error(request, 'Please, upload a valid file.') context = { 'form': form } return render(request, 'testthat.html', context) Note: { "sectorInfo": { "code": "string", "name": "string" }, "bill": { "id": 0, "name": "string", "size": 0 }, } -
Want to pass json array as django variable inside javascript
I have a json array and I want to pass this inside a javascript variable, inside the django template. I am able to access the variable inside django template {{variable}} . But not able to access this inside the javascript.This is my variable: [ {'Book ID': '1', 'Book Name': 'Challenging Times', 'Category': 'Business', 'Price': '125.60' }, {'Book ID': '2', 'Book Name': 'Learning JavaScript', 'Category': 'Programming', 'Price': '56.00' } ] I have used {{variable|safe}} inside the js but not working. Plz let me know where I am making the mistake. -
Django REST FRAMEWORK + django admin data save
I am not able to save my rest API data to my another Django Project. How I can populate another rest API data to my Django admin database ? -
Sorting by favorite category in Django
Good day all. I have a django problem.. I have a dashboard page where one of the field is the total number of items in a person's favorite category.. So in my model there will be a slot where user can pick their favorite category Like for example.. If I register. I can pick django as my favorite backend language.. Now I want to make sure that I get the total number of content in that django category on my dashboard.. If another user picks java.. It should bring out the total number of content in java. If another picks php it should bring out total number of content in php I was to know if it's possible to do Objects.filter(favorite_category) -
Python Django filter avoid overlapping between range dates
I'm having a bit of a logic blank this morning. I get 2 datetime objects from a user (a range), start_time and end_time. Idea is to return an exists if there's an overlap between the input range and an existing schedule time. I tried the following, but I'm far off with the logic. if Schedule.objects.filter(start_date__gte=ts_start, end_date__lte=ts_start).filter(start_date__gte=ts_end, end_date__lte=ts_end ).exists(): Any suggestions would be much appreciated. Thanks! -
django - Multiple uploads to later edit as multiple posts
I'm new to django and I'm doing a music project. I want to select multiple mp3 and upload it and then the form appears to me to edit the parameters for each mp3 separately (example, artist, title, image, etc). upload multiple files in one input, to edit later for separate post. Project https://github.com/Jimmy809/Multimedia/tree/Rama-1 Thx -
Is it possible to get all authors by single query in django
class Author(models.Model): name = models.CharField(max_length=50) class Chapter(models.Model): book = models.ForeignKey(Album, on_delete=models.CASCADE) author = models.ManyToManyField("Author") class Book(models.Model): author = models.ManyToManyField("Author") I am trying to show all related authors when I visit one author detail. To do that currently I do this to achieve this: authors = [] for chapter in Author.objects.get(id=id).chapter_set.all(): authors.append(chapter.artists.all()) Is there any other way to do this by djangoORM -
Django having problem in adding user to specific group
forms.py class UserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') def save(self,commit=True): user = super(UserForm,self).save(commit=False) user.set_password = self.cleaned_data['password1'] user.email = self.cleaned_data['email'] if commit: user.save() views.py def register_view(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = form.save() customer_group = Group.objects.filter(name='CUSTOMER').exists() if customer_group: Group.objects.get(name='CUSTOMER').user_set.add(user) else: Group.objects.create(name='CUSTOMER') Group.objects.get(name='CUSTOMER').user_set.add(user) messages.success(request,'註冊成功! 請按指示登入!') return redirect('login') else: messages.error(request,'註冊無效! 請再試過!') context = {'form':form} return render(request,'customer/register.html',context) When I try to register a new user, the form can be successfully saved and the group CUSTOMER can be added but I have a problem if I want to add that user to the group so are there any methods in order to add the user to the group automatically after that user had registered a new account along with the User model? -
How to add multiple rows to a table in one submission in Django
I am adding an object through the submit button by making a template without using Forms.py. Here I want to add multiple rows in one submission. Because there are times when all but one field have the same value. So, I want to know how to add multiple rows in one submission without submitting every time. [add.html] <form id="add-form" class="forms-sample" method="post" action="/add/" enctype="multipart/form-data"> {% csrf_token %} {% include 'add_form.html' %} <div class="mt-2" style="text-align:right;"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> [add_form.html] <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped text-black">Date {% autoescape off %} <div class="text-danger small" style="line-height: 1rem;">{{ errors.date }}</div> {% endautoescape %} </label> <div class="col-sm-9 form-input-container"> <div> <input autocomplete="off" class="form-control col-sm-12 date" name="date" id="date" value="{{ supporting.date|date:'Y/m/d H:i' }}" > </div> </div> </div> <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped text-black">종류 {% autoescape off %} <div class="text-danger small" style="line-height: 1rem;">{{ errors.kinds }}</div> {% endautoescape %} </label> <div class="col-sm-9 form-input-container"> <div> <select id="kinds" name="kinds" style="margin-top: 4px; margin-bottom: 7px; padding: 1px 0.5rem 0 0.5rem; height: 2rem;"> <option value="">-------</option> <option value="A" {% if "A" == supporting.kinds %} selected {% endif %}>A</option> <option value="B" {% if "B" == supporting.kinds %} selected {% endif %}>B</option> </select> </div> </div> </div> <div> <label class="col-sm-3 font-weight-bold col-form-label pl-3 striped … -
Complex Tabular Data Representation in Angular from an API
I am trying to represent this table in angular13 I have created a backend API with Django Rest Framework with the following structure: FieldHead:{id,name} e.g Production FieldProperty: { id, name,FieldHead} e.g PRODUCTION in HRS Product: {id,name,weight} e.g.20ltrs Supplier: {id, name} e.g. ABZ, XYZ ProductPropertyCost:{FieldProperty,Product,Supplier,cost} I am trying to find the best format I can return the data inorder to represent it in this format for every Supplier and how to represent it like this -
Model serializer without any fields
I would like to have serializer which only validate instance field "default" and return nothing. I want do that without picking any fields but I'm receving an error that i need to pick some fields or use all_, can you please help me what i can do then ? class PaymentMethodDefaultSerializer(serializers.ModelSerializer): class Meta: model = PaymentMethod def save(self, **kwargs): instance = PaymentMethod.set_as_default(self.instance) return instance @staticmethod def validate_default(value): if value: raise serializers.ValidationError( 'There is an default payment' ) return value -
Model class computedfields.models.ComputedFieldsAdminModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm trying to add a calculated field to my model (i want the field to be stored in the model/ the admin panel/ and in the database) PS : I'm not sure if it's the right method to add calculated columns to my model. i'm trying to use computedfields and i have this error RuntimeError: Model class computedfields.models.ComputedFieldsAdminModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. models.py : from asyncio.windows_events import NULL from email.policy import default from msilib import type_valid from pyexpat import model from unittest.util import _MAX_LENGTH from django.db import models import computed_property from computedfields.models import ComputedFieldsModel, computed, compute class MyProject(models.Model): Compte_Analytique = models.CharField(max_length=30) Libelles = models.CharField(max_length=500) Realisation= models.CharField(max_length=50) Prévision = models.CharField(max_length=50,blank=True,default=0) @computed(models.CharField(max_length=500), depends=[('self', ['Realisation_cum_total', 'Prévison_de_cloture','Prévision_2020','Reste_a_realiser'])]) def CGI(self): cloture=self.Realisation +self.Prévision return cloture def __str__(self): return self.Libelles``` settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'home.apps.HomeConfig', ] apps.py: from django.apps import AppConfig class HomeConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'home' -
Django-stubs doesn't ignore import
I've tried to configurate pre-commit + mypy + django-stubs, so I have error when i try to commit. ModuleNotFoundError: No module named 'environ' My configs: .pre-commit-config.yaml - repo: https://github.com/pre-commit/mirrors-mypy rev: '' hooks: - id: mypy exclude: "[a-zA-Z]*/(migrations)/(.)*" args: [--config=setup.cfg, --no-strict-optional, --ignore-missing-imports] additional_dependencies: [django-stubs] setup.cfg [mypy] allow_redefinition = True check_untyped_defs = True ignore_missing_imports = True incremental = True strict_optional = True show_traceback = True warn_no_return = False warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True plugins = mypy_django_plugin.main show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.local [mypy_django_plugin] ignore_missing_model_attributes = True [mypy-*.migrations.*] # Django migrations should not produce any errors: ignore_errors = True Does anyone have any ideas? -
ValueError: dictionary update sequence element #0 has length 1; 2 is required on cacheops
I get an error with this line of code in my settings.py for cacheops CACHEOPS = {'letes.*':('all'),} This is the error. ValueError: dictionary update sequence element #0 has length 1; 2 is required -
DRF: Optimization in use_pk_only_optimization?
What is the optimization in use_pk_only_optimization? I am setting it to return False but I am afraid to badly affecting the performance. Best Regards -
How Do I Access Data From a Multi-Table Inheritance Definition?
Straight from the Django Docs.... from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) I've been playing with this all afternoon. The good news is that I can get it to work as long as you don't call your app Abstract... I can see the data in my database so I know it's working...but I can't figure out how to access the data. In the past I have used Class Based Views...this is my first go at using a multi-table inheritance structure beyond class based views. I have tried to do... def get_absolute_url(self): return reverse("App:create_restaurant_detail",kwargs={'pk':self.object.place_ptr_id}) But the url lookup keeps saying not found. I'm trying to figure out how to access the data in the table. Thanks for any thoughts and help in advance. -
ModuleNotFoundError: No module named 'rest_framework'. I have installed djangorestframework and I have 'rest_framework' in INSTALLED_APPS
I am having trouble importing rest_framework from django. I have already installed djangorestframework using 'pip install djangorestframework' and I have 'rest_framework' in the INSTALLED_APPS section in settings.py. I am working in vsCode and I have tried restarting it to see if that would but I'm having no luck. Any ideas on how to fix this? -
Django, accessing the top parent objects from second level parents from child with many to many realtaionship
I have a setup where I have these models. Devices Slideshows Slides The device can have only one slideshow Slideshow can be assigned to many devices The slide can be assigned to many slideshows Now, I am trying to work my way up the tree to get all of the devices that have all the slideshows that the slide belongs to. Lets say I have a hold of the 'slide 1' object. Is there a query that could get me all the devices at the top of the tree? Currently, this is how I am traversing to the top as I need to send a post_save signal, it is working as is but I feel like it is a bad way to do it. and it's hard for even me to follow. I am using related names to go up the tree. related_name=devices related_name=slideshows I was hoping to do something simple like instance.slideshows.devices.all() but that yields related manager errors or even instance.slideshows.all().devices.all() slideshows = instance.slideshows.all() related_devices = [] for slideshow in slideshows: devices = slideshow.devices.all() related_devices = list(chain(related_devices, devices)) for device in related_devices: post_save.send(Device, instance=device) -
django howto use select_related not using local id key
i have made two models where i would like to get them joined on the two name keys. models.py class MODELa (models.Model): ...... nameXX = models.CharField(_("name"), max_length=255, primary_key=True) class MODELb (models.Model): ...... nameYY = models.CharField(_("nameYY"), max_length=255) FKxx = models.ForeignKey(to=MODELa, on_delete=models.CASCADE, null=True) views.py rows = MODELb.objects.all().select_related('FKxx') using debug toolbar, i can see the join is using the id field LEFT OUTER JOIN "MODELa" ON ("MODELb"."FKxx_id" = "MODELa"."nameXX") How do i set it use the local key nameYY? -
DRF set_cookie does not work when frontend is on localhost and backend is on a remote server
I've created a DRF app which the backend is using jwt authentication with httpolnly cookies for authentication and it also uses a enforce_csrf for perventing csrf attacks. from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings from rest_framework.authentication import CSRFCheck from rest_framework import exceptions def enforce_csrf(request): check = CSRFCheck() check.process_request(request) reason = check.process_view(request, None, (), {}) print(reason) if reason: raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CookieBasedJWTAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token to pervent csrf attacks django set a cookie and also a 'csrftokenmiddleware' and compares them. here is the sample code for setting csrf cookie and token: class SetCSRFToken(APIView): permission_classes = [AllowAny] def get(self, request): response = Response() csrf.get_token(request) response.status_code = status.HTTP_200_OK csrf_secret = csrf.get_token(request) response.set_cookie( key = 'csrftoken', value = request.META["CSRF_COOKIE"], expires = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'], path= settings.SIMPLE_JWT['AUTH_COOKIE_PATH'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = False, samesite = 'Lax' ) response.data = {"status": "CSRF cookie set", 'csrfmiddlewaretoken':request.META["CSRF_COOKIE"]} return response i also set : CORS_ALLOW_ALL_ORIGINS= True CORS_ALLOW_CREDENTIALS = True the code works perfect when both frontend and backend are on the localhost, but when i run the … -
Django: Thread causing InMemoryUploadedFile to prematurely close?
Good day, I have a problem where a CSV file, sent to a View and later passed into a new thread for processing, sometimes closes prematurely and I can't figure out why. The behaviour is intermittent and only started happening after I switched to using a new thread to process the file. This is the original way I was processing the file and it worked, but for large files it caused time-out issues on the client: class LoadCSVFile(APIView): permission_class = (IsAuthenticated,) parser_classes = [FormParser, MultiPartParser] def post(self, request): file = request.FILES['file'] data_set = file.read().decode('utf-8') io_string = io.StringIO(data_set) for row_data in csv.reader(io_string, delimiter=',', quotechar='"'): print('row_data:', row_data) return Response({ 'message': 'File received and is currently processing.', 'status_code': status.HTTP_200_OK }, status.HTTP_200_OK) So I now process the file in a new thread like so: class LoadCSVFile(APIView): permission_class = (IsAuthenticated,) parser_classes = [FormParser, MultiPartParser] def post(self, request): request_handler = RequestHandler(request) csv_handler = CSVHandler(request.FILES['file']) # Fire and forget the file processing. t = threading.Thread(target=request_handler.resolve, kwargs={ 'csv_handler': csv_handler }) t.start() return Response({ 'message': 'File received and is currently processing.', 'status_code': status.HTTP_200_OK }, status.HTTP_200_OK) class RequestHandler(object): def __init__(self, request : Request): self.request = request def resolve(self, **kwargs): csv_handler = kwargs['csv_handler'] try: print('Processing file...') csv_handler.process_file() except Exception as e: … -
Django get parameter from url in Template to set CSS
I have a dynamic category menu list in my template that I would like to highlight (set active) when the url parameter matches the menu item. Therefore when the page equals the menu item the category will be highlighted. URL examples: https://[domainname]/training/?category=1 https://[domainname]/training/?category=2 https://[domainname]/training/?category=3 {% for categories in category_list %} <a href="{% url 'training' %}?category={{categories.Category_id}}" class="list-group-item list-group-item-action {% if request.GET.category == 'categories.Category_id' %}active{% endif %}"> {% endfor%} -
Null value of foreign key column in Django Serializer
I'm using ModelSerializer and setting all fields from my Item model, but I have null value in category field when retrieving everything. Item description Item and Category Model As you can see value of category is null