Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to add ics file as attachment and in the body django
I am trying to send invitation to outlook I have my ics file and dont know how to send it in body as outlook does -
How can I re-redirect the callback to a different subdomain
Django, django-allauth, django-tenants I have multiple tenants and I want to have them all authenticated from a single central location with oauth. auth.localhost is the central location that I want to use to authenticate customer1.localhost customer2.localhost customerX.localhost these. I have auth.localhost/callback as my oauth callback url in the oauth2 app. The ouath2 app redirects the user to auth.localhost/callback?token=token # roughly and I am re-redirecting in auth.localhost/callback?token=token to customer1.localhost/callback?token=token hoping that the dynamics should remain the same, and that allauth should be able to get the relevant information from url and authenticate the user as if we are in auth.localhost. The problem is that google doesn't allow this somehow and errors with {'error': 'invalid_grant', 'error_description': 'Bad Request'} when I'm redirecting the callback with the parameters to a customer url. How can I achieve this? -
How to bundle the resources from an INSTALLED_APPS in Django with Webpack?
I have a main Django app, say myApp, which has subApp in its INSTALLED_APPS list. I use Webpack 5 to compile my main application's resources. The subApp is actually used in several applications which are in Django 2 and Django 3. However I cannot find a way to tell Webpack, from myApp, to go look into subApp to compile the resource files that are in there. How could one do that? If it helps imagination, let's pretend there is no js/css optimisation in subApp and Webpack would manage that from myApp on compilation. And if it's not possible directly in Webpack's config, would there be a way to import subApp's scripts and stylesheets in myApp's script files and stylesheets to make webpack compile them from there? Any help welcome. Thanks for your help. -
Triggering Django events from React Front End
I am developing an inventory management system using a Django Backend and React Frontend linked with the Django REST API. Currently I am able to make get and HTTP requests to the Django backend, for example my GET and POST requests are handled in the following code within customers/views.py file: def Customers_list(request): if request.method == 'GET': data = Customer.objects.all() serializer = CustomerSerializer(data, context={'request': request}, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The requests are made using axios, an example of this is shown here: getCustomers = () => { axios.get(API_URL).then(res => this.setState({ customers: res.data })); }; Where the API_URL points to "http://localhost:8000/api/customers/" My question is how would I allow more responses from the backend to my limited request types, for instance, I would like to have a button that increases the account age of all customers by 1, how could I impliment this and other similar features where buttons trigger events in the django backend? -
Error 'Product' object has no attribute '_combinator_query'
I am creating an e-commerce website in django where the homepage can be changed dynamically by changing the instances of FeaturedProduct objects. These objects have two ForeignKeys. First is to the Product class and the other is to FeaturedCategory class(this is for the type of deal, eg: daily deals, new arrivals, etc). So, I'm trying to get the Product instances in a queryset instead of the FeaturedProduct queryset. When I union two querysets, I get an error that 'Product' object has no attribute '_combinator_query'. The codes have been shown below. My models.py class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default='1') sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_DEFAULT, default='2') price = models.IntegerField(default=0) stock = models.IntegerField(default=0) desc = models.TextField() pub_date = models.DateField() avg_rating = models.IntegerField(default=0) avg_rating_float = models.FloatField(default=0.0) number_of_ratings = models.IntegerField(default=0) image1 = models.ImageField(upload_to="images", default="") image2 = models.ImageField(upload_to="images", default="") image3 = models.ImageField(upload_to="images", default="") slug = models.SlugField(blank=True, help_text=('Leave this parameter empty, it will get generated automatically.')) def save(self, *args, **kwargs): self.slug = slugify(self.product_name) super(Product, self).save(*args, **kwargs) def __str__(self): return self.product_name class FeaturedCategory(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category class Meta: verbose_name_plural = "Featured Categories" class FeaturedProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) featured_category = models.ForeignKey(FeaturedCategory, on_delete=models.CASCADE) def __str__(self): return self.product.product_name My … -
How can I do to parallelize a loop for?
I have this code : for user in users: user.name = "test" user.save() And I would like to optimize that using a parallel loop. How can I do that ? Thank you very much ! -
Calculating Foreign Key Totals in Django
I am wanting to make tables to show total scores for both user and teams. Models: class Team(Model): team_name = models.CharField(max_length=20, null=True, blank=True) class Player(Model): player_id = models.IntegerField(unique=True, null=False, blank=False) player_first_name = models.CharField(max_length=20, null=True, blank=True) player_last_name = models.CharField(max_length=20, null=True, blank=True) class Game(Model): score = models.FloatField(null=False, blank=False) game_type = models.CharField(max_length=8, choices=GAME_CHOICES) team = models.ForeignKey(Team, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) Each Game relates to a specific player and a specific team. Each player can be in multiple teams so no relation there. In my table I am wanting totals for the score by each player and the score for each team. The code I have tried for my table: class PlayerTable(tables.Table): sum_scores = tables.Column(Player.objects.annotate(total_score=models.Sum('game__score'))) class Meta: model = Player exclude = ["id"] attrs = {'class': 'table table-sm'} However, this does not seem to work. How do I resolve this so that the last column in the player table will be each players total score? -
Pycharm Django Console No module named 'django_manage_shell' on WSL
I recently started to working on WSL Ubuntu-20.04. There is no problem on running the server. But when I tried to connect the Django Console of Pycharm, I get the error below: Traceback (most recent call last): File "<input>", line 7, in <module> ModuleNotFoundError: No module named 'django_manage_shell' I checked the consoles interpreter and starting script, tried to add project path, my virtualenv path but nothing worked. My Django Console Options This is starting script: import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS]) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run(PROJECT_ROOT) I had no issues like this when I working on Ubuntu nor Windows. This issue happened with WSL. So I'm waiting for your helps and thanks a lot for your time. -
Im getting an error :expected string or bytes-like object
#my views files from django.shortcuts import render from django.http import HttpResponse from datetime import datetime from home.models import Contact #When my form is submitted with post method it goes in contact function and i am getting error 'expected string or bytes-like object' # Create your views here. def contact(request): if request.method=='POST': name=request.POST['name'] email=request.POST['email'] phone=request.POST['phone'] desc=request.POST['desc'] contact = Contact(name=name,email=email,phone=phone,desc=desc,date=datetime.today) contact.save() return render(request,'contact.html') Models file for creating table and here i didnot got an issues. from django.db import models # Create your models here. class Contact(models.Model): name=models.CharField(max_length=122) email=models.CharField(max_length=122) phone=models.CharField(max_length=12) desc=models.TextField() date=models.DateTimeField() -
Django migrate cmd details for migrating specific app models to specific Schema of Database
Hi I am having a django app, which is having model instances of Tables which are should be pointed and created in non public schemas something named ex: url or ftp, these are two different schemas exists along with public schema of database. The ask is, how Django migrate command be used to create particular app model's makemigration code snippet to specific schema instead public. -
Django with cx_oracle, calling sql function is taking lot of time
I have sql function defined in oracle database. When I call it in "Toad For Oracle" using following statement "select ccl_bal(1,2,0) from dual" it take hardly 2 seconds. But when I call it from django it takes lot of time 4-5 minuts. Here is my code. result=connection.cursor().callfunc("ccl_bal",int,[1, 2, 0]) Any help?? -
PasswordChangeDoneView dose not redirect to " change password done page"
In class base view "django" I have a problem , after post email with "PasswordResetView" the django go to login page but it must show me "PasswordChangeDoneView" views: class UserPassReset(PasswordResetView): template_name = 'accounts/password_reset_form.html' success_url = reverse_lazy('accounts:PasswordChangeDone') #success_url = 'done' email_template_name = 'accounts/password_reset_email.html' class PasswordChangeDone( PasswordChangeDoneView): template_name='accounts/password_reset_done.html' urls: path('login/', views.UserLogin.as_view() , name='UserLogin'), path('passreset/', views.UserPassReset.as_view() , name='UserPassReset'), path('passreset/done', views.PasswordChangeDone.as_view(), name='PasswordChangeDone'), HTML reset password: {% block content %} <h3>Enter Email </h3> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send"> </form> {% endblock %} -
django Project: JsTree disappears when running with docker
I have an issue with a Jstree instance in my Django project. When I run the project using ./manage.py runserver the Jstree works perfectly fine, but when I run it with docker-compose up the Tree is shown for a few seconds and then disappears. No error is thrown. I know that its a very specific issue, but maybe one of you has a clue what I missed. -
Django Crispy Forms doesnt display the first Textfield
I am using Django with Crispy Forms and Bootstrap. To render forms on my page I always use: <form method="POST"> {% csrf_token %} {{ form|crispy }} <div class="form-group"> <button class="btn btn-dark" type="submit">{% trans "Anmelden" %}</button> <small class="text-muted ml-2"> <a href="{% url 'password_reset' %}">{% trans "Password vergessen?" %}</a> </small> </div> </form> But with this code the first box Textbox doesnt get displayed properly as seen below. (German Website to Login.) The Textbox is still there though. I can click it and write. It is just that there is a border missing. Any idea what I did worng?