Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting "This field is required" from my Django Form when using Client().post to test even thought form.data shows values in those fields
I'm trying to test some form logic in my views.py and need to simply pass a form to that view in order to do that but I can't figure out why it isn't receiving a valid form when passed using a Client().post from my tests. When using the form from the browser normally it works fine. I'm using Django test Client submitting a form with a POST request and How should I write tests for Forms in Django? as guidance with no luck after looking at many different resources. The errors from form.errors shows name - This field is required address - This field is required However my form.data shows <QueryDict: {"'name': 'foo bar', 'address': '2344 foo st'}": ['']}> The working live form has the form.data as: <QueryDict: {'csrfmiddlewaretoken': ['htR...Rel', 'htR...Rel'], 'name': ['test'], 'address': ['test'],'submit': ['Submit_Form']}> I've played around with getting a "csrfmiddlewaretoken" but I don't feel like that the problem. I've also tried setting the .initial and played around with content type. Is the form.data not what is looked at? form.is_valid() is True before the post to the view.py. Thanks in advance for the help! My tests code is: @pytest.mark.django_db def test_add_bar_with_logged_in_user_form(setUpUser, django_user_model): from ..models.forms import BarForm from django.test … -
Django join through table even if don't match
I'm starting to use Django, but I'm just a beginner. I have a problem with Django Queries, and although I've done a lot of research online, I haven't found any answers that can help me. Models.py: class Articles(models.Model): ID = models.AutoField(primary_key=True) description = models.TextField() price = MoneyField(blank=True, null=True, decimal_places=2, max_digits=8, default_currency='EUR') class Meta: ordering = ('description',) def __str__(self): return self.description class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() Item_ID = models.ManyToManyField(Items, through="Detail", blank=True) class Detail(models.Model): ID = models.AutoField(primary_key=True) article_id = models.ForeignKey(articles, on_delete = models.CASCADE) Intervention_ID = models.ForeignKey(Interventions, on_delete = models.CASCADE) quantity = models.IntegerField(null=True, blank=True, default='1') I would like to be able to create a Query that takes all the records of the 'Interventions' model and all the records of the 'Details' table. The problem is that if an intervention is made, but without having used any article, the intervention itself is not displayed. How can I do? I tried with prefetch_related but it doesn't seem to work. Heartfelt thanks to everyone. -
Sonarqube displaying 0% of coverage and no unittest in django project using coverage.py
I'm working on creating unitest for a django project I installed sonarqube : docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest through docker image and sonar-scanner using this command : docker run -v /home/hind/Desktop/map-manager:/usr/src --network="host" sonarsource/sonar-scanner-cli -Dsonar.host.url=http://localhost:9000/ -Dsonar.login=sqp_e7171bd635104a04d29c523243cf54000946ea7f and I before that I added coverage to my project , I created 23 unitest and all running well except for one that is failling I run tests with : coverage run manage.py run test maps and when I run the report of the sonarqube resultcoverage report and the report is displaying this : Name Stmts Miss Cover --------------------------------------------------- app/__init__.py 0 0 100% app/settings.py 58 10 83% app/urls.py 12 0 100% manage.py 13 6 54% maps/__init__.py 0 0 100% maps/admin.py 141 62 56% maps/migrations/__init__.py 0 0 100% maps/models.py 163 10 94% maps/templatetags/__init__.py 0 0 100% maps/tests.py 195 3 98% --------------------------------------------------- TOTAL 582 91 84% but in sonar-scanner I get 0.0% coverage and nothing in unitest enter image description here sonarsube result I dont know what's the problem so the coverage is not 0.0% -
How to allow multiple IP addresses and use that ip address from different network in django?
Therefore, I need to access my Django project from localhost to some other different network with a different different domain or IP address (my custom domain and ip address). Is there a method to achieve without using any live domain like AWS or GoDaddy? The Django host, ngrok, serveo, and thord parts I tried did not provide a custom domain name or IP. -
Django Machina - display post times in local timezone
I am using django-machina as a forum. I want post times in the forums to be displayed to users in their local times. I have TIME_ZONE = 'UTC' and USE_TZ = True in my settings.py file. I have also installed "pytz." The times are currently displayed in UTC time. I have attempted to use the following in a template: <small>{{ node.last_post.created | localtime }}</small> However this has no effect on the display times. I put this in the template as a test: {% get_current_timezone as TIME_ZONE %} {{ TIME_ZONE }} and it displays "UTC" How can I get the times to display in the user's local time zone? -
Error in AES Encryption/Decryption via python
We have integrated a API through which I am getting a encrypted data. Now in the docs they have given me a software link to decrypt the data. Here is the website they have recommend me to use to decrypt the received data: https://aesencryption.net/ It works fine and I am getting the decrypted data on this website On this website they have given their code they are using for decryption & that is in PHP. I have used chat GPT to convert that PHP code in python with little modification of my own. But it doesn't work with this code. I am mentioning everything that I have and have tried. import hashlib from Crypto.Cipher import AES import base64 class AESFunction: secret_key = None key = None decrypted_string = None encrypted_string = None @staticmethod def set_key(my_key): key = bytes.fromhex(my_key) sha = hashlib.sha256() sha.update(key) key = sha.digest()[:32] AESFunction.secret_key = AESFunction.key = key @staticmethod def get_decrypted_string(): return AESFunction.decrypted_string @staticmethod def set_decrypted_string(decrypted_string): AESFunction.decrypted_string = decrypted_string @staticmethod def get_encrypted_string(): return AESFunction.encrypted_string @staticmethod def set_encrypted_string(encrypted_string): AESFunction.encrypted_string = encrypted_string @staticmethod def encrypt(str_to_encrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) encrypted_bytes = cipher.encrypt(AESFunction.pad(str_to_encrypt).encode('utf-8')) AESFunction.set_encrypted_string(base64.b64encode(encrypted_bytes).decode('utf-8')) @staticmethod def decrypt(str_to_decrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) decrypted_bytes = cipher.decrypt(base64.b64decode(str_to_decrypt)) AESFunction.set_decrypted_string(AESFunction.unpad(decrypted_bytes).decode('utf-8', errors='replace')) @staticmethod def pad(text): block_size = … -
CSRF_TRUSTED_ORIGINS works only with a string, not with a list as expected
Context I am running a Netbox instance, which uses Django. Inside of its parameters, I have to set CSRF_TRUSTED_ORIGINS to the origins I trust for Netbox to work properly. The Netbox instance I use runs inside a Docker container (netbox-docker). Issue I have found out that if I write these as a list, like expected in the documentation (see here), I get a 403 error with the following description: CSRF verification failed. Request aborted. Activating debug mode also tells me this: Origin checking failed - https://myurl does not match any trusted origins., which I do not understand because my variable looks like this: CSRF_TRUSTED_ORIGINS=['https://172.23.0.5', 'https://myurl']. Temporary workaround If I set the variable as a simple string, I do not get any error: CSRF_TRUSTED_ORIGINS="https://myurl" works flawlessly for myurl (of course, it still blocks all the other URLs). Issue (still) That worked for some time, but now I have to add a second domain name referencing my Netbox instance, so I would need to add "https://myurl2" to the trusted origins list. Since having a list does not work here, I do not really know how to proceed. What I have tried I have tried to change the way I assign its value … -
How to send mail to admin from individual mail I'd in Django?
I'm Working on Employee Management System Project, There is three type of user HR, Director and Employee. I want to send record mail to Director mail I'd from Employees individual email ID. How I can implement this feature, I'm working in Django. I'm trying to implement using Django send_mail() function but there is password providing issue, we can't provide email password for all employees. I want to know how i can implement. -
Form type request in Postman for API with nested serializers in Django Rest Framework
I need to pass the nested dictionary which is the mixture of text and file. I created the nested serializer to get the data from API request. What will be my request like in Postman? Request Structure: { "type":"Large", "category":[ { "category_segment":"A", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image": **''' Category A Image File Here'''** }, { "category_segment":"B", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image":**'''Category B Image File Here'''** } ] } Serializer class DataSerializer(serializers.Serializer): category_segment = serializers.CharField() category_features = serializers.ListField(child=serializers.CharField(default='Not Required'),default='Not Required') action = serializers.ListField(child=serializers.CharField()) image = serializers.FileField() class ExtractionSerializer(serializers.Serializer): type = serializers.CharField() category_image = serializers.ListField(child = DataSerializer()) -
Django - How to test an application with millions of users
I want to test a blog application with millions of users particularly where each posts have number of views that is visited by users. Although I tried to login with different browser for each users,its not efficient. How should I test users to login and try this application? Requirements Counts must be real time or near-real time. No daily or hourly aggregates. Each user must only be counted once. The displayed count must be within a few percentage points of the actual tally. The system must be able to run at production scale and process events within a few seconds of their occurrence. Although I tried to login with different browser for each users,its not efficient. -
Passing kwargs into FactoryBoy nested RelatedFactories for pytest
I see so many different ways of doing this that I'm getting a bit of choice paralysis. Problem description I have a top-level FactoryBoy factory, FruitBasketFactory. This defines a RelatedFactory to AppleFactory, a sort of "conduit" factory: AppleFactory defines 2 RelatedFactories: SeedFactory and SkinFactory. Some pseudo code: class FruitBasketFactory(factory.django.DjangoModelFactory): class Meta: model = FruitBasket apple = factory.RelatedFactory( AppleFactory, factory_related_name="fruit_basket" ) class AppleFactory(factory.django.DjangoModelFactory): class Meta: model = Apple fruit_basket = None seed = factory.RelatedFactory( SeedFactory, factory_related_name="apple" ) skin = factory.RelatedFactory( SkinFactory, factory_related_name="apple" ) class SeedFactory(factory.django.DjangoModelFactory): class Meta: model = Seed apple = None num_seeds = 10 seed_color = "black" class SkinFactory(factory.django.DjangoModelFactory): class Meta: model = Skin apple = None skin_color="red" My goal For my tests, I want to set a top-level flag e.g. fruit_basket_factory(apple_type_is_PinkLady=True), and 'pass down state' to all related, dependent factories. In this case, the changes required would be setting: fruit_basket.apple.seed.num_seeds = 5 fruit_basket.apple.seed.seed_color = "brown" fruit_basket.apple.skin.skin_color= "green" Is this possible? I'm imagining some sort of Class Params on each Factory that serve as 'message-passers'? In reality, my conduit factory has around 5-10 RelatedFactories. -
Forbidden (CSRF cookie not set.):- Nodejs 13 with Django
I am trying to send an HTTP POST request from my frontend in Node.js 13 to my Django backend, but I keep getting the error "Forbidden (CSRF cookie not set)." Currently, the application is configured to send an API request to my server to obtain the csrf_token when I open the website. Then, I attempted to send an API request to register with the csrf_token, but encountered the aforementioned error. const respond = await fetch( 'http://127.0.0.1:8000/register/register_user/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken, }, body: JSON.stringify({ name: name, email: email, password: password, passport: passport, trustNode: trustNode, }), cache: 'no-cache', } ); This is my Django settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website_backend', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:8000' ] -
Django model clean function validation error problem
I have a Django model with custom clean function as below: class License(models.Modes): # fields of the model def clean(self): if condition1: raise ValidationError('Please correct the error!') The problem is that, my admin user uploads some file as needed by FileField of License Model, but when I raise the ValidationError file fields are emptied and user is forced to upload the files again. Is it possible to raise the error, but keep the files? -
django primary key auto assigning available id from least value
In django project primary key are assigned automatically. In my model I have some model object with id (=5,6). id (= 1,2,3,4,) is deleted from the DB. Now when I create new object model,django assigning id with the value 7. But I want this to assign in a order like 1,2,3,4 and 7 and so. How can I implement this? I've tried to create a complete different id field with custom logic to assign the available id first,but I was expecting a django built-in function. -
'dict' object has no attribute 'headers': it is coming from clickjacking.py
I have a method that generates pdf cheque for a client. the code as follows @csrf_exempt def generate_pdf(request): body = ujson.loads(request.body) monitoring = Monitoring.objects.filter(tr_id=body['tr_id']).first() if not monitoring: return { "message": MESSAGE['NotDataTrID'] } data = { 'headers': ["Abdulloh",], 'user': monitoring.user, 'tr_id': monitoring.tr_id, 't_id': monitoring.t_id, 'type': monitoring.type, 'pay_type': monitoring.pay_type, 'sender_token': monitoring.sender_token, } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') it should generate a cheqeu in the end. But I am receiving an error from python env it is coming from clickjacking.py. Can anyne help. I am using python 3.9 and centos 7 for operation system -
How do I run 2 processes in the return of a Django view?
I have a django site - does stuff.. when the print button is pressed I need it to run a def() and then return to home return view_xlsx(request, xlspath) return render(request, 'webpage/HomePage.html', {'last_update': lastupdted}) How can I do both Run the view_xlsx ( which downloads in browser) and then return home? I have tried return view_xlsx(request, xlspath), render(request, 'webpage/HomePage.html', {'last_update': lastupdted}) and try: return view_xlsx(request, xlspath) finally: return render(request, 'website/HomePage.html', {'last_update': lastupdted}) They both work independently of each other, but wont seem to work together. Thoughts ? -
Trying to install postgres within docker container and containerizing django project
I am new to docker and web-development generally. When trying to containerize my django-project I run into an error and can't solve it for several days. The error might be silly, but I can't find a solution. I'll be very glad if someone helps me to solve me the problem. Thank you in advance. As operational system I use Ubuntu 22.04 Here is the output after commands docker compose build and docker compose up: [+] Running 2/0 ⠿ Container test_task-db_task-1 Created 0.0s ⠿ Container test_task_container Created 0.0s Attaching to test_task-db_task-1, test_task_container test_task-db_task-1 | test_task-db_task-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization test_task-db_task-1 | test_task-db_task-1 | 2023-06-07 10:46:07.124 UTC [1] LOG: starting PostgreSQL 14.1 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20211027) 10.3.1 20211027, 64-bit test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv6 address "::", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.147 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" test_task-db_task-1 | 2023-06-07 10:46:07.163 UTC [21] LOG: database system was shut down at 2023-06-07 10:45:29 UTC test_task-db_task-1 | 2023-06-07 10:46:07.218 UTC [1] LOG: database system is ready to accept connections test_task_container | Watching … -
Multiple form view, in which JSON fed to one form, constitutes another in Class Based Views
I want to create a class based view in Django that after receiving one form, will translate it to another and then accept the second form (both forms accept files - the first just one, the other several). I have tried the approach with MultiFormsView (you can check the question here): Cannot proceed with multiform view in class based views And then I moved a bit further with Tarquiniuses help with another method: I cannot pass the values between the methods in classBasedView Now the code looks like this: Django: @user_authenticated @user_hkm @translation def firmware_cbv2(request): class Firmware_view(FormView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def get_success_url(self): return self.request.path def form_invalid(self, form): print("the form is invalid") return super().form_invalid(form) def get_context_data(self, message=None, bundle=None,**kwargs): context = super().get_context_data(**kwargs) context['bundle'] = bundle context['message'] = message return context def form_valid(self, form): bundle, message = {}, {} if request.FILES: if len(request.FILES) < 2 and "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) bundle["units"] = units bundle["file"] = { "name": folder_name, "content": json.dumps(content) } message.update({ "type": "info", "content": "The form was parsed successfully" }) except Exception as e: print("there was an error", e) else: print("I am … -
Tagged Posts not Paginating
I have a Django app that displays posts that are created using Django's built-in admin interface. The posts have tags incorporated using django-taggit (https://django-taggit.readthedocs.io/en/latest/) The main page (home.html) is set up to display posts and tags and when a tag is clicked, it takes you to a page (tag_posts.html) with all tagged posts e.g. If i click on a post with the tag 'apple', I am presented with a page that shows all posts tagged with 'apple'. The main page works as intended, as does the pagination for home.html. THE ISSUE: When viewing the list of tagged posts, it is showing the number of posts by the number specifed with paginate_by (in the code it's 2) but not showing me the option to click next/previous or page numbers. What I Have Attempted: I thought it may be the Bootstrap navigation links in the html file but I am using the same as in my home.html, which works. re-factored my class-based view to include the tag as part of the context and supplying to the html as a context variable Used basic html for navigation links The issue lies with TagPostsView Here is my view.py: from django.shortcuts import get_object_or_404, render from … -
what is more often used in practice: FBV or CBV?
I'm new to Django development, so I want to ask people who have more practice - what do they use more often? I'm of course assuming it's CBV since it's easier for others to read, but I'll ask anyway. thanks in advance for your reply -
Django - generate product page with one url and view function?
I have a list of products with product ids. How do i create the function to open the page based on the product_id and user_id? Currently I have in urls.py: path('product/<int:product_id>/', views.product, name='product'), And in my views.py: @login_required() def product(request, product_id, user_id=None): return render(request, 'users/product.html') I am new to Django and could not find an answer searching online... -
Fulltext Search in Django with Haystack/Whoosh - Displaying Search results with tags from models not in results
swarm intelligence, right now i try to implement a database fulltext-search in a Django-project with haystack and whoosh in the backend. Installation, configuration and indexing ist done. Search works as intended. So NOW I'm talking about displaying search results: "side" problem: Results seem to be not sorted. I would like to know, WHERE in the different code-tables from Django (views/forms/serach-index/urls.py) i can set a configuration for the result-ordering? Reason for Question is furthermore: When I am trying to set up the template for displaying the results, it is no problem to use a {{ result.object.last_name }} tag when result is from model, where "last_name" is included.... But if i get results from a child table, what do i have to do to display "last_name" from parent table, too? My search-indexes.py: from haystack import indexes from employees.models import Employees, Employments, Professions, ForeignMissions, \ LanguageAbilities, SecondDegrees, MilCourseDetails, CivCourseDetails class EmployeesIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') titel_rank = indexes.CharField(model_attr='title_rank', null=True) rank_short = indexes.CharField(model_attr='rank_short', null=True) last_name = indexes.EdgeNgramField(model_attr='last_name') first_name = indexes.CharField(model_attr='first_name') prefix_title = indexes.CharField(model_attr='prefix_title', null=True) suffix_title = indexes.CharField(model_attr='suffix_title', null=True) street = indexes.CharField(model_attr='street') building_number = indexes.CharField(model_attr='building_number') postal_code = indexes.CharField(model_attr='postal_code') city = indexes.CharField(model_attr='city') country = indexes.CharField(model_attr='country') employee_number = indexes.CharField(model_attr='employee_number') key_number = indexes.CharField(model_attr='key_number', null=True) … -
Django RESTAPI how to make calculation APIs PUT or POST?
Hi I'm trying to make calculation rest api using django. My objective is to save preprocessed_data(result) into the db table field The process is read raw data path(txt file) from db and calculate using pandas & numpy after that make result txt file save to db preprocessed_data field. this is my models.py class PreprocessData(models.Model): raw = models.FileField( upload_to=_user_directory_path, storage=OverwriteStorage(), preprocessed_data = models.CharField( max_length=200, null=True, blank=True, ) ) and views.py class PreprocessCalculate(APIView): def _get_object(self, pk): try: data = PreprocessData.objects.get(id=pk) return data except PreprocessData.DoesNotExist: raise NotFound #get or put or post which is the best design for api? # PUT API def put(self, request, pk): data = self._get_object(pk) serializer = PreprocessCalculateSerializer(data, request.data, partial=True) if serializer.is_valid(): updated_serializer = serializer.save() return Response(PreprocessDataSerializer(updated_serializer).data) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and serializers.py class PreprocessResultField(serializers.CharField): def to_representation(self, value) -> str: ret = {"result": value.test_func()} return ret def to_internal_value(self, data): return data["result"] class PreprocessCalculateSerializer(serializers.ModelSerializer): preprocessed_data = PreprocessResultField() class Meta: model = PreprocessData fields = ("uuid", "preprocessed_data") my question is when I use the above code. In db "preprocessed_field" is still null... what is the problem in custom field serializer? I choose "PUT" method to calculate raw file, but I think if I use "PUT" it has a problem to change … -
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop class PrimitiveQuerySet(QuerySet): def update(self, *args, **kwargs): super().update(*args, **kwargs) super().using('New').update(*args, **kwargs) class Primitive(models.Model): modified_by = models.CharField(max_length=200, null=True) modified_on = models.DateTimeField(null=True) deleted_by = models.CharField(max_length=200, null=True) deleted_on = models.DateTimeField(null=True) deleted_flag = models.BooleanField(null=True, blank=True, default=False) objects = PrimitiveQuerySet.as_manager() def save(self, *args, **kwargs): # Dump data into default database super().save(*args, **kwargs) # Save the same data to the new database using_db = kwargs.pop('using', None) # Extract 'using' parameter self._state.db = using_db # Set the target database for saving self.save_base(using='New', force_insert=False, force_update=False ` I got the approach how to update and save data in two db but issue is it is going into infinite loop -
Django Chatterbot-how to add "default-response" to settings .py?
In my "django" application in settings.py I have: CHATTERBOT = { 'name': 'bot1', 'storage_adapter': "chatterbot.storage.SQLStorageAdapter", 'logic_adapters': [ 'chatterbot.logic.BestMatch', ] } How do I add the auto default response parameter? I tried countless ways but it doesn't work.