Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tests failling after django and python upgrade
I've upgraded Django from 4.0.5 to 4.1.6 and python from 3.9 to 3.11 I've also upgraded dependencies: pip==23.0 pytest==7.2.1 pytest-django==4.5.2 coverage==7.1.0 pytest-cov==4.0.0 pylint==2.16.2 mock==5.0.1 These are my logs: django-admin test Traceback (most recent call last): File "/usr/local/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 394, in run_from_argv parser = self.create_parser(argv[0], argv[1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 357, in create_parser self.add_arguments(parser) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 54, in add_arguments test_runner_class = get_runner(settings, self.test_runner) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/utils.py", line 394, in get_runner test_module = __import__(test_module_name, {}, {}, test_path[-1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django_coverage/coverage_runner.py", line 31, in <module> from django.db.models import get_app, get_apps ImportError: cannot import name 'get_app' from 'django.db.models' (/usr/local/lib/python3.11/site-packages/django/db/models/__init__.py) -
Incorrect type. Expected pk value, received str
how to post from html form in [enter image description here] (https://i.stack.imgur.com/fevLp.png) django rest framework api i am getting error as Incorrect type. Expected pk value, received str. -
Fullfill drf serializer attribute from dict by key name
Imagine I have a serializer with lower camel-named fields what I have to keep by contract: class SomeSerializer(serializers.Serializer): someField = serializers.CharField() And I have following data to serilaize where I want to keep key names in snake case to follow convention: data = {'some_field': 'I love python'} I want serializer to fullfill its someField from dict some_field key's value serialized_data = SomeSerializer(data=data) serialized_data.is_valid() serialized_data.data['someField'] == 'I love python' What I tried already: DRF serializer source - seems to be applicable to model-based serialzers? DRF serializer method field - seems to be hard to apply when there is few fields of different formats - charfields, datefeilds, intfields and all I need is just to pull values from dict Custom renderers - but they are applied after serialization and validation will fail and will affect whole view Any other suggestions? -
My view does not redirect after processing a form. Used HttpResponseRedirect
I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it. I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/ I have the following files: urls.py: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('test', views.test_view, name='test') ] views.py: def index(request): return render(request, 'index.html', context) def test_view(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): return HttpResponseRedirect('home:index') else: form = TestForm() return render(request, 'test.html', context={'form':form, 'text':'No text yet.',}) template: test.html <div> <form action="home:club-invite" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <hr> <p>Your text: {{ text }}</p> </div> The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing... Am I missing something here? PS:I also tried return redirect('home:index'). Still no success. -
Multiple Databases in 1 Django Project
I am planning to develop a AI-Enabled Stock Market Project using Django & Tensorflow For Clients, I plan to use MSSQL For Stock Tickers, I plan to use MongoDB How do I do it in Django? I am in Planning stage -
Django reduce amount of queries (M2M relation with through model)
I would like to reduce the amount of similar queries. Here are my models: class Skill(models.Model): name = models.TextField() class Employee(models.Model): firstname = models.TextField() skills = models.ManyToManyField(Skill, through='SkillStatus') def skills_percentage(self): completed = 0 total = 0 for skill in self.skills.all().prefetch_related("skillstatus_set__employee"): for item in skill.skillstatus_set.all(): if item.employee.firstname == self.firstname: total += 1 if item.status: completed += 1 try: percentage = round((completed / total * 100), 2) except ZeroDivisionError: percentage = 0.0 return f"{percentage} %" class SkillStatus(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) status = models.BooleanField(default=False) My main problen is related to method skills_percentage, I make too many queries while calculating mentioned value. I have already improved situation a little bit with prefetch_related, but there are still extra queries in Django Debug Toolbar. What else can be done here? I have tried to play with different combinations of select_related and prefetch_related. I thought about other options to calculate skills_percentage but they also required to many queries... Thanks in advance. -
Python Test - I'm not able to get PermissionDenied on Client() get
I'm not finding the way to get when the PermissionDenied error is raised. This test try to catch a Permission Denied on a Django, it is expected just to accept staff user to return a 202 status_code This is the code: from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.test import Client, TestCase from django.urls import reverse from scrapers.models import Scraper class PublicWebTestCase(TestCase): def setUp(self): # Every test needs a client. self.client = Client() # Create staff user (no staff) self.user = User.objects.create_user('juan', 'juan@myemail.com.ar', 'juan') self.staff_user = User.objects.create_user( 'victor', 'victor@lala.com.ar', 'Vitor', is_staff=True ) self.client.raise_request_exception = True # crear un scraper para que haya una vista de el self.scraper = Scraper.objects.create( name='My Scraper', folder="X", ) self.page_url = reverse('scrapers-page') def test_scrapers_page_for_anon_user(self): """ Scrapers view as anonymous user """ self.assertRaises(PermissionDenied, self.client.get, self.page_url) And this is the result I get: Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). Forbidden (Permission denied): /scrapers/ Traceback (most recent call last): File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/lugezz/Dev/lll/stud/scrapers/mixins.py", line 14, in dispatch raise PermissionDenied … -
How to solve subprocess.calledprocesserror command returned non-zero exit status 1 error?
I created a task with celery and I'm calling it in my views. But when I trigger the task it returns an error: [2023-02-17 11:37:41,777: ERROR/ForkPoolWorker-7] Task f.tasks.trigger_model[6edf150] raised unexpected: CalledProcessError(1, ['spark-submit', 'run_trigger.py', '../inputs/Test_Dataset_config.yml', '../inputs/run_mode_config.yml']) Traceback (most recent call last): File "/python3.10/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/sgenv/sgvenv/lib/python3.10/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/tasks.py", line 20, in trigger_model subprocess.run(["spark-submit", "run_trigger.py", main_config, runmode_config], check=True, capture_output=True) File "/app/analytics/sgenv/python/lib/python3.10/subprocess.py", line 526, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['spark-submit', 'run_trigger.py', '../inputs/Test_Dataset_config.yml', '../inputs/run_mode_config.yml']' returned non-zero exit status 1. And here is my code: @shared_task() def trigger_model(main_config, runmode_config): with cd("$HOME"): subprocess.run(["spark-submit", "run_trigger.py", main_config, runmode_config], check=True, capture_output=True) How can I fix it and why it gives me this error? -
wWay to find id in tag
I am creating a followers list to the sidebar. How can I get author_id in my custom tag? @register.inclusion_tag('list_followers.html', takes_context=True) def show_followers(context, author_id): request = context['request'] if request.user.is_authenticated: followers = Profile.objects.filter(name=author_id) return {'followers': followers} _sidebar.html Thanks... I tried to get author_id from views.py to posts_tags.py def author_info(request, author_id): """return following users""" current_user = request.user.id author = User.objects.get(id=author_id) .............. or get author_id in _sidebar.html somehow {% load posts_tags %} ........... <div class="media"> <div class="p-3 border bg-light"> <div class="container"> {% show_followers author_id=here %} </div> </div> </div> but I couldn't... -
Django + React app deployment via zappa on aws
I am currently deploying a django + react app on amazon aws using zappa. The page works as intended as long as I navigate on the page via clicking. However, when I refresh the page I do always get a 404 error. Why is this? The URL that I am located on when refreshing the page is like this: myDomainName/currentPath When I refresh the page, an immediate redirect is caused and the new request is made to: myDomainName/stageName/currentPath Therefore, the URL that I see in the browser search bar when everything is done loading is: myDomainName/stageName/currentPath instead of myDomainName/currentPath. As react does not know this URL with the prepended stageName, it raises a 404 error. My question is: How can I make sure that the URL after loading is of form myDomainName/currentPath? I think the redirect of CloudFront must happen, as its origin is simply located at path: /stageName/currentPath. Thus, I cannot change anything here. Note: Once this problem happened once on a specific page, the next refresh works correctly as CloudFront uses cached data. Any advice is warmly welcome, as it is very frustrating to have a fully functional page, which does not work correctly on page refresh. Cheers -
Query set for many to many object relationship
Need to post many items onetime -many titles- in a titles list from mobile app to the backend, the problem is when use create method within the for loop it gets no record in database & that Type Error -Direct assignment to the forward side of a many-to-many set is prohibited. Use container.set() instead.- when try to use the set() method it's not showing any right case!!!!, the problem is when to use create in order to made many create objects in many-to-many relationship. please guide. models.py class Container(models.Model): name = models.CharField(max_length=200, blank=False) capacity = models.IntegerField( null=False ,blank=False) class Item(models.Model): title = models.CharField(max_length=200, blank=False) container = models.ManyToManyField(container) serializers.py class ContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields = '__all__' class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' Request { "container": { "name": "container1", "capacity": 10, }, "Items":[ {"title":"tl1",}, {"title":"tl2",}, {"title":"tl3",} ] } view.py @api_view(['POST']) def additems(request): data = request.data container = Container.objects.create( name = data['name'] capacity = data['capacity'] ) container.save() for i in Items: item = Item.objects.create( container = container , title = i['title'] , ) item.save() serializer = ContainerSerializer(container, many=False) return response(serializer.data) TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use container.set() instead. … -
How to ignore django expression errors in vscode js file?
Is there any way to ignore these kind of errors (django expressions)? I mean the code works perfectly, but the vscode is triggering those errors. In a way it visually bothers me. -
Django Autocomplete Light - Check all options on click
I have a django autocomplete light, with more than 200 options. Therefore, i want to include a button "select all". I almost managed to do so, with the following code. $('#facility-types').val(['2', '5', '6', '10', '11', '12', '13', '14']); $('#facility-types').trigger('change'); // Notify any JS components that the value changed The problem is, that with django autocomplete light, the option-tags for the select fields are only then created, when the user has manually selected an option. Furthermore, the option-tag has a data-select-2-id that appears me to be kind of random. <option value="12" data-select2-id="127">xxxx</option> Any ideas, how to programatically select all options of a django-autocomplete-light select field? Thank you very much in advance!! -
"detail": "Method \"GET\" not allowed." on DELETE Method even if it's not set to GET (DRF + AJAX)
I'm trying to make a marketplace web project, Whenever I try to delete a Cart Product from cart, it redirects to an API view that shows that the GET method is not allowed. The delete function does not have a separate page, therefore it links to the api itself when the button is clicked. I have double checked the urls of the api and they all are labelled correctly in the api side and in the ajax side when calling its function, yet it still shows said error. Cart Viewset: from rest_framework.response import Response from rest_framework import status, viewsets from cart.models import Cart from cart.serializers import CartSerializer, CartUpdateSerializer from rest_framework.parsers import MultiPartParser, FormParser class CartViewSet(viewsets.ViewSet): parser_classes = (MultiPartParser, FormParser) # Function for adding products to user cart def addto_cart(self, request, *args, **kwargs): import pdb; pdb.set_trace() cartProduct = Cart.objects.filter(buyer = request.user.id) filtered = cartProduct.filter(product = self.kwargs.get("product_id")).first() print(filtered.cart_quantity) # Check if added cart product is a duplicate if cartProduct.filter(product = self.kwargs.get("product_id")).exists(): print("Cart Product is a Duplicate!") serializerUpdate = CartUpdateSerializer(filtered, data=request.data, partial=True) #Only updates cart quantity if serializerUpdate.is_valid(): addedQty = serializerUpdate.validated_data['cart_quantity'] total = filtered.cart_quantity + addedQty serializerUpdate.save(cart_quantity = total) return Response(serializerUpdate.data, status = status.HTTP_200_OK) else: serializer = CartSerializer(data=request.data) if serializer.is_valid(): serializer.save(buyer=request.user) return Response(serializer.data, … -
Atributes behavior according to the situtation in Django
I am trying to add some logic to change attribute in class block. This is my initial code: <div class="accordion accordion-flush" id="accordionFlushExample"> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo"> 2022 </button> So I am trying to implement something like: if current year equal to 2022 it have to be: class="accordion-button expand" else class="accordion-button collapsed" I have tried to add something like this but of course it doesn't work: <button class="accordion-button {% if {{now "Y"}}==2022 %} expand {% else %} collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo"> 2022 </button> How to fix it? -
mypy pre-commit check on a Django project with Pipenv
I would like to run mypy static type checks with pre-commit and thus have the below config in .pre-commit-config.yaml repos: - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v1.0.0' hooks: - id: mypy args: ['--ignore-missing-imports', '--cache-dir', '/dev/null', '--show-error-codes'] However, I get errors like No module named 'mypy_django_plugin', and basically the same for all project dependencies. I am aware additional_dependencies should be used to list dependencies. The thing is, the project has 30+ dependencies and manually listing them here is a bit impractical (same goes for keeping them in sync with Pipfile). I have also read elsewhere (SO, pre-commit GitHub) that installing dependencies dynamically from a requirements file is not supported. So is it somehow possible to populate additional_dependencies from a pipfile.lock? PS: How to have a single source of truth for poetry and pre-commit package version? deals with the same problem, but the solution is Poetry specific. -
data doesn't show on django template
My Views enter image description here My Template enter image description here My Result enter image description here my data enter image description here how i solve it data on django template doesn't show but when i change it is a number it changed -
Django: Deleting multiple objects with a view that requires a object pk?
Hey I got this Code to remove my keys: class AKeysRemove(DeleteView, ProgramContextMixin): model = AKeys template_name = 'administration/keys/remove.html' def dispatch(self, request, *args, **kwargs): return super(AKeysRemove, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('akeys_index', args=[self.get_program_id()]) def delete(self, request, *args, **kwargs): # Get the query parameters from the request is_active = request.GET.get('is_active') category = request.GET.get('category') # Build a Q object to filter AccessKeys by is_active and category q_filter = Q() if is_active is not None: q_filter &= Q(is_active=is_active) if category is not None: q_filter &= Q(category=category) # Check if there are any filters has_filters = is_active is not None or category is not None # Delete the AKeys that match the filter, or just the one AKey if has_filters: queryset = self.get_queryset().filter(q_filter) deleted_count, _ = queryset.delete() if deleted_count == 1: messages.success(request, f"One AKey deleted.") else: messages.success(request, f"{deleted_count} AKeys deleted.") else: obj = self.get_object() obj.delete() messages.success(request, f"AKey {obj} deleted.") return redirect(self.get_success_url()) My url looks like this: re_path(r'^p/(?P<p_id>[0-9]+)/keys/(?P<pk>[0-9]+)/delete/?$', AKeysRemove.as_view(), name='akeys_delete'), Deleting one Single Key works fine, but I build myself a filter to delete Keys from a certain category or if they're active or not (is_active) <div class="row" style="margin-top: 10px"> <div class="col-md-12"> <form method="POST" action="{% url 'akeys_delete' p.id %}" id="delete-akeys-form"> <div class="form-group"> <label for="category-filter">Category:</label> <select … -
Microservices Architecture Django
I am new to microservices architecture. I have a microservice (A) responsible for registering and logging in users. And, I have another microservice (B) responsible for storing the bookings, order form the logged in user. Both microservices (A) and (B) are having a separate database. How can I store the user bookings and orders on microservice (B) based on microservice (A) using a Rest API? I'm using Django Rest framework to build my system. I am unsure how to maintain an interface between two databases. I need guidance with the best approaches to sync data to microservice (B) when a user from microservice (A) make a booking or order -
Django Form - Pass Extra Arguments (Dynamic Form Creation)
I am trying to pass extra parameters (not provided by the Forms) in customize my template In this case I am passing an icon font. class AddForm(forms.Form): def __init__(self, *args, **kwargs): *passing some args* self.fields[field_key] = forms.CharField(**field_args) self.fields[field_key].icon = 'fa-font' template.html {% for field in form%} {{field.icon}} {{field}} {% endfor %} When I render the form to to the view, no icon is printed out. How can I pass extra parameters to a form field? -
DRF Allow AnonymousUser owner with HyperlinkedModelSerializer
When the book owner is authenticated it's ok, but if the book owner is not authenticated this error appears ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000002677F18EE00>": "Book.owner" must be an instance of " CustomUser".. I think this problem is caused by HyperlinkedModelSerializer. The owner of the book is specified in the perform_create() method, which is taken from self.request.user. I want authenticated users or non-authenticated users to be able to create books. models.py class Book(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, # allow Anonymous user on_delete=models.CASCADE, related_name="books", ) title = models.TextField() serializers.py class BookSerializer(serializers.HyperlinkedModelSerializer): owner_username = serializers.ReadOnlyField(source="owner.username") class Meta: model = Book fields = ( "url", "owner", "owner_username", "title", ) read_only_fields = ("owner",) views.py class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) I need your help to fix this problem. Thanks in advance. -
Password shown twice for django register form
I am making django register form, but it shows the password twice. (three times including password conformation) Does anyone figure out the reason> These are source code below. register.html {% extends "defapp/base.html" %} {% block title %}User Register{% endblock %} {% block content %} <form method="POST" class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} RegisterView Class class RegisterView(CreateView): form_class = f.RegisterForm template_name = "defapp/register.html" success_url = reverse_lazy("top") def form_valid(self, form): user = form.save() login(self.request, user) self.object = user return HttpResponseRedirect(self.get_success_url()) class Login(LoginView): form_class = f.LoginForm template_name = 'defapp/login.html' class Logout(LoginRequiredMixin, LogoutView): template_name = 'defapp/login.html' RegisterForm is here. from django.contrib.auth.forms import AuthenticationForm,UserCreationForm from django.contrib.auth.models import User class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label class RegisterForm(UserCreationForm): class Meta: model = User fields = ["username", "password", "email"] -
How to take the data (in for loop) that is output in the terminal and show it on a web page?
I want to make a page where text is entered, and then a function that outputs synonyms of words from this text. My view.py is: def home_view(request): if request.method == "POST": text = request.POST["translate"] print(text) translator = Translator() translate_text = translator.translate(text, src='auto', dest='en') print(translate_text.text) Text = translate_text.text.lower().replace('.', '') word_list = Text.split() # print(word_list) for word in word_list: synonyms = get_some_word_synonyms(word) kk_word = translator.translate(word, src='auto', dest='en') kk_word = kk_word.text if synonyms: print( kk_word, 's synonym is:') for synonym in synonyms: # print(synonym) translate_text = translator.translate(synonym, src='auto', dest='en') print(" ", translate_text.text) return render(request,'index.html') I have this output in terminal. Wanna make web page were you can see something like this. Procedures and systems for identifying and eliminating malfunctions and malfunctions of equipment, networks and systems procedures s synonym is: procedure process systems s synonym is: system identifying s synonym is: identify place eliminating s synonym is: extinguish eliminate get rid of do away with malfunctions s synonym is: malfunction malfunctions s synonym is: malfunction networks s synonym is: network web systems s synonym is: system -
Django REST framework Query Throughput on AWS
I've trying to run a simple django server on amazon lightsail. The server is supposed to be a backend that serves game state to twitch viewers via an extension. I'm currently trying to have each viewer poll my backend every second. Trying a very bear bones read to start I'm essentially storing the game state in memory using django's cache (there's only one tracked 'player' for now) and serving it back to users via the django REST framework. Given that my requests and responses are quite small I'd expect to easily serve at least a few hundred users but I seem to top out of the sustainable CPU usage at around 50 users. Is this expected for this setup? Are there optimizations I can make or obvious bottlenecks? Here's my backend that gets polled every second https://github.com/boardengineer/extension Normal backend reads come in at about 800 bytes. I tried returning empty responses to test if the response size should be optimized but it only made a small difference. I thought of removing header content to further reduce response size but I don't think i found a way to do so correctly. I also tried removing some of my middleware hoping to … -
How to pass change_password.html to replace Django Admin Password Reset
Currently in my urls.py I have the following links for user to reset their password app_name = 'users' .............. path('login/', MyLoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'), path('password/', user_views.change_password, name='change_password'), ............................. ............................. ............................... path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), After the user receives the reset email and clicks on the link to reset password it goes to the Django Admin Style page to reset password. How can I pass the template that I have change_password.html and how can I redirect afterwards to the login page to login