Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value attribute in views
Hello is there a way to get 'value' attribute from HTML template into views.py and use it there?? HTML: <form class="card__delete" method="POST"> {% csrf_token %} <button value="{{item.id}}" class="card__delete__button" name="delete" type="submit">&#10008</button> </form> views.py class TodoView(UserPassesTestMixin, CreateView): model = Item template_name = 'home/todo.html' form_class = ItemCreationForm def test_func(self): return self.request.user.username in self.request.path def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['card'] = Card.objects.get(user=self.request.user, pk=self.kwargs.get('pk')) return context def post(self, request, pk, username): if 'delete' in self.request.POST: Item.objects.get(id=pk).delete() print('deleted') return redirect('home-page') -
Django REST Framework ViewSet Authentication Token issue
I have a small API in my Django project, I've been following tutorials for authentication tokens. I'm able to generate and store tokens, but whenever I do a cURL request to the API, with the token, it always returns unauthenticated, even though the token is correct. The endpoint worked before I applied the token authentication. Any help would be great, code is below: api/views.py from rest_framework import viewsets from .serializers import PlatformSerializer from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from userplatforms.models import Platform class PlatformViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = PlatformSerializer queryset = Platform.objects.all().order_by('user_id') api/urls.py from django.urls import path, include from rest_framework import routers from rest_framework.authtoken import views as auth_views from . import views router = routers.DefaultRouter() router.register(r'userplatforms', views.PlatformViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('authtoken/', auth_views.obtain_auth_token, name='tokenauth') ] api/serializers.py from rest_framework import serializers from userplatforms.models import Platform class PlatformSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Platform fields = ('id', 'user_id', 'platform_reference', 'platform_variables') settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } INSTALLED_APPS = [ 'api.apps.ApiConfig', 'userplatforms.apps.UserplatformsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'rest_framework', 'rest_framework.authtoken' ] -
How to start a celery task again as soon as it's over?
An apply_async() within the task will probably work, it'll schedule the task again repeatedly. Is there a better way to write it? -
Ordering custom fields in django admin
I have a User model with the following fields: #models.py class User(models.Model): ... first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255, null=True, blank=True, default="") last_name = models.CharField(max_length=255) ... I have written a custom field like bellow that can be ordered with first_name, middle_name and last_name: @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ("username", "email", "full_name", "is_staff", "date_joined") list_filter = ("is_staff", "is_active") @admin.display(ordering=("first_name", "middle_name", "last_name")) def full_name(self, user: User): return f"{user.first_name} {user.middle_name} {user.last_name}" But admin.display(ordering=...) doesn't work with multiple fields like above. How to make this custom field ordered by multiple fields? -
Django admin action to download multiple pdfs
I have been trying to make custom Django admin action that allows me to convert html page to pdf and then download that pdf, for each object separately if more than once is selected. and since there is only one request to be sent I know there will be only one response. So I tried to put these pdfs in a zip file and then download the zip.. but What I see at the end is corrupted zip file. No idea where is the problem CODE in admin.py def report_pdf(self, request, queryset): from django.template.loader import get_template from xhtml2pdf import pisa import tempfile import zipfile with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: for item in enumerate(queryset): context = {"transactions": item} template_path = "test-pdf.html" template = get_template(template_path) html = template.render(context) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() print(pdf) file.close() fileNameInZip = f"{item.chp_reference}.zip" archive.writestr(fileNameInZip, pdf) tmp.seek(0) response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename="pdfs.zip"' return response -
error with Django using poetry env when I try to run tests
I have this error with Django using poetry env when I try to run tests only with this command: python manage.py test module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/moegts/.pyenv/versions/3.9.5/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/moegts/python/snacks_crud_project/.venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 6, in <module> from django.test.runner import get_max_test_processes File "/home/moegts/python/snacks_crud_project/.venv/lib/python3.9/site-packages/django/test/runner.py", line 2, in <module> import ctypes File "/home/moegts/.pyenv/versions/3.9.5/lib/python3.9/ctypes/__init__.py", line 8, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' I did reinstall all the setup for the WSL & Ubuntu etc and that didn't solve the problem -
Can not put more parameters in post Django
I have a problem I gets an error post() missing 1 required positional argument: 'pk'. It occured when I added slug into it. Is there any workaround? I would appreciate any kind of help. def post(self, request, pk, username, slug): if 'delete' in self.request.POST: Item.objects.get(id=pk).delete() print('deleted') return redirect('home-page') if 'add' in self.request.POST: form = ItemCreationForm(self.request.POST) if form.is_valid(): form.save() name = form.cleaned_data.get('itemName') item = Item.objects.create(itemName=name) card = Card.objects.get(user=self.request.user, slug=self.kwargs.get('slug')) card.cardItems.add(item) return redirect('todo-page', username=self.request.user.username, slug=self.kwargs.get('slug')) -
Date format in Django Model field with REST API
Building a test exercise for a company using Django Rest API. Stuck at date format in Django Model field. I need format like this %d-%m-%Y, but all data I get in format 2021-12-20. Here is what I've done. models.py created_at = models.DateField(auto_now_add=True, verbose_name='Создана') updated_at = models.DateField(auto_now=True, verbose_name='Обновлена') settings.py DATE_INPUT_FORMATS = ['%d-%m-%Y'] DATE_FORMAT = "d-m-Y" USE_I18N = False USE_L10N = False USE_TZ = False Also I need to get and POST data via API call in this view: GET /drivers/driver/?created_at__gte=22-11-2021 -
Django REST Framework: Exception: Unsupported media type 'application/pdf' in request
I'm using django to upload a file without using model or template or serializer.Django views are being used to upload a file to a third-party server. "UnsupportedMediaType: Unsupported media type "image/gif" in request" is the exception. **I'm using Postman to hit a POST request with a binary body(file).**When debugger comes to file =request.FILE['file'], it throws exception "UnsupportedMediaType: Unsupported media type "image/gif" in request" . API View: def upload_document(request): acct_id = request.query_params.get('client_acct_id') doc_type = request.query_params.get('doc_type') file = request.FILE['file']``` -
Django: Listing queryset results under alphabetical headings
I'm trying to list the results from a query of 'Articles' under alphabetical headings based of the Article Title, eg: A Apples Anteaters B Bees Bats etc I know I could do this manually with querysets and filters within the view but is there a more pythonic approach to this? My initial thought was a pair of for loops within the template, one with the alphabet and the other with the articles, with something like {% if article.startwith({{ letter}}) %} but I don't think that is included with the Django templating language. Model: class Article(models.Model): title = models.CharField(max_length=200) tagline = models.CharField(max_length=75, blank=False, default='Required') author = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null = True ) created = models.DateTimeField(auto_now_add=True) department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) tags = TaggableManager() banner_image = models.ImageField(upload_to='wiki_images/banners', null=True, blank=True) body = models.TextField() I also considered the Django regroup tag but struggling to understand how to pass it the first letter of each articles title. Running Django 3.1 on this project. edit: Typo -
'WorkToDo' object has no attribute 'todoativity_set'
I'm writing an api rest using django-rest-framework but I'm getting the following error: Got AttributeError when attempting to get a value for field `activities` on serializer `WorkToDoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `WorkToDo` instance. Original exception text was: 'WorkToDo' object has no attribute 'todoativity_set'. Models class Activity(models.Model): name = models.CharField(max_length=200) client_price = models.DecimalField(decimal_places=2, max_digits=12, default=0) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) technician_price = models.DecimalField(decimal_places=2, max_digits=12, default=0) class WorkToDo(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) activity = models.ManyToManyField(Activity, through="ToDoActivity", related_name="todos") price = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): if self.price is None or self.price == "": self.price = total_price(self) return super(WorkToDo, self).save(*args, **kwargs) class ToDoActivity(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) work_todo = models.ForeignKey(WorkToDo, on_delete=models.CASCADE) price = models.FloatField(null=True, blank=True) class Meta: unique_together = (('activity', 'work_todo',),) def save(self, *args, **kwargs): if self.price is None or self.price == "": self.price = recomended_price(self) return super(ToDoActivity, self).save(*args, **kwargs) Serializers class ToDoActivitySerializer(ModelSerializer): id = serializers.PrimaryKeyRelatedField(source='activity.id', read_only=False, required=True, queryset=Activity.objects.all()) class Meta: model = ToDoActivity fields = ["id", "price"] class WorkToDoSerializer(ModelSerializer): activities = ToDoActivitySerializer(source="todoativity_set", many=True) class Meta: model = WorkToDo fields = ["id", "device", "activities", "price", "lifting", "order"] def create(self, validated_data): instance = WorkToDo.objects.create(**validated_data) if "activities" in self.initial_data: activity_price = self.initial_data.get("activities") for data … -
Django ORM queries
from django.contrib.auth.models import User from django.db import models class CUser(User): score = models.IntegerField() The custom user has an additional field ("score"), we want to do the following operations using ORM queries only. Every answer must have a single query: Calculate the mean score of all users. Find the user with the highest score. Find if there is any user with score less than 2 (return True/False) Find all the users which have score exactly equal to the mean score (need to calculate mean score again in the same query). Change the score value of all users in a single query to 100 (one hundred) Find all the users which don't have score 10 or 20 Print a list of all the score values from all users excluding the first 10 users. -
how to get a product ID by accessing a product file
I have a file that is part of a product, I need to automate a file attribute (partnumber) that asks for a product attribute, how can I access this information? My models.py: class Produto(models.Model): ... tipoProduto = ForeignKey(TipoProduto, ...) ... class Arquivo(models.Model): revisao = IntegerField() nome = CharField(max_length=30) tipo = CharField(max_length=4, choices=tipoArquivo) tipoArquivo = CharField(max_length=15, choices=tipoArquivoSLD) partNumber = CharField(max_length=16, null=True, blank=True) tipoFabricacao = CharField(max_length=25, choices=tipoFabricacaoChoice) file = models.FileField(upload_to=filePath) my views.py: def GetPartNumber(request, id): partnumberForm = PartNumberForm() file = Arquivo.objects.get(id=id) if request.method == 'POST': partnumberForm = PartNumberForm(request.POST or None) if partnumberForm.is_valid(): pt = partnumberForm.save(commit=False) productTip = 'GC' sldTip = file.tipoArquivo cod = PartNumber.objects.get() year = datetime.date.today().year pt = str(productTip) + str(sldTip) + str(cod) + '-' + str(year) pt.save() context={'partnumberForm':partnumberForm} return render(request, 'produtos/NewPartNumber.html', context) -
Python, Django: Query on combined models?
inside my app I have multiple models, like: models.py: class Company(models.Model): name = models.CharField(max_length=100) class Coworker(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE) As you can see, a Company can contain one, multiple or no Coworker! Is it possible to query Company but also receive the data from connected Coworker? For example something like this: id | Company | Coworker 1 | Company_A | Coworker_A 2 | Company_B | 3 | Company_C | Coworker_B 4 | Company_C | Coworker_C 5 | Company_C | Coworker_D 6 | Company_D | Coworker_E 7 | Company_D | Coworker_F 8 | Company_E | 9 | Company_F | Coworker_G 10 | Company_F | Coworker_H ... My problem is, that I can't query on the Coworker, because I don't want to miss those Companies that have no related data! Thanks for your help and have a great day! -
Django forms not receiving input
I'm using Django's forms.py method to builda form, but am not getting any data when trying to get the input by doing request.POST.get('value') on it. For every print statement that gave a response, I put a comment next to the command with whatever it returned in the terminal. Additionally, I do not understand what the action = "address" is meant for in the form. Finally, the csrf verification was not working and kept returning CSRF verification failed so I disabled it, but if anyone knows how to get this working I would appreciate it. forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Enter name:', max_length=100) views.py @csrf_exempt def blank(request): if request.method == 'POST': get = request.POST.get print(f"get: {get}") # get: <bound method MultiValueDict.get of <QueryDict: {}>> print(f"your_name: {request.POST.get('your_name')}") # your_name: None form = NameForm(request.POST) if form.is_valid(): your_name = form.cleaned_data["your_name"] print(f"your_name cleaned: {your_name}") return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'blank.html', {'form': form}) blank.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <form action="" method="post"> {{ form }} <input type="submit" value="Submit"> </form> </body> </html> -
sphinx documentation not getting docstrings/modules
Hej! :) I want to create a documentation of my django project and using sphinx. I wrote docstring to every function and class which I want to be integrated automatically. I followed this tutorial and everything run. My documentation won't give me the docstring information but myProject.app.views module as an output (for every file in my project) but no information whats in the file. My app.rst looks like that: biodata.stakeholders package ============================ Subpackages ----------- .. toctree:: :maxdepth: 4 biodata.stakeholders.migrations biodata.stakeholders.templatetags Submodules --------- biodata.stakeholders.admin module --------------------------------- .. automodule:: biodata.stakeholders.admin :members: :undoc-members: :show-inheritance: biodata.stakeholders.models module ---------------------------------- .. automodule:: biodata.stakeholders.models :members: :undoc-members: :show-inheritance: # index.rst .. toctree:: :maxdepth: 2 :caption: Contents: .. automodule:: Run :members: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` and I added extensions = ['sphinx.ext.autodoc','sphinx.ext.napoleon'] to the conf.py When running make html I get WARNING: autodoc: failed to import module 'stakeholders.admin' from module 'biodata'; the following exception was raised: No module named 'biodata.stakeholders' Does anyone know what I'm doing wrong or missing? Any help is appreciated! :) -
how to return a global variable for access in different functions
I have a function that returns a render of a html (function 1). I want to change a global variable using formula 1 and the access this edited global variable in another formula (formula 2). In order to do this I think I have to return the global variable in formula 1, so the edited version can be accessed in formula 2. My problem is that function 1 already returns a render request. global_variable = 0 def function1(request): global_variable = 10 return render(request, 'index.html', {}) def function2(request): print(global_variable) excel = open(path, 'rb') response = HttpResponse(excel.read(), content_type="app/vnd.openxmlformat.spreadsheetml.sheet") response['Content-Disposition'] = 'attachment; filename=' + os.path.basename("Excel.xlsx") return response I have tried to just add in the global variable at the end of the function like so: def function1(request): global_variable = 10 return render(request, 'index.html', {}), global_variable except it causes the error 'tuple' object has no attribute 'get' -
How to increase response time in Django rest framework with Celery?
I am trying to increase the ability of the Django rest framework to handle more requests. I wrapped my Django rest framework with Celery. Any suggestions on how to further increase the handling of the number of RPS? Here is my code from celery import current_app from rest_framework.decorators import api_view class SomeViewSet(viewsets.ModelViewSet): queryset = SomeModel.objects.all() serializer_class = SomeSerializer @api_view(('POST',)) def some_post_request(request): serializer = serializer_class(data=request.data) if serializer.is_valid(): address = serializer.validated_data['somedata'] file_path = "usr/" with open(file_path, 'wb+') as fp: for chunk in address: fp.write(chunk) result = some_function.delay(file_path, address) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) @api_view(('GET',)) def some_get_request(request, task_id): task = current_app.AsyncResult(task_id) context = {'task_status': task.status, 'task_id': task.id} if task.status == 'PENDING': return Response({**context}, status=status.HTTP_200_OK) else: response_data = task.get() print(response_data) return Response({**context, **response_data}, status=status.HTTP_201_CREATED) I would appreciate complete answers on how to further improve the performance of the celery and Django rest framework by either modifying the above code or suggesting libraries you have used. For example, I tried using the following and it dropped my RPS from 800 to 450. from asgiref.sync import sync_to_async @sync_to_async @api_view(('POST',)) def some_post_request(request): -
A simple database connection failure in an Angular-Django-MongoDB app
I am just trying to establish a simple database connectionin an Angular-Django-MongoDB application, with a real MongoDB database called myDB that conatins a cluster called consumers. I know my connection string is mongodb+srv://MyUser2021:TestMe@cluster0.j9jz1.mongodb.net/test Just to see if I can get it all to communicate, I have written the following in views.py: @csrf_exempt def consumers(): print("consumers") with its correspondence in urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), # http://localhost:8000/admin/ url(r'^consumers/', consumers), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] In my Angular app, I have written a simple service script for it: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Post } from '../models/post.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { consumersMongodbApiUrl = "http://localhost:8000/consumers"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions); } } When I call some function somewhere else that invokes the addConsumerMongodb method in this service class, I get POST http://localhost:8000/consumers 403 (Forbidden) in my webpage dev console. I have looked at lots and lots of posts on this particular error message, but nothing has helped me so far... Could it be that the consumersMongodbApiUrl should … -
When running the command to make migrations it throws a GenericForeignKey error in django
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.auth.models import User class LikedItems(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_Type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() This is the model that I've created and when I run the following command it give an error. python manage.py makemigrations ERROR: ERRORS: likes.LikedItems.content_object: (contenttypes.E002) The GenericForeignKey content type ref erences the nonexistent field 'LikedItems.content_type'. -
Filling a MultipleWidget from database
I'm trying to get a list of weekday options into a PositiveSmallIntegerField in Django and back to the form. I found a very similar question from the year 2011 which covers the process of having a MultiSelect widget with weekday options, Representing a multi-select field for weekdays in a Django model. Also, there has been an additional question regarding the reverse process, Custo widget based on CheckBoxMultipleSelect for weekdays in Django by user gabn88, which sadly has been deleted since. I tried the approach with the BitChoices class in the first post, and the class itself seems to work. However, I fail to put the selection back to something I can fill the form with. At least that's what I think judging from the error message on my view: Select a valid choice. ['2', '16', '128'] is not one of the available choices. Can anybody help me out, please? -
Populate dropdown using data from firebase database and Django?
Iam creating a web app that displays registered user in a dropdown menu,i have a firebase databse that constain the details but i dont know how to populate dropdown menu using the data,iam new to django and web devolopment.I have seen many article on populating the dropdown from local databse but i cannot find any article which uses data from firebase,So please help. url.py from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), ] view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request,'vl.html') Thanks In Advance! -
Django redirect() doesn't redirect but rather refreshes the same page
view.py @login_required(login_url='index', redirect_field_name=None) def new_character(request): if request.method == 'POST': character_form = CharacterForm(request.POST) if character_form.is_valid(): new_character = character_form.save(commit=False) new_character.creator = request.user new_character.save() # If new_character has a primary key (pk) then it # means it was saved to the database. if new_character.pk: # TODO: For some reason this doesn't work. redirect('list_characters') else: character_form = CharacterForm() return render(request, 'characters/new-character.html', {'character_form': character_form}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.list_characters, name='list_characters'), path('new/', views.new_character, name='new_character'), ] I checked and new_character.pk is coerced to True. However, the redirect doesn't happen and instead the same page is simply refreshed. -
how to change merging two queries to josnResponse - django
i'm trying to merge two queries , i did this models.py class MyDateTimes(models.Model): deadline = models.DateTimeField() class ModelA(models.Model): title = models.CharField(max_length=30) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class ModelB(models.Model): post = models.ForeignKey(MyPosts,on_delete=models.PROTECT) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class MyPosts(models.Model): article = models.CharField(max_length=30) i've to merge ModelA with ModelB , here is what i did from itertools import chain modelA = ModelA.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) modelB = ModelB.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) my_query = list(chain(modelA, modelB)) my_listA = [] my_listB = [] i have to return json response of my_query for i in modelA: item={ 'title':i.title, 'dead_line':i.deadline.deadline, } my_listA.append(item) for i in modelB: item={ 'title':i.post.article, 'dead_line':i.deadline.deadline, } my_listB.append(item) note : because i need to use ForeignKey and OneToOne data thats i couldn't use serialiser function i want to do it into one list to return JsonResponse , in order to callable into ajax call ! thank you in advance , please let me know the most efficient way to achieve that -
How to add custom page for 403 error django
Question as in title. How to set custom page for an error in django. I tried using just in templates new file like '403.html' but it did not work. I tried also this: def handler404(request, exception, template_name="404.html"): response = render_to_response(template_name) response.status_code = 404 return response but I can not import render_to_response