Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building Complex Dynamic Queries With Django
Here is a sample model I have: class Commission(models.Model): status = models.CharField(null=True, blank=True) customer_name = models.CharField(null=True, blank=True) order_dat = models.CharField(null=True, blank=True) For status, I can have up to 10 different status types, such as: requested, confirmed, paid... If I want to build a way to dynamically filter all orders with a specific status with a specific customer, I would do the following: sample_kwargs['status'] = 'active' sample_kwargs['custom_name'] = 'John Doe' Then get my results with the following: all_commmissions = Commission.objects.filter(**sample_kwargs) This all works well, but what I am now trying to do is is get all the customer's orders that are equal to multiple statuses. For example, I want all of John Doe's orders that are equal to both confirmed, and paid. Normally I'd used the Q filter all_commmissions = Commission.objects.filter( Q(status='confirmed') | Q(status='paid')) But this only allows me to hard code things in. How can I build a complex dynamic query (such as my sample_kwargs example) that uses OR? Or what is the best way I can achieve this? I could not find anything in the documentation. Thank you for your help. -
Django Inline download not showing the filename in the browser correctly
I'm running into an oddity that I can't explain, other than it's an inline, instead an attachment. def respond_as_inline(request, file_path, original_filename, ranged=False): # https://stackoverflow.com/questions/36392510/django-download-a-file # https://stackoverflow.com/questions/27712778/video-plays-in-other-browsers-but-not-safari # https://stackoverflow.com/questions/720419/how-can-i-find-out-whether-a-server-supports-the-range-header filename = os.path.join(file_path, original_filename) if os.path.exists(filename): mtype, encoding = mimetypes.guess_type(original_filename) if mtype is None: mtype = 'application/octet-stream' with open(filename, 'rb') as fh: if ranged: response = RangedFileResponse(request, file=open(filename, 'rb'), as_attachment=False, filename=original_filename) response["Content-Type"] = mtype else: response = HttpResponse(fh.read(), content_type=mtype) response['Content-Disposition'] = 'inline; filename=%s'% original_filename return response else: print("File not found") raise Http404 Now this is working fine, except for the fact, that if I use the inline attachment, the filename that is shown from the browser is the url name (a UUID), and not the filename (eg original_filename). If I change this to be an attachment, when it is downloaded, the correct filename is detected/used. Anyone have a good answer/solution? And no, by design this is inline, so that the PDF, graphic, etc, can be viewed in the browser. If I can it to be an attachment, the default is to save to disk. That's not helpful on an tablet. -
How to send Notification to React Native (mobile) app from Django (back-end)
I am developing a mobile application using React Native. and using Django as a back-end Language. I want to know how I can send notifications from Django to React native mobile application. Thanks in advance -
get_object_or_404 does not return object that I've verified to exist in database
I've been trying to figure out why get_object_or_404 can't find an object that exists but I can't figure it out. So the problem is occuring when I try to call this function like this. JS Ajax to call function: var url; url = {{ OrderItem.change_item_quantity}}; $.ajax( { type: "GET", url: url, data: { newquantity: realquantity }, success: function(data) { console.log("success") spinner{{ forloop.counter0 }}.addClass(pauseClass); $("#totalprice{{ forloop.counter0 }}").css("display", "block") }, error: function(errordata) { console.log(errordata) } }) changeTimer = false; },300); This calls a function in my OrderItem model (models.py): class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(VarientItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity}x {self.item.item.title} of varient {self.item.varient} for {self.user.email}" def get_item_total(self): return (self.item.final_price * self.quantity) def change_item_quantity(self): return reverse("core:change_item_quantity", kwargs={ 'slug': self.item.item.slug, 'ordervarient': self.item.varient, 'orderfinalprice': self.item.final_price }) class VarientItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) varient = models.JSONField(blank=True, null=True) final_price = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return self.item.title My url for change_item_quantity: urlpatterns = [ path('change_item_quantity/<slug>/<ordervarient>/<orderfinalprice>', views.change_item_quantity, name='change_item_quantity') ] Finally, my function actually lives in views.py: def change_item_quantity(request, slug, ordervarient, orderfinalprice): if request.method == 'GET': new_quantity_str = request.GET.get('newquantity', None) new_quantity = ast.literal_eval(new_quantity_str) try: new_quantity_int = int(new_quantity) if int(new_quantity) <= 0: raise ValueError("Numbers can't be negative") except: response = HttpResponse('Quantity … -
Can we create django forms without Crispy Forms Template?
I am a front-end developer, hardly 2 weeks old with Django with basic structured knowledge of Python. Since I am always keen to develop my own designs and layouts, I am not a great fan of using Bootstrap. I have seen and followed multiples tutorials and everyone is focussing at including Bootstrap while creating log-in forms crispy forms. I would like to know if there is any possible way to style forms by using customised CSS and not including Bootstrap and how to do that. Please help. Looking forward. -
how can i have a centralized login in multi tenancy
I'm working on a small project using Django / Rest Framework with a multi-tenancy package, https://django-tenants.readthedocs.io/en/latest/ and as you know to be logged in i must set the subdomain of each user like that, tenant1.mydomain.com and the second user must access by tenant2.mydomain.com. how can I have a centralized login? -
i am creating a to do list model (TodoModel) in django, and I want to display data of the logged in user only, but I am getting the data of all users
i want to display the data of logged in user only, but im getting data of all users .i.e i want to display task, deadline and note of logged in user only in my case. admin.py: from django.contrib import admin from .models import TodoModel admin.site.register(TodoModel) forms.py: from django import forms from .models import TodoModel class TodoForm(forms.ModelForm): class Meta: model = TodoModel widgets = { 'task': forms.Textarea(attrs={'rows':4, 'cols':21}), 'Note': forms.Textarea(attrs={'rows':4, 'cols':21}), } fields = '__all__' models.py: from django.db import models class TodoModel(models.Model): task = models.TextField(primary_key=True) deadline = models.CharField(max_length=50) Note = models.TextField(max_length=50) def __str__(self): return self.task views.py: def showtask(request): data = TodoModel.objects.all() return render(request, "showtask.html",{"data":data}) Here i'm trying to get data(task,deadline and note) for only the logged in user, but instead im getting the data of all the users. It will be a great help if someone help me with this, i'm just a django begineer. -
Django form data validation
I'm new to Django and instead of using Django forms ,I'm using bootrap forms with user model that I have created I have to check the login details before giving access to the user dashboard . And also how to set cookies , sessions but I'm not using the default admin or user model for anything . I'm a website for a client plz give me suggestions based on this not as a project . -
django: form with additional fields of many-to-many relationship
I have a many-to-many relationship with a custom pivot table (through argument) to have additional fields. In my form I want to display the many-to-many relationship using checkboxes. And for each ckechbox I want to be able to set the quantity parameter. The model: class Match(models.Model): # ...Some additional fields... bonus = models.ManyToManyField(Bonus_type, blank=True, through='Match_bonus') class Match_bonus(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE) bonus = models.ForeignKey(Bonus_type, on_delete=models.CASCADE) quantity = models.IntegerField(blank=True, default=1, validators=[MinValueValidator(0)]) The form: class MatchForm(forms.ModelForm): bonus_quantity = forms.IntegerField(validators=[MinValueValidator(0)]) # this is actually wrong because I need one of this field for each option of the ModelMultipleChoiceField bonus = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, tournament_type, **kwargs): super(MatchForm, self).__init__(*args, **kwargs) self.fields["bonus"].queryset = Bonus_type.objects.filter(tournament_type=tournament_type) class Meta: model = Match exclude = () In my view, I display the form in a formset using inlineformset_factory: matchFormset = inlineformset_factory(Menu, Match, MatchForm, exclude=['weight_player_1,weight_player_2'], extra=extra_form) formset = matchFormset(instance=menu, form_kwargs={'tournament_type': tournament.tournament_type}) Any hint on how to perform that? -
Create Multiple Instances at Once Django Rest Framework
There seems to be a lot of documentation out there on this but none of it seems to work for me. I am trying to build an API View that creates one or many objects at the same time. Something like passing in the following: [ { "response": "I have no favourites", "user": 1, "update": "64c5fe6f-cb65-493d-8ef4-126db0195c33", "question": "297b46b4-714b-4434-b4e6-668ff926b38e" }, { "response": "Good", "user": 1, "update": "64c5fe6f-cb65-493d-8ef4-126db0195c33", "question": "13916052-690e-4638-bb7c-908c38dcd75e" } ] My current Viewset class FeedbackViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Feedback.objects.all() serializer_class = FeedbackSerializer and Serializer: class ContributionSerializer(serializers.ModelSerializer): class Meta: model = Contribution fields = '__all__' I have tried setting FeedbackSerializer(many=True) but this then tells me its not callable. Further, I have tried a ListCreateAPIView but this tells me it expects a dictionary but not a list. -
How do I filter my result by a month and a year that I input?
I'm trying to filter an order to get the most sold pizza in a given month and year. This is the code so far but I don't know how to configure it so it would search depending on the month and year I type and not a fixed one. For example, if I type my query as month 03 and year 2021 then I should get my object. How do I manage to do that? Fecha is the date that's defined in the models as fecha = models.DateField(auto_now_add=True) obj = Order.objects.filter(fecha__month=month, fecha__year=year).annotate(Max('pizzas__cant')).order_by('-pizzas__cant__max').first() This is the model: class Pedido(models.Model): fecha = models.DateField(auto_now_add=True) email = models.EmailField(max_length=200, null=True) telefono = models.IntegerField(null=True) pizzas = models.ManyToManyField('Pizzas', related_name='pedidos', blank=True) cantidad = models.IntegerField(default=0) def __str__(self): return self.email -
error while running" python manage.py runserver "
hello every one I start learning since python several months but I met with an error. In tutorial it is showing like this.. tutorial But here in my case it is giving some error like this my error -
React API Sends Blank Value (Some State Issue)
I've a login form with Validate() function. I'm trying to send input values to my Django backend but i'm getting response as below. I think the issue is i'm storing my data like " input:{} " but on the App.js i've username and password values. I'm new at React and i'm gonna freak out. I need this validation function. I'm so confused. { "username": [ "This field may not be blank." ], "password": [ "This field may not be blank." ] LoginForm.js (handle_login is a function on my App.js) import React from 'react'; import PropTypes from 'prop-types'; class LoginForm extends React.Component { constructor() { super(); this.state = { input: {}, iderr: false, data: null, errors: {} }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } checkgiris = (e, data) => { e.preventDefault(); fetch('http://localhost:8000/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(respons => { if(respons.status === 200){ this.props.handle_login(e, this.state.input) } else { this.setState({iderr:true}) } }) }; handleChange(e) { let input = this.state.input; input[e.target.name] = e.target.value; this.setState({ input }); } handleSubmit(e) { e.preventDefault(); if(this.validate()){ console.log(this.state); let input = {}; input["username"] = ""; input["password"] = ""; this.setState({input:input}); this.checkgiris(e, this.state.input) } } validate(){ let input = this.state.input; let errors = {}; … -
Exception Type: DoesNotExist | Profile matching query does not exist
I am trying to get the username in the URL pattern instead of id <a class="dropdown-item" href="{% url 'UserApp:profile' username=profile.username%}">Profile</a> and so getting an error in the logout function: Profile matching query does not exist. But the profile template is rendering will all the query without any error. If I use id in the URL as well everything is working fine! Please suggest to me how can I get rid of the error. Thank you! Views.py def logout_view(request): logout(request.user) return redirect("index") @login_required def profile(request, username): title = 'Profile' context={'title': title} profile = Profile.objects.get(username=username) if profile: context.update(profile = profile) else: return HttpResponse("user is not found") return render(request, 'UserApp/profile.html', context) Urls.py from django.urls import path from UserApp import views app_name = 'UserApp' urlpatterns = [ path('<str:username>/', views.profile, name='profile'), path('signup/', views.signup, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('update/', views.update_profile, name='update'), ] I used BaseUserManager, AbstractBaseUser for user registration and customer profile models to get the username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') username = models.CharField(max_length=264, null=True, blank=True) full_name = models.CharField(max_length=264, blank=True) address_1 = models.TextField(max_length=300, blank=True) city = models.CharField(max_length=40, blank=True) zipcode = models.CharField(max_length=10, blank=True) country = models.CharField(max_length=50, blank=True) date_joined = models.DateTimeField(auto_now_add=True) pro_pic = models.ImageField(upload_to=None, blank=True) about = models.CharField(max_length=500, blank=True) def __str__(self): return … -
recieving error : MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled with DJANGO PYTHON
I'm receiving this error in the console: Refused to apply style from 'http://127.0.0.1:8000/faq/owl-carousel/owl.carousel.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. My friend told me to write mimetypes.add_type(“text/css”, “.css”, True) into settings.py but i recieved this message: File "/Users/fiennesharris/anonima_sandbox/anonima/settingsDEV.py", line 14 import mimetypes ^ IndentationError: unexpected indent I'm using Django so how can I fix this? much appreciated! -
Trying to run multi-django on apache, enabling site2.conf shoots down Site1 (error 404)
Okay so I'm trying to run 2 django/wagtail sites as subdomains under the same IP using apache and wsgi like so: www.domain.com/site1 www.domain.com/site2 site.conf looks as follows: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html/pe.blog ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /pe/static /home/maxehlenz/pe.blog/static <Directory /home/maxehlenz/pe.blog/static> Require all granted </Directory> Alias /pe/media /home/maxehlenz/pe.blog/media <Directory /home/maxehlenz/pe.blog/media> Require all granted </Directory> <Directory /home/maxehlenz/pe.blog/pe_blog> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /pe /home/maxehlenz/pe.blog/pe_blog/wsgi.py WSGIDaemonProcess django_app python-path=/home/maxehlenz/pe.blog python-home=/home/maxehlenz/pe.blog WSGIProcessGroup django_app Site 2 has a similar .conf file but with different aliases for static and media, different python home and venv and different document.root and different demon process/group/wsgi Wsgi.py file looks like this import os from django.core.wsgi import get_wsgi_application # i changed this line according to the docs and replaced it with whats below #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pe_blog.settings.dev") os.environ["DJANGO_SETTINGS_MODULE"] = "pe_blog.settings.dev" application = get_wsgi_application() When I run the sites one by one everything appears to be set-up correctly and runs fine. However if I do an a2ensite on both site1.conf and site2.conf Site 1 then becomes unreachable. (404) There is nothing regarding this in the error.log I'm completely new to apache, what am I missing here? -
How do I model a many to many relationship in Django Rest Framework?
I need to model a many to many relationship. I've read some documentation, but I don't know how to model. I'll give you an example of what I want to do. I have to entities, Album and song. They have a many to many relationship. class Song(models.Model): name = models.CharField(unique=True, max_length=255) class Album(models.Model): nombre = models.CharField(unique=True, max_length=255) songs = models.ManyToManyField(Song, blank=True) The user, in the frontend, provides me the data of an album that I must save. It provides me the name of the album and the name of the songs. How could I model it on the serializers? Nothing runs. Thank you very much -
Django ORM create nested query prevent using `having`
Assume I have a Transaction model which has following fields [token, pair_token, amount, related_transaction], I want to generate a query like this in mysql: SELECT token_id, pair_token_id, ( SELECT ABS(t3.amount / t2.amount) price FROM Transaction t2 join Transaction t3 on t2.related_transaction_id=t3.id WHERE t2.id=MAX(t1.id)) FROM Transaction t1 WHERE t1.token_id in (1, 2, 3, 5, 6) and t2.pair_token_id in (4) and t1.timestamp > CURRENT_TIMESTAMP - interval 24 hour GROUP BY token_id, pair_token_id; This query finds the last value of two related transaction which equals the price of a combination of a token and its pair_token. To get a similar results inside django I have used Subquery as below: trs = Transaction.objects.filter(token_id__in=[1, 2, 3], pair_token_id__in=[4], timestamp__gt=Now()-timedelta(hours=24)) last_price = Transaction.objects.annotate(price=Abs(F('related_transaction__amount') / F('amount'))) trs = trs.values('token_id', 'pair_token_id').annotate( price=Subquery(last_price.filter(id=Max(OuterRef('id'))).values('price'))).\ values('token_id', 'pair_token_id', 'price') But it generates a wrong query: SELECT `Transaction`.`token_id`, `Transaction`.`pair_token_id`, ( SELECT ABS((U1.`amount` / U0.`amount`)) AS `price` FROM `Transaction` U0 LEFT OUTER JOIN `Transaction` U1 ON (U0.`related_transaction_id` =U1.`id`) HAVING U0.`id` = MAX(`Transaction`.`id`)) AS `price` FROM `Transaction` WHERE (`Transaction`.`pair_token_id` IN (4) AND `Transaction`.`timestamp` > (CURRENT_TIMESTAMP - INTERVAL 86400000000 MICROSECOND) AND `Transaction`.`token_id` IN (1, 2, 3, 5, 6)) Mysql generates an error for this query and it must be, I do not know how to avoid generating … -
Django and Django rest framework serializer multiple relation tables
There are three models: class QLabel(models.Model): label = models.CharField(max_length=10) class Question(models.Model): question = models.TextField() label = models.ForeignKey(QLabel, related_name='qdetail', on_delete=models.DO_NOTHING) class Path(models.Model): question = models.ForeignKey(QLabel, related_name='ask', on_delete=models.CASCADE) next_q = models.ForeignKey(QLabel, related_name='next', on_delete=models.CASCADE) And the serializers.py like this: class PathSerializer(serializers.ModelSerializer): q = serializers.StringRelatedField(source='question', read_only=True) nq = serializers.StringRelatedField(source='next_q', read_only=True) class Meta: model = Path fields = ('q', 'nq') The results as follow: { "q": "Q1", "nq": "Q2", }, Instead of "Q1", how to obtain Q1 related question from Question models? -
Django: Upgrading sqlite3 database on MacOS, Python still showing the older version even after upgrading
I had sqlite3 version 3.23.1 installed. and the sqlite binary file path is: /anaconda3/bin/sqlite3 then I downloaded the sqlite3 zip file from https://sqlite.org/download.html (version 3.35.4). Then followed the following commands to upgrade my sqlite3 database: which sqlite3 sudo mv /anaconda3/bin/sqlite3 /anaconda3/bin/sqlite3-old sudo chmod -x /anaconda3/bin/sqlite3-old mv /downloads/sqlite3-downloaded-directory/sqlite3 /anaconda3/bin/ sudo chmod +x /anaconda3/bin/sqlite3 Then I checked the version: sqlite3 --version and it showed the upgraded version 3.35.4 But then I went into my Atom editor where I am writing my Django application and entered into the python shell using: python manage.py shell and then checked the version from here using the following commands: >> import sqlite3 >> print(sqlite3.sqlite_version) but it is still showing the older version i.e 3.23.1 Does anyone has an idea how to resolve this issue. -
how to add ACCOUNT_EMAIL_BLACKLIST iam using django allauth
how to add ACCOUNT_EMAIL_BLACKLIST iam using django allauth , i read here https://django-allauth.readthedocs.io/en/latest/configuration.html and i see this option ACCOUNT_USERNAME_BLACKLIST (=[]) that mean A list of usernames that can’t be used by user in signup . i want same thing but with email how to add something like ACCOUNT_EMAIL_BLACKLIST for email -
Cannot access superuser in Django admin page created by python manage.py createsuperuser
When I create the superuser in Django, which runs successfully, when I try to enter in the admin path in my browser http://127.0.0.1:8000/admin/login/?next=/admin/ and insert the email and the password, I get the following error: Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. Can you help me? I don't understand where is the problem. I have defined the following fields in the Account models.py file: is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) -
i have generic view by but it doesnt work
i have genericView in my django views file and this code should show Album detail but in doesnt work please help me my model: class Album(models.Model): name = models.CharField(max_length=100) artist = models.ForeignKey(Musician, on_delete=models.CASCADE) num_stars = models.IntegerField() my view file: class AlbumDetailView(DetailView, ListView): template_name = 'album_detail.html' paginate_by = 1 def get_queryset(self): return Album.objects.filter(num_stars__gte= 3) my html file: <head> <meta charset="UTF-8"> <title>{{ album.name|capfirst }}</title> </head> <body> <div> <p>Album : {{ album.name|capfirst }}</p> <p>Artist : {{ album.artist.name|capfirst }}</p> <p>Score : {{ album.num_stars }}</p> </div> </body> -
Python Django Restframework Password Validation does not work
At first I also saw this Post, but this doesn't work for me. I have a Django Rest Framework Project. If I create a user through django directly I get errors like: But if I have a normal HTTP POST Request I get a normal 200 Response: {"email": "test@test.com", "response": "successfully registered new user.", "token": "3618d0c362dd66bbb093e1234b72901f9d74a905", "username": "haha"} What is the problem? I also tried to build a custom validation for the password, but this isn't really what I want, because it is a great Django feature. -
__str__ returned non-string (type ManyRelatedManager)
I'm getting this error after adding the get_cliente to my serializer: TypeError at /pedido __str__ returned non-string (type ManyRelatedManager) What can I do to fix it? This is the serializer: class PedidoSerializer(serializers.ModelSerializer): cliente = serializers.SerializerMethodField() class Meta: model = Pedido fields = ('fecha','pizzas','telefono','email', 'cliente') def validate(self, data): email = data.get('email') telefono = data.get('telefono') if not email and not telefono: raise serializers.ValidationError("Se requiere email o telefono") return data def get_cliente(self, data): try: if Cliente.objects.filter(email=data).exists() or Cliente.objects.filter(telefono=data).exists(): selected_cliente = Cliente.objects.all() return ClienteSerializer(selected_cliente, many=True).data except Cliente.DoesNotExist: return None