Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Which is more efficient filter query in django and why?
1 : Model1.object.filter(column1="XYZ").filter(column2="ABC") 2 : Model1.object.filter(column1="XYX", column2="ABC") Among these two, which is more efficient in terms of time taken as well as number of db calls? -
Django ORM: Annotating a ForeignKey
In order to simplify a very complicated query, I am trying to annotate a User to a Submission as if the user were a ForeignKey field. Here is the (much simplified) core of my attempt so far: import django.db.models as djdm myfk = djdm.ForeignKey(User, on_delete=djdm.DO_NOTHING) qs = Submission.objects.annotate(_user= djdm.Subquery(rcm.RQCuser.objects.values('pk')[:1], output_field=myfk) ) print(qs[0]._user.username) I get AttributeError: 'int' object has no attribute 'username' What do I need to do to convince Django that _user should end up as a relation to a User model instance? Furthermore, my actual complex query shows a different symptom (at what I had hoped would be the equivalent spot): AttributeError: 'ForeignKey' object has no attribute 'model' Can anybody contribute a guess what the origin of this may be? -
How to use csrf if using django just as REST API without frontend
I am currently using Django only as an API that contains no templates or HTML (frontend is on other server), it is just used to be requested. How do I enable csrf protection for POST requests if I don't have access to the csrf? -
How can I monitor a website with javascript
I would like to get an idea on how to create a monitoring web app with javascript that when you are having an exam or a test to take online it will check to know if you left the site to find answers -
Django 2 function calls - 2 different results
When I call the first function, there are no errors. When I call the second function, I get the error: Field 'id' expected a number but got <Product: Hoodie adidas (Clothes)>. How is this possible? First function: Basket.objects.filter(user=current_user, product=_get_product_by_id(product_id=product_id)) Second function: def _is_user_have_product_in_basket_by_id(user: str, product_id: any) -> bool: return len(Basket.objects.filter(user=user, product_id=_get_product_by_id(product_id=product_id))) == 0 Additional function def _get_product_by_id(product_id: int) -> int: return Product.objects.get(id=product_id) -
django-rest-framework: How to prepopulate django-rest-framework serializer fields before validation?
Hello I am new to django and I am using django-rest-framework for making res APIs. Is there any hook or any Signals like django for executing a callback on pre validation state? I need to prepopulate some data outside the admin area before the validation and then I am doing this stuff: if serializer.is_valid(): serializer.save() Here is my serializer class: class HeroSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hero fields = ['name', 'alias', 'gender'] Do I need another serializer for write operations? or should I create a custom Signal for it? Please suggest me an efficient way to do this. -
Can we get to know what was the time of the last screenshot or photo taken by the user
I am working on a website in Django. I want to get to know the last image the user has taken and is saved in its phone that means that photo shouldn't be sent by anyone, it should be taken by the user's device especially screenshot. I have searched a lot of ways but not able to find the real. Is there any method that will work on website as, I am not sure, but I fear that the web-browser don't allow this. Please help me out -
Best way to store databases details in Django
I would like to store the details of multiple databases that the django rest api will eventually connect to and retrieve the data. Initially I created a model that looked like this: class DB_Connector(models.Model): server = models.CharField(max_length=250) database = models.CharField(max_length=100) db_username = models.CharField(max_length=100) db_password = models.CharField(max_length=256) table = models.CharField(max_length=250 , null=True) port = models.IntegerField(default=5432) def __str__(self) -> str: return self.server The problem is the password field, I cannot hash it since otherwise I can't get the raw db_password to connect to the database. Should I use an encryption and decryption algortihm to secure the db_password field? -
Heroku deployment error Migrations error using github
I have this Django application, everything works fine. After I have deployed I get receiving this error No Session Django Table I understand its a migration error I have used the GitHub deployment method, And even include the migration and the Procfile. What am I missing? -
How do `default` and `default_if_none` behave if variable is missing or undefined?
In Django, how do default and default_if_none behave if the variable is missing from the request context? For example, take this view: def example_view(request): return render(request, 'example.html', {'foo': 'bar'}) And take this corresponding Django template: {{ missing_variable|default:"default value" }} <br> {{ missing_variable|default_if_none:"default_if_none value" }} What will be rendered here? -
Django form validation not called - instead returns message: Select a valid choice. That choice is not one of the available choices
I am using Django 3.2 I have the following classes in my project: class Foo(models.Model) keycode = models.Char(max_length=16,unique=True, db_index=True) # other fields .. class FooBar(models.Model) linked_foo = models.ForeignKey(Foo, on_delete=models.SET_NULL, default=None, blank=True) # other fields .. class FooBarForm(forms.ModelForm): def clean_linked_foo(self): cleaned_data = self.clean() keycode = cleaned_data.get('linked_foo') foo = None if keycode: try: foo = Foo.objects.get(keycode=keycode) except ObjectDoesNotExist: raise ValidationError('Please enter a valid Foo keycode (or leave this field blank)' return foo class Meta: model = Foo fields = ['linked_foo', # ..............] widgets = { 'linked_foo': forms.TextInput(attrs={'class': 'form-control input'}), # other fields ... } In essence, when FooBar is being created, the creator is presented with a field that they can enter a code into (or leave blank). In the form validation, the code is checked to see if it exists in the Db. If the foo object exists, then it is saved as a FK in the Foobar object. However my validation is not being called (set breakpoints are not triggered), and instead, I get this strange error message. What is going on, and how do I fix this issue?