Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Form shows wrong date format while changing element in Django
I need the date format dd-mm-yyyy and I changed it everywhere. The date in the list of elements shows correctly. The database also has a requirement to enter the date in this format. However, when I try to modify an existing element, the form shows a date in the format yyyy-mm-dd and I have to change the date to dd-mm-yyyy each time to make changes to the element, otherwise an error occurs. How can I make the date displayed in the format dd-mm-yyyy by default when editing an element? forms.py class CaseRequestForm(forms.ModelForm): class Meta: model = CaseRequest fields = ('name', 'datebirth') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'datebirth': forms.TextInput(attrs={'class': 'form-control'}), } Models.py class CaseRequest(models.Model): name = models.CharField('Put full name',max_length=255) datebirth = models.DateField('Put date in dd.mm.yy format') def __str__(self): return self.name def get_absolute_url(self): return reverse('caserequest') @property def case_exists(self): return Case.objects.filter(name=self.name, datebirth=self.datebirth).exists() Views.py class UpdateCaseRequestView(UpdateView): model = CaseRequest form_class = CaseRequestForm template_name = 'add_caserequest.html' update_caserequest.py <div> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-secondary">Send</button> </form> </div> In settings.py I already added DATE_INPUT_FORMATS = ["%d.%m.%Y"] USE_L10N = False -
Update score model field using JavaScript in Django
I have created a math game using Django and I use JavaScript in the backend to run the game without a page refresh. I need to update the score field after the game ends. I can't seem to get that to work. The score updates on the frontend but not in the database so when the detail form displays the score is always zero. JavaScript: `window.addEventListener('load', function () { let number1; let number2; operator = document.getElementById('operator').innerHTML; max = Number(document.getElementById('max').innerHTML); if (operator == '+') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); } else if (operator == '-') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); if (number2 > number1) { number2 = number1 number1 = number2 } } else if (operator == '*') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); } else { number2 = Math.floor((Math.random() * max) + 1); numberx = Math.floor((Math.random() * max) + 1); number1 = number2 * numberx } document.getElementById('number1').innerHTML=number1; document.getElementById('number2').innerHTML=number2; document.getElementById('tbInput').focus(); window.addEventListener("keydown", function(e) { if (e.key === 'Enter' || e.keycode === 13) { if (operator == '+') { answer = number1 + number2; … -
Django TabularInline override admin temaplate
I have a class that inherits from TabularInline. I have overridden the template, how do I pass data to this template to output it? class commercial_proposal_productadmin(SortableTabularInline): model = commercial_proposal_product extra = 0 template = "admin/tabular.html" i tried to use the change_view function, but the world value is not displayed in the template def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = {'world':'hello'} return super().change_view(request, object_id, form_url, extra_context=extra_context) -
How to get the IP address of incoming connection in custom PAM module
I am using PAM authentication to authenticate with my linux server. I have created a view on my website through Apache2 where I can use python to manually validate each login through a web shell with facial recognition and two factor authentication. This is working, but I can't seem to recover the IP address of the incoming connection. I need a way to find the IP address of my connection to the server before SSH is connected, in the PAM module which is running Python. I would like to use bash for this. I am trying to execute commands to recover the IP address, I tried using "who" and other commands to see incoming SSH connections to no avail. I also tried using "echo $PAM_RHOST" and "$SSH_CLIENT" and "$SSH_CONNECTION" with no success. -
Django - creating automatically database in postgresql for tests, and deleting it after it
I wonder if there is a possibility to trigger somehow automatic creation of database directly from application's code, only for tests purpose. In the perfect scenario, it should look like: Run the tests in Django Database being automatically created and fulfilled (postgresql) After tests pass, whole database should be deleted. For now what I have, is only fulfilling database with tables, and dropping it after tests, but I can't figure out if there is a possibility to trigger creation of database, so user won't be force to do it manually. I was looking for solution, but couldn't find any proper answer for it. I was trying to find a solution for it in documentation in Django, or postgresql but couldn't find any similar problem. -
Django: convert CharField primary key to IntegerField
I have a model (devices) with a CharField primary key containing integers that I would like to convert to an IntegerField. The problem is the devices are also used as a foreign key in another tables meaning when I change the field in my models.py and run the makemigrations/migrate I keep getting an error prompting me to drop the dependent objects first. How can I change the device primary key to an IntegerField without dropping the dependent objects? models.py class Device(models.Model): id = models.CharField(primary_key=True, unique=True, max_length=255) date_created = models.DateField() class Station(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey('Device', on_delete=models.PROTECT) error when running the migration constraint api_station_device_id_117642ec_fk_api_device_id on table api_station depends on index api_device_pkey HINT: Use DROP ... CASCADE to drop the dependent objects too. -
How do I know if my Django project is ready to be deployed?
I already finished my project that I made with django, and I want to upload it. I already bought the domain, and they are about to host it for me.. once they give me the host, I just upload it and that's it? Or are there more steps to do within the code? What do I have to do?. that is, once everything is uploaded to the host, will everything be seen? And the Admin will continue to work, when in the search engine put /admin/ ???. that is, I wonder what are all the steps to follow so that once I host my page everything can be seen. that is, what things would have to be configured in the congif.py, and other things. I would appreciate a lot if you give me advice/tips/solutions.. What I know is that I have to change the debug to DEBUG=False ... And I don't know anything else, once they pass me the port and other host information, I simply upload the files of my project to the host and that's it, nothing more? Isn't it necessary to write more code to show it? Excuse me, I have never displayed a page