Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
solid_i18n overriding current language
I'm using solid_18n urls just so that the default language is used as root path. I have SOLID_I18N_USE_REDIRECTS = True to redirect to the preferred language which is stored in request.session, however once you select a language, if you try going back to the default language using Django's view i18n.set_language it will redirect back to the other language. You end up stuck at that language. For example, you current language is Spanish and your current path /es/whatever. You try switching back to English, which is the default language, through /i18n/setlang/. But instead of changing the language to English and redirecting to /whatever, it's going back to /es/whatever with Spanish still active. Note that you can still change to non-default languages by setting the language or browsing to the corresponding prefix. For example /de/whatever or selecting it through set_language will work and will set German as current language, store it in the session and redirect accordingly. This is the solid_i18n middleware function: class SolidLocaleMiddleware(LocaleMiddleware): def process_request(self, request): check_path = self.is_language_prefix_patterns_used language_path = get_language_from_path(request.path_info) if check_path and not self.use_redirects: language = language_path or self.default_lang else: language = trans.get_language_from_request(request, check_path) set_language_from_path(language_path) trans.activate(language) request.LANGUAGE_CODE = trans.get_language() And this is Django: def set_language(request): """ Redirect … -
How to get absolute path in Django when using nginx?
I have a django project running on nginx and waitress. Here are the nginx settings: # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name localhost; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias C:/Users/Administrator/Documents/mydjangoproject/media; # your Django project's media files - amend as required } location /static { alias C:/Users/Administrator/Documents/mydjangoproject/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { proxy_pass http://localhost:8080; } In my views.py file, when I use my_url = request.build_absolute_uri(uri) I get http://localhost:8080/ instead of https://example.com How can I accomplish to get that absolute path (https://example.com)? -
BaseSerializer.save() takes 1 positional argument but 2 were given; Django rest Framework
Here is my error message TypeError at /users/auth/registration/ BaseSerializer.save() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://127.0.0.1:8000/users/auth/registration/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: BaseSerializer.save() takes 1 positional argument but 2 were given Exception Location: C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\dj_rest_auth\registration\views.py, line 85, in perform_create Serializers Here is my serializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'email', 'first_name', 'last_name', 'occupation', 'phone', 'sex'] -
HStore.DictionaryField returns a string when this part of the code exist in Django. Not sure why
Will try to explain this as best I can. The snippet of code see below screenshot (narrowed it down to line 358) causes models with HStore.DictionaryField on, another section of the project, to return a string instead of the HStore Dict object. Removing this section resolves the issue fixes the issue and returns the HStore Dict. Cannot figure out how this snippet of code can affect that. This is in a admin.py class SomeModel(models.Model): allowed_vals = hstore.DictionaryField() -
Django : Upload Files to an container of a Azure Blob Storage
I want to have an application that upload files to an container of an Azure Blob Storage. I started by doing an application that uplod the files in a static media folder. Now I want to change it that the files go the the container. I have three problems to fix : The models.py, where I do not know how I should modify it. What do I do with the moldels.Filefield. I used it to define the folder to upload the file but right now I should not need it, should I ? If I am not wrong, I need it because of my form. This is my view upload. The view works but I am not sure that I did it the best way to upload to the container. Is it possible to do it in a different more efficient or nicer ? Should I add something in my settings.py file ? models.py class UploadFiles(models.Model): User = models.CharField(max_length=200) Documents = models.FileField() PreviousFilename = models.CharField(max_length=200) NewFilename = models.CharField(max_length=200) SizeFile = models.IntegerField() Uploaded_at = models.DateTimeField(auto_now_add=True) views.py from io import BytesIO import os from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from datetime import datetime, timedelta from … -
How i can get a value field from a foreignkey field properly
i want to get a value of a field (named "width") from foreignkey field named square exit on my form to print it on a pdf: Here is the code line that i have used it to get this value("width"): width = float(FormulaireIng.objects.get(square = FormulaireIng.objects.last()).values_list('width')) Here is the models.py: class FormulaireIng(models.Model): square = models.ForeignKey(Square, on_delete=models.CASCADE) class Square(models.Model): width = models.FloatField(verbose_name="Width", max_length=50) an error displayed after developing that: ValueError at /pdf/ Cannot query "4.0": Must be "Square" instance. How i can get a value field from a foreignkey field properly from a model. Thanks in advance. -
Django- how to make a vendor based membership and subscription?
I never saw this on Django tutorials.I was wondering if its even possible and if it is how so can you make a vendor based membership and subscription? -
How to create a record from GET data (form does not pass the validation)
I am confused when I try to insert record from a "GET" request I will try to explain what I want to do. I am creating an application to take inventory of assets. I have 3 tables in my database. I have a main table called fixed asset("ActFijo") where all the assets of my company are registered. Another call Inventory ("Inventario"), which stores the name of each inventory and another call Inventory_detail ("Inventario_detalle"), where the details or assets in which they are being counted are stored to verify that the equipament or furniture is not being stolen in that location. From the main table ("ActFijo") I have to search for the furniture or asset and store it in the detail table ("Inventario_detalle") I'm confused I don't know how to work on a GET request and then do a POST all in one request Do I have to write my code in parts in a GET request and then POST? Or can I do everything in the GET request? This is the code I have so far I don't know if it's ok, please I need guidance For example my code does not pass the validation of the form. if form.is_valid(): … -
When is it appropriate to use SQLite database in production environment?
I have read that one should not use a SQLite database in production environments for a Django or Flask web application. The reason most given are that SQLite databases don't scale well, but others argue they do. Are there other reasons not to use SQLite in production environments? In my application, I an building a Flask (or Django) web site to run on a Raspberry PI Zero W for a single user to control some machinery. The machinery does pose a health risk to others in the vicinity of the machinery, so the code needs to be as error free as possible. Are there any pitfalls to using SQLite for the app, or do I need to use MySQL instead. Why? Thanks, Mark -
Which code is better for readability? Is this a bad practice?
Hello I have a code that looks more or less like this (in views) if request.method == "POST": formset1 = Formset1( request.POST, form_kwargs={"id": id}, prefix="form1" ) formset2 = Formset2( request.POST, form_kwargs={"id": id}, prefix="form2" ) if ( form.is_valid() and formset1.is_valid() and formset2.is_valid() ): service = Service() try: service.save(form, formset1, formset2) except ValidationError as e: form.add_error("some error", e) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) return redirect("list") else: formset1 = Formset1( prefix="form1", form_kwargs={"id": id}, queryset=items1.all(), ) formset2 = Formset2( prefix="form2", form_kwargs={"id": id}, queryset=items2.all(), ) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) However I think the code would be more readable like this: if request.method == "POST": formset1 = Formset1( request.POST, form_kwargs={"id": id}, prefix="form1" ) formset2 = Formset2( request.POST, form_kwargs={"id": id}, prefix="form2" ) if ( form.is_valid() and formset1.is_valid() and formset2.is_valid() ): try: service = Service() service.save(form, formset1, formset2) return redirect("list") except ValidationError as e: form.add_error("some error", e) else: formset1 = Formset1( prefix="form1", form_kwargs={"id": id}, queryset=items1.all(), ) formset2 = Formset2( prefix="form2", form_kwargs={"id": id}, queryset=items2.all(), ) context = { "form": form, "formset1": formset1, "formset2": formset2, } return render(request, "form.html", context) The second option is better in my opinion since there's less … -
Import-Export with "multilevel" models
I am figuring how can I manage this situation with import export using the same excel and differents models with differents djangoapps. I have the following models: # employees/models.py class Employee(models.Model): name = models.CharField(max_length=100) job = models.ForeignKey(Job, on_delete=models.SET_NULL, null=True, blank=True) # jobs/models.py class Job(models.Model): value = models.CharField(max_length=100) department = models.ForeignKey(Department, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) place = models.ForeignKey(Place, verbose_name='Centro de trabajo', on_delete=models.SET_NULL, null=True, blank=True) class Department(models.Model): value = models.CharField(max_length=100) business = models.ForeignKey(Business, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) class Place(models.Model): value = models.CharField(max_length=100) business = models.ForeignKey(Business, verbose_name='Departamento', on_delete=models.SET_NULL, null=True, blank=True) class Business(models.Model): name = models.CharField(max_length=100) On excel I have following values: xls_employee_name, xls_employee_job, xls_business_name I know how to import employee name and his job because Job is directly related by ForeignKey. But how can I import business name? Below is the code for employee name and his job: # employees/resource.py class EmpleadoResource(resources.ModelResource): name = fields.Field(attribute='nombre', column_name='Nombre') job = fields.Field( column_name='xls_employee_job', attribute='job', widget=ForeignKeyWidget( Job, field='value' )) class Meta: model = Employee fields = ('name','job',) skip_unchanged = True def before_import_row(self, row, **kwargs): self.job = row["xls_employee_job"] def after_import_instance(self, instance, new, row_number=None, **kwargs): Job.objects.get_or_create(name=self.job) Is it possible to import business name using one excel? I appreciate if someone could guide me. I'm also pretty new with django. -
QuerySet throwing error when calling mode_to_dict
Getting below error when Calling API from Postman. Is it models problem? Error 'QuerySet' object has no attribute '_meta' Internal Server Error: /candidates/CandidateSummary Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 511, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 423, in finalize_response assert isinstance(response, HttpResponseBase), ( AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` [10/Mar/2022 20:21:23] "GET /candidates/CandidateSummary HTTP/1.1" 500 77831 Unauthorized: /candidates/CandidateSummary [10/Mar/2022 20:21:39] "GET /candidates/CandidateSummary HTTP/1.1" 401 58 'QuerySet' object has no attribute '_meta' Internal Server Error: /candidates/CandidateSummary Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-** packages/rest_framework/views.py", line 511, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 423, in finalize_response assert isinstance(response, HttpResponseBase), ( … -
Why Can't I Add Azure DB Extension on Mac?
I am following this guide: https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone&pivots=postgres-single-server After successfully completing Step 1 and Step 2, I get to Step 3: "Install the db-up extension for the Azure CLI: az extension add --name db-up" Yet, when I run this command, I receive the following output: X@Y-MacBook-Pro djangoapp % az extension add --name db-up Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. Retrying ... Failed to delete '/Users/X/.azure/cliextensions/db-up': [Errno 2] No such file or directory: '/Users/X/.azure/cliextensions/db-up'. You may try to delete it manually. An error occurred. Pip failed with status code 1. Use --debug for more information. Any ideas here? I've tried some of the solutions to similar errors I've found on Stack/GitHub, but so far no luck. The goal is to get a Django app deployed to Azure with a connected DB also on Azure. Thanks! -
django custom function for filter query
I've a field in my model called, test_data = models.TextField(...), and the model is called MyOrm and this test_data contains data which is actually string, some holds JSON data, and some reference to blob-url. Now I'm trying to streamline my data. So I want to filter all the MyOrm object whose test_data ain't JSON. I'm just storing/trying to store some meta-data along with url, then I will convert them. Can anyone suggest me a way to do so?? pseudocode: select all my-orm where is_not_json(my-orm.test-data) -
How to compare data from two models in Modelform Django
I'm creating an ebay like auction site where users can bid on an item they like and if the bid is higher than the last bid, the bid amount displayed would update to the newest bid. I want to run validation on the modelform to compare the first amount (that the person that created the listing) inputted with the last bid (that the new user inputted). The problem is that they are in two different models and I'm not sure how to validate both without an error FORMS.PY class BidForm(forms.ModelForm): class Meta: model = Bids fields = ['new_bid'] labels = { 'new_bid': ('Bid'), } def clean_new_bid(self): new_bid = self.cleaned_data['new_bid'] current_bid = self.cleaned_data['current_bid'] if new_bid <= current_bid: error = ValidationError("New bid must be greater than the previous bid") self.add_error('new_bid', error) return new_bid MODELS.PY class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding', null=True) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.IntegerField() done_at = models.DateTimeField(auto_now_add=True) VIEWS.PY @login_required def make_bid(request, … -
when admin updates user profile how to access that obj in views and perform some task in django
when admin updates user profile how to access that obj in views and perform some task in django i have user model and when user creates new account by default his id is deactivated but when admin activate their account from admin panel by change the user model field "is_active" to True the i want to send that user an email and some other task also so how to get that user's object that activated by admin -
Django Python: Why does decrypting a file fail?
I'm using https://github.com/eblocha/django-encrypted-files to encrypt files uploaded through Django. It uses AES in CTR mode to encrypt files via an upload handler. I'm trying to manually test the file encryption and decryption by uploading a file via Django form and the retrieving the file via FTP and decrypting it locally. But I find I can't decrypt the file locally using the python shell; the decrypted file is the same as the encrypted file, except the encrypted file has about 15 more characters at the beginning of the file. I've installed cryptography 36.0.1 https://pypi.org/project/cryptography/ locally, and pip is up to date. This is what I'm trying: $ python3 >>> AES_KEY = b'\x1......8f\xdd' // same key as in Django >>> AES_KEY.hex() '1a3ef8c....7e8fdd' // output >>> full = open ("decrypt.txt", 'rb') >>> save=open("decrypted.txt", "wb") >>> read = full.read() >>> save.write(read[16:]) >>> read[:16].hex() '69djeu....9b' // output >>> exit() At this point, the file decrypted.txt is saved, but it's the same as the encrypted file, except the encrypted file has about 15 more characters at the beginning of the file. How can I decrypt the file decrypt.txt to decrypted.txt? Should I use a different Python library locally other than cryptography? -
Coverage html report in django python application created htmlcov folder with files, however each file has strange prefix
i am learning how to use coverage package for evaluating which statements in django/python application are covered by unit tests and which are not. I ran command: coverage run --source "APP" manage.py test && coverage report && coverage html , which created htmlcov folder and multiple html-files inside it. Each file corresponds to the .py file, however in the beginning of each file-name , i see a strange prefix, something like this: "d_10d11d93a0707d03_example_py.html" instead of expected "example_py.html". I wasn't able to google any explanations to this. Please help if you know why is this happening and how to avoid this prefix if at all possible. Thanks! -
Textinput with ModelChoiceField
I yesterday asked this question without success but I have still been working on the problem. Save user input which is a string as object in db . In short the question yesterday described how I wanted to have a registration key in my registration form to be able to restrict who can register themselves. What I have done now is in the forms.py file have I created a key field as a ModelChoiceField with a textinput as the widget. When I write a key which exists in the DB I get the following error: "Select a valid choice. That choice is not one of the available choices.". I can't use Select as the widget as that would display the keys for the users. I tried both methods in this post but without any success. So the question know is, how can I have a TextInput with a ModelChoiceField? -
Wagtail RichTextField - Make admin edit field wider/taller and allow resizing
I recently came across a setting that changes the RichTextField in Wagtail admin to be "full size", ie it was wider and taller, and it maybe even allowed the user to resize the field (not sure about that). I cannot recall what that setting was or where it was used. I believe it was a settings.py feature but I am not having any luck finding it. How can I enable the "full size" Wagtail RichTextField? -
How to display data in the same column of two fields of the model depending on the option chosen from the radio button in Django?
I have a question. It turns out that I have a form that when you click on a radio button, certain inputs are enabled, and when you click on another radio button option, other inputs appear. The inputs save different information depending on the option you chose in the radio buttons, for example, in one input you have to put the name of the person, in another input it is the name of the corporation. When displaying the information in the list, I would like a column to say 'Name' and either the client name or the corporation name to appear. I would not like to place two columns, one that says client name and another corporation name, but in only one that says name, they appear. How can I do that? This is how i have my html and this is how I would like it to be html <form method="post"> {% csrf_token %} <div class="d-flex justify-content-between"> <a href="{% url 'Clientes:clientes_add' %}"> <button type="button" class="btn btn-success mb-3 waves-effect waves-light" onclick="addNewCustomer()">Add new</button> </a> <div class="col-md-6 mb-3 d-flex align-items-center"> <label class="m-0 col-md-2 text-right">Date range:&nbsp;&nbsp;</label> <input type="date" name="fromdate" class="form-control"> <input type="date" name="todate" class="form-control"> <input type="submit" value="Search" class="btn btn-light"> </div> </div> <div class="card"> … -
Django Elastic Beanstalk to RDS MySQL problems connecting
I'm trying to connect my Django Elastic Beanstalk to my RDS MySQL. My Django works with my RDS MySQL through localhost, but when trying to upload my Django to Elastic Beanstalk I get "failed to deploy application" and AWS shows errors (below). My project has mysqlclient in requirements.txt, like here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-rds.html According to that page, that should be enough. I've of course tried to search for similar questions but haven't had success so far. I've noticed that many questions refer to needing a packages.config file inside .ebextensions, I tried many of those suggestions without success. Is that the problem? Why wouldn't that be mentioned on the AWS page? × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-r0dz9d2g/mysqlclient_f2b5c53e43a648c284b06f7af63d9855/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] -
How to handle open sourcing elastic beanstalk Django applications / should .ebextensions be in my .gitigore?
I am building my personal website using Django (I'm a beginner) and I am learning how to deploy my application to AWS, the tutorial I am following tells me to create the .ebextentions folder with the django.config file inside of it. Is it safe/does it make sense to have this inside a github repo or not? Thank you in advance! -
Calling Django view does not execute the function when called more than once
Spring function in Django Views is executed well when called once, but not executed when called twice. Any help would be appreciated. views.py The below is Spring function in views.py. "spring: try starts" is printed when the function is called once but nothing appears in terminal when the function is called for the second time. @api_view(['GET']) def spring(request): try: print("spring: try starts") pc = seasonCheck("spring") return StreamingHttpResponse(gen("spring",pc), content_type='multipart/x-mixed-replace; boundary=frame') except Exception as ex: return HttpResponse(ex) seasonTest The below is where Spring function is called. Whenever the user clicks the button, seasonTest has to be executed. As mentioned above, however, Spring function is not executed when the user clicks the button more than once. function seasonTest(season) { if (season == "spring") { setImg('http://localhost:8000/spring/'); } } -
Retrieve filter data on DjangoObjectType
Good morning, I have created with graphene django a DjangoObjectType that returns several pieces of information. Among which I have integrated django_filters to filter the data. Is it possible to retrieve the values of the filters inserted on the frontend side to read them in DjangoObjectType and so return some information? thanks