Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to connect a docker compose application using django to a private AWS RDS postgres database
How can I connect my Django application to a private AWS Postgres RDS? My current VPC infrastructure is setup like below: Two Public subnets Two Private subnets connected to a NAT Gateway. (NAT is linked to Public subnets) Postgres RDS database is connected to private subnets above Please note that docker-compose is being used because i am using ECS Fargate for the backend infrastructure. I been stuck for days now and cant seem to find the solution, I would really appreciated if someone could help me figure it out. Thank you in advanced. -
My unittests don't work due to connection already closed
I am trying to do unittests but it does not work. Here is my file of tests : class SimpleTest(TestCase): def authenticate(self): useremail = 'myemail@email.fr' userpassword = 'password' c = self.client loggedin = c.login(email=useremail, password=userpassword) self.assertTrue(loggedin, "Not logged") def test_1(self): self.authenticate() c = self.client data = { 'searched': 'companylimit' } response = c.post('/djangoproject/get_information/', data, follow=True) self.assertEqual(response.status_code, 200) logger.info(pformat(json.loads(response.content)['result'])) self.assertIs(type(json.loads(response.content)['result']), int) time.sleep(5) def test_2(self): self.authenticate() c = self.client data = { 'searched': 'management', 'requested': User.objects.filter(is_active=True)[0].uniqueid } response = c.post('/djangoproject/get_information/', data, follow=True) self.assertEqual(response.status_code, 200) logger.info(pformat(json.loads(response.content)['result'])) if type(json.loads(response.content)['result']) == list: self.assertIs(type(json.loads(response.content)['result']), list) else: self.assertEqual(json.loads(response.content)['result'], "") I got django.db.utils.InterfaceError: connection already closed because I have 2 tests whereas with just one test it works. Could you help me please ? Thank you very much ! -
drf-yasg2 doesn't take label from serializer
Here project https://github.com/albertalexandrov/repo2/ with database and data in it. The problem is that I cannot specify labels when displaying in swagger: Serializers for the group view: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' class GroupSerializer(serializers.ModelSerializer): elder = PersonSerializer(label='Elder') teacher = PersonSerializer(label='Teacher') class Meta: model = Group fields = '__all__' As if drf-yasg2 take the first label and then repeates it for another fields. How can I fix it? -
How to render external database table into Django templte?
I have access to the oracle DB table. The table has a huge amount of data and so many entries. It is also updated daily. So far, I have managed to connect to the database. I want to show the data from the DB to my Django template as shown below: Since it is huge data, I want it to show 10 entries at once. It would also be great if I can add filters to it. I managed to get all the data and return it using a function, but what I don't know is how to display the data in a table like this in a template in Django. -
Django - background processing without using any external message-broker and related packages
I have to solve this issue: i have a 4G/4Core Ubuntu server 18.04LTS based machine with my django application, postgres, redis, and some other services that runs off my web application. The nature of the application is quite simple: every 5 minutes i have to collect data and save it to my db from remote devices via SNMP protocol, the total number of devices is around 300. I want to start this task without slowing down my application, so i've offloaded this task, i've tried both Threads, Multiprocessing and Django-RQ/python-rq. Now, here are the results: Threads: 1800 seconds Multiprocessing: 180 seconds (using fork method as default context, but i'm having random deadlocks, so is totally unusable after all) Python-RQ and Django-RQ with 12 workers: 180/200 seconds Now, it seems that my operations are all I/O bound, so, excluding the multiprocessing approach, the background worker with Python-rq seems effective, but i'm experiencing that it eats up all my memory. You guys, have a solution? i mean: the multiprocessing way using fork as default context is totally unusable due to the random deadlock..but the python-rq/django-rq solution is functional and heavy! How i can use the multiprocessing module with spawn as default context, … -
Setting the signed in user as field in Django model form
I have a model form in my Django site, and I want it to automatically set the user who is signed in as the 'creator' (one of the fields), without allowing them to change it. This field doesn't need to show up in the form for the user, but it needs to be added to the database. How would I go about this? Here is the relevant forms.py form: class EventForm(ModelForm): class Meta: model = Event fields = ('name','category','descr','start','end', 'location', 'attending', 'creator') labels = { 'name': '', 'category': '', 'descr': '', 'start': 'Start Date and Time', 'end': 'End Date and Time', 'location': 'Location', 'attending': 'Attending', 'creator': 'Creator', } widgets = { 'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Name of Event'}), 'category': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Event Category'}), 'descr': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Description'}), 'start': forms.TextInput(attrs={'class':'form-control', 'placeholder':'YYYY-MM-DD HH:MM:SS'}), 'end': forms.TextInput(attrs={'class':'form-control', 'placeholder':'YYYY-MM-DD HH:MM:SS'}), 'location': forms.Select(attrs={'class':'form-select', }), 'attending': forms.SelectMultiple(attrs={'class':'form-control', }), 'creator': forms.Select(attrs={'class':'form-select', }), } The view just has the form loaded with form = EventForm(), and the template displays form.as_p Thanks in advance for any help. -
save() prohibited to prevent data loss due to unsaved related object 'user' with Foreign Keys
I am trying to POST a new User in User table and assign attribute to this user in the next related table UserAttribute. UserAttribute table contains 'user' field, which is foreign key to the User table. User.id = UserAttribute.user My POST method creates a new record in User table, hovewer I can not create relation in UserAttribute table. I am getting: save() prohibited to prevent data loss due to unsaved related object 'user'. It is strange because the User is successfully created in User table. I tried to save record in two ways. You can find the code on belove. What is more, I tried transactions too. models.py class User(models.Model): id = models.IntegerField(primary_key = True) email = models.CharField(unique=True, max_length=180) roles = models.JSONField(default=dict) password = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) firebase_id = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(default=now) progress_sub_step = models.IntegerField(blank=True, null=True) step_available_date = models.DateTimeField(blank=True, null=True) progress_step = models.IntegerField(blank=True, null=True) active = models.IntegerField(default=1) last_login_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'user' class Attribute(models.Model): name = models.CharField(max_length=255) value = models.CharField(max_length=255) class Meta: managed = False db_table = 'attribute' class UserAttribute(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'attribute') attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) class Meta: managed = … -
Django throws too many values to unpack (expected 2) when I return a render
When I return a render from a function-based view in Django, it is giving the error: too many values to unpack (expected 2). I am giving the render 3 values (request, template_name, context), but the docs say it should be ok, and it has worked elswhere. Here is my code: View: @login_required def updateview(request, pk): if request.method == "POST": instance = get_object_or_404(Listing, tag=pk) updateform = ListingUpdateForm(request.POST, instance=instance) if updateform.is_valid(): updateform.save() listing = updateform.instance messages.success(request, "New Listing Created") return redirect(reverse('main:listingdetails', kwargs={'pk': listing.tag})) else: messages.error(request, 'Please correct the error below.') updateform = ListingUpdateForm return render(request, "main/createlisting.html", context={"updateform":updateform}) Template: {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{updateform}} <button type="submit">post</button> </form> {% endblock %} Form: class ListingUpdateForm(forms.ModelForm): countryList = (("US", "United States"), ("UK", "United Kingdom")), country = forms.ChoiceField(choices=countryList) class Meta: model = Listing fields = ('title', 'description', 'price', 'country') Thanks for any help. -
Python Django ManyToManyFields
When adding a new quest it is not added to the Score prize model. What do i have to do to fix it? class Quest(models.Model): task = models.CharField(max_length=200, null=True) grand = models.IntegerField(default=1, null=True) class Score(models.Model): prize = models.ManyToManyField(Quest) points = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) -
When i try to connect DB using env variable then i am getting [password authentication failed for user "root"] Django
When I try to connect DB with env variable in setting.py then I am getting an error. (password authentication failed for user "root") And if we try to connect DB with static credentials in setting.py then it's connected. I am getting errors in Django and DB Postgres. Please help. TIA -
Create serialization with data from two tables
Good evening everyone, I need help to be able to serialize the data as "Desired result" but I'm only getting the result of the image "Result I'm getting", can someone help me? I've tried some other ways but I wasn't successful, I ask you not to judge my code as I'm a beginner Thank you! Desired result "total_amount": 20000, // Valor total da compra sem desconto "total_amount_with_discount": 19500, // Valor total da compra com desconto "total_discount": 500, // Valor total de descontos "products": [ { "id": 1, "quantity": 2, "unit_amount": 10000, // Preço do produto em centavos "total_amount": 20000, // Valor total na compra desse produto em centavos "discount": 500, // Valor total de desconto em centavos "is_gift": false // É brinde? }, { "id": 3, "quantity": 1, "unit_amount": 0, // Preço do produto em centavos "total_amount": 0, // Valor total na compra desse produto em centavos "discount": 0, // Valor total de desconto em centavos "is_gift": true // É brinde? } ] } Result I'm getting [{"total_amount":"1000.00","total_amount_with_discount":"900.00","total_discount":"100.00","products":[1]}] models.py from django.db import models class CartItem(models.Model): cart = models.ForeignKey("Checkout", on_delete=models.CASCADE, verbose_name='Checkout', related_name="cart") item = models.ForeignKey("Product", on_delete=models.CASCADE, related_name="cartItens") quantity = models.CharField(max_length=5, verbose_name="Quantidade") line_item_total = models.CharField(max_length=5, blank=True) class Meta: verbose_name = 'Itens dos … -
Is it possible to nest two different model serializer into one with no foreign key relation
I have two models as:- Organization:- id name OrganizationOwner:- user(foreignkeyrelation(User)) Organization(foreignkeyrelation(Organization)) I am trying to create a serializer like this:- class OrganizationOwnerSerializtion(serializers.ModelSerializer): class Meta: model = OrganzizationOwner fields = ('user',) class OrganizationSerialier(serializers.ModelSerializer): org_owners = OrganizationOwnerSerializtion() class Meta: model = Organization fields = ('id', 'name', 'org_own',) with the above serializers, What I am trying to do is, populate the org_owner field with the user instances and overwrite the create method to create org_owner by fetching the organization instance to it manually. But, however I a getting this error:- Got AttributeError when attempting to get a value for field `org_owner` on serializer `OrganizationDetailSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Organization` instance. Original exception text was: 'Organization' object has no attribute 'org_owner'. -
Django why infinite pagination not working and taking me to next page?
it's taking me to next page when I am clicking on load more button. I want my content will be load dynamically in same page or without go to next page. here is my code #I am loading those js in my base.html <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="{% static 'theme/js/jquery.waypoints.min.js'%}"></script> <script src="{% static 'theme/js/infinite.min.js'%}"></script> <script src="{% static 'theme/js/jquery-2.2.4.min.js'%}"></script> here is my html page code where I want to implement infinite pagination <div class="infinite-container"> {% for i in content %} #my others code.... {%endfor%} </div> {% if content.has_next %} <a class="infinite-more-link" href="?page={{ content.next_page_number }}">More</a> {% endif %} <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[1] }); </script> When I am clicking in more button it's taking me second page but I don't want to go second page. Why content not loading in same page? why it's taking me to next page? how to load content dynamically without go next page? -
Django Unit Tests Fail Because of "i18n_pattern"
Today I learned about internationalization and added it to my project, but after I finished localization I tried to run tests and almost all of the tests failed. The first thing that came to my mind was that it was because of the Custom Exception Handler. I changed the lines but nothing improved. Then I remembered the other possibility. It must have happened because of i18n_patterns. I removed that pattern and tried again, tests completed successfully. How can I solve this problem? Traceback Traceback (most recent call last): File "E:\!Staj\bookorbooks\bookorbooks\manage.py", line 22, in <module> main() File "E:\!Staj\bookorbooks\bookorbooks\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\commands\test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\test\runner.py", line 728, in run_tests self.run_checks(databases) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\test\runner.py", line 665, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\commands\check.py", line 63, in handle self.check( File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = … -
Django + Get Cached data and manipulate
how to get the cached data in below extended viewset in django ? Base Viewset class BaseViewSet(ListAPIView): http_method_names = ['get', 'options'] permission_classes = [IsAuthorizedUser] @method_decorator(cache_page(settings.VIEWSET_CACHE_TIMEOUT)) def list(self, request, *args, **kwargs): return Response(data={"message":"somedata"} New Viewset class NewViewSet(BaseViewSet): group_permissions = { 'GET': ( roles.New, ) } -
Flatten List of Objects in Django Rest Framework
I am using Django Rest Framework (DRF) and am trying to create a custom serializer that flattens a list of objects to a list of strings. I have the following definitions: Models: class MyUser(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50) crn = models.UUIDField(default=uuid.uuid4, editable=False) action = models.CharField(max_length=50) def __str__(self): return f"{self.email} - {self.crn}" class Qualification(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) source = models.CharField(max_length=50) state = models.CharField(max_length=50) def __str__(self): return f"{self.name}" class MyUserQualification(models.Model): myuser = models.ForeignKey( MyUser, on_delete=CASCADE, related_name="qualifications" ) qualification = models.ForeignKey(Qualification, on_delete=CASCADE) name = models.CharField(max_length=50) version = models.CharField(max_length=50) def __str__(self): return f"{self.name} - {self.version}" Serializers: class MyUserQualificationBulkSerializer(serializers.ModelSerializer): id = serializers.CharField(source="qualification.id") class Meta: model = myUserQualification fields = ["id"] class BulkQualificationSerializer(serializers.ModelSerializer): qualifications = MyUserQualificationBulkSerializer( many=True, read_only=True, ) class Meta: model = myUser fields = ["qualifications"] Views: class MyUserDetail(generics.RetrieveAPIView): lookup_field = "email" queryset = MyUser.objects.all() serializer_class = BulkQualificationSerializer When I get my view, I get something like this: "qualifications": [ { "id": "70b019bc-23c3-46e1-9d9f-5f30e10b5c2e" }, { "id": "70b019bc-23c3-46e1-9d9f-5f30e10b5c2e" }, { "id": "aa9ef90c-69c4-43ea-ab5c-10fac32160f6" }, { "id": "e3b0fc09-f143-4801-81dd-6624ad07a590" }, { "id": "937f8253-ae58-4059-9ae5-a9a98e41bf72" }, { "id": "b646765f-0416-4c61-9f8f-3cefe7f10ff7" }, { "id": "94a5b2a4-2470-47b9-aa7d-a59f7f4a5383" } ] What I am trying to do is flatten the view returned … -
Unable to access django user when passed from external url
I am implementing OIDC single sign on and when the user signs out from the external service, they pass back to my site using the /oidc-logout callback URL. However, when this happens I can't get the user info from request. The view function is called but the user is shown as an AnonymousUser (even although they remain logged in in the same browser), and the redirect doesn't happen. However, if I actually visit the url using http://127.0.0.1:8000/oidc-logout/ I can get access to the user, can log them out and run the redirect. urls.py path('oidc-logout/', views.my_oidc_logout_view, name='oidc-logout'), views.py def my_oidc_logout_view(request): user = request.user print('request.user shows: ', user) auth.logout(request) return HttpResponseRedirect(reverse('home')) Is there something I need to do see the user and make the redirect work properly? -
Django User password only works after manually change in terminal
I cant figure out why Django User password is not accepted. I've tried creating multiple users and each time I try to log in Django tells that the username or password didnt match. It must be a password issue because each time I change the password manually in terminal python manage.py changepassword username then the login is successful. I also checked that once the registration of the user is done then a user is added to the database and a hashed password is created as expected. Any ideas what could be wrong here? models.py class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py def register(request): registered = False if request.method == 'POST': user_form = UserCreateForm(data=request.POST) profile_form = ProfileCreationForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) print(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'logo' in request.FILES: profile.logo = request.FILES['logo'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserCreateForm() profile_form = ProfileCreationForm() return render(request, 'companies/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) forms.py class UserCreateForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Lietotājvārds' -
aggregation functions(sum) in Django and Mongo engine
I want to calculate the sum of the amount field in documents which name is 'a' using mongo engine and Django! Transaction.objects.filter(name='a').count() above the line work properly but when using sum and try this Transaction.objects.filter(name='a').aggregate(Sum('amount')) I got an error. I want to know how to use aggregation functions in mongo engine and django. i think it's not similar with the default ORM Django -
CSRF token missing or incorrect - displaying dynamic html content with django and js
I'm trying to load data with ajax using this tutorial. I'm using Django as a framework for my project and unfortunately the data does not load propely, instead I get a following error message: "CSRF token missing or incorrect". I assume I need to somehow insert the csrf token into the request but not quite sure how to achieve this. Below is the code. views.py def ChapterListPL(request): chapter_pl = ChapterPL.objects.filter(status=1).order_by('issue') context = { 'chapter_pl': chapter_pl, } return render(request, 'comics/chapters_pl.html', context) html file <div id="container"></div> <input type="button" value="AJAX Load" onclick="aload();"/> <script> function aload() { var xhr = new XMLHttpRequest(); xhr.open("POST", "{% url 'chapter_pl' %}"); xhr.onload = function () { document.getElementById("container").innerHTML = this.response; }; xhr.send(); } </script> -
How to display products from subcategories in parent categories in Django?
models.py class Category(models.Model): def __str__(self): return self.name parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=60) views.py def category(request, id): category_user = Category.objects.get(pk=id) products = Product.objects.filter(category = category_user) context = {'category_user':category_user, 'products': products} return render(request, 'store/category.html', context) Now products from different categories are separated. I want to display "children" products in main category too, but I don't know how. Pls help. Thank u in advance. -
Why is my checkbox is unchecked after saving?
I have created a checkbutton with Python (Django) like this: in my views.py: def list(response, list_id): ls = ToDoList.objects.get(id=list_id) if response.method == "POST": # If we are POST-ing something (saving, adding items, etc..) print(response.POST) if response.POST.get("save"): # SAVING CHECK-BUTTONS for item in ls.listitem_set.all(): # Loop through all items if response.POST.get("c" + str(item.id)) == "clicked": # Check if it has been clicked or not item.complete = True else: item.complete = False item.save() elif response.POST.get("newItem"): # ADDING ITEM TO LIST txt = response.POST.get("new") # Get text-input by name if len(txt) > 2: # Check for valid input ls.listitem_set.create(text=txt, complete=False) else: print("Invalid") return render(response, "myapp/list.html", {"ls": ls}) and this is my list.html: {% extends "myapp/base.html" %} {% block title %}View List of Items{% endblock %} {% block content %} <h1>{{ls.name}}</h1> <form method="POST" action="#"> {% csrf_token %} <ul> {% for item in ls.listitem_set.all %} {% if item.complete == TRUE %} <li><input type="checkbox" , value="clicked" , name="c{{item.id}}" checked>{{item.text}}</li> {% else %} <li><input type="checkbox" , value="clicked" , name="c{{item.id}}">{{item.text}}</li> {% endif %} {% endfor %} </ul> <button type="submit" , name="save" , value="save">Save</button> <!--Updates checked items --> <input type="text" , name="new"> <button type="submit" , name="newItem" , value="newItem"> Add Item </button> <!--Adds new items --> </form> {% endblock %} … -
Django: Does an expression like blog.user.username execute an additional database operation in django?
Hey guys I am new to django and have a doubt regarding using these expressions a lot. blog.user.username or blog.user.email, etc. Does this execute a database operation like we call User.objects.get(username=blog.user.username) to fetch that info? or is it preloaded when we load the blog instance object, i mean along with this get_object_or_404(Blog, id=id)? -
Mantain relationships between many-to-many columns django-tables2
I'm working on the development of a web with Django and PostgreSQL and I'm using the app django-tables2 to create HTML tables. class SampleTable(ColumnShiftTableBootstrap4): class Meta: model = Sample fields = ("name", "sample_id_sex", "pools", "indexes", "gene_cand_lists",) My database collects Next Generation Sequencing (NGS) data. sample_id_sex is a foreign key (1:N relationship) while pools, indexes and gene_cand_lists are many-to-many columns, the combination of these three rows are unique: in other words, they are related. My problem is that in each row the values are ordered by default. For example, the sample X belongs to the pool CES001 and has the index B2 and the gene list list3 but it also belongs to the pool CES002 with the index A1 and list1. In the table, they should appear like this (, as the separator in the many-to-many columns): sample sex pools indexes gene_lists 12-009 male CES001, CES002 B2, A1 list3, list1 But they appear like this: sample sex pools indexes gene_lists 12-009 male CES001, CES002 A1, B2 list1, list3 The relationships between the three columns are broken. Is there a way to correct this? And the separator could be a newline and not a comma? -
Data is In database but it is still saving the form
if request.method == "POST": form = HayvanEkle(request.POST) if form.is_valid(): if request.POST.get("alan") in Hayvan.objects.all(): return redirect("/") else: form.save() return redirect("/") "alan" is in the database but it is still saving the form. What should I do?