Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ManyToManyField, filtering by matching all related values
I have in my model to classes: User: name Pair: users=ManyToManyField(User) I want to make working and in the next step optimal query which allows me to get all pairs of two users. This code of course not works, but shows my problem. The order of user_1 and user_2 is not important. def get_pair_by_users(user_name_1, user_name_2): return Pairs.objects.filter(users__name=user_name_1 & users__name=user_name_2) -
add key and value in json dict
how add key and value from user in file? def register(): while True: username=input("enter your username: ") if not username.strip(): print("\") continue if username in user_data: print("this user exist") else: break while True: password=input("enter your password: ") if not password.strip(): print("\") continue renter_pass=input("enter again") if password !=renter_pass: print("pass and \pass should be equal!") else: break while True: age=input("enter your age: ") if not age.strip(): print("\") continue if not age.(): print("input must be number ") continue else: break the age not dump with key and my dict "y": ["1470", "12"]} dosnt have age key -
Trying to make query with filtering foreign key
I have a huge list of sports teams that has their respective league as a foreign key, (NBA, NCAA, MLB, NFL). In my Django form, I am trying to filter out only the teams with the MLB key but when I do the query with Objects.filter(league='MLB') I get an error that tells me it wants the id number. But when I do Objects.filter(league=3), I don't get an error but the queryset is empty. Objects.all() returns all the teams from all the leagues. If I run a for loop I can print out all the team's leagues, I just can't seem to search by them. I'm not sure what I am doing wrong. I appreciate your help. Models class TeamName(models.Model): name = models.CharField(max_length=100, null=False, blank=False) abbreviation = models.CharField(max_length=10, null=False, blank=False) league = models.ForeignKey( 'League', null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return self.name class League(models.Model): leagues = ( ('MLB', ('MLB')), ('NBA', ('NBA')), ('NCAAB', ('NCAAB')), ('NFL', ('NFL')), ) name = models.CharField( max_length=10, choices=leagues, null=False, blank=False) def __str__(self): return self.name Forms def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) seasons = Season.objects.filter(name='MLB2021') names = [(season.id, season.name) for season in seasons] self.fields['season'].choices = names team_names = TeamName.objects.filter(league='MLB') teams = [(team.id, team.name)for team in team_names] self.fields['name'].choices = teams -
Django: Filtering two objects from the same "column"
Im quite new to django and hmtl and have managed to create a chart where the user can filter which first_name they want . I want to extend this so the user now can enter two first names in seperate forms and have both be displayed in the same chart. I´m using the django_filters package. models.py class Name(models.Model): first_name = models.CharField() value = models.IntegerField() views.py def Page(request): object = Name.objects.all() filter1 = myFilter(requests.Get, queryset = object) filter2 = myFilter(requests.Get, queryset = object) person_1 = filter1.qs person_2 = filter2.qs context = { person_1: person1, person_2: person2, filter1: filter1, filter2: filter2 } return render(request, "chart.html", context) chart.html <form method = "get" style ="margin-left: 50px"> {{ filter1.form }} {{ filter2.form }} <button type = "submit"> Search</button> </form> *ACESSS OBJECTs ETC* *CHART.JS STUFF* I dont get any errors and both forms works well, but not simultaneously. My guess is that I can't filter this way? -
Why is React not working in django project?
I have a django project, and I'm trying to add react to one page. I have a page called reacttest.html, and a reacttest.js file. I have installed React with npm. Here are the two files content: reacttest.js : import React from "react"; React.render( <h1>Bonjour, monde !</h1>, document.getElementById('root') ); reacttest.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React test</title> </head> <body> <div id="root"></div> <script type="text/jsx" src={% static 'app/js/reacttest.js' %}></script> </body> </html> Thanks! -
how can i make registration by email using Django registration
I'm workig on a small project using Django, i have installed django-registration to create the registration feature, but as i can see the registration is by the username and not by the email, Link of the package : https://django-registration-redux.readthedocs.io/ how can I fix that, This is my forms.py from django_registration.forms import RegistrationForm from .models import CustomUser class CustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = CustomUser -
How Do I Count A Favorite Category - Django Query
I created a website for sharing anything about books in pdf. But i want to know what is the favorite category by how much 1 category used by many books. Books - Category has been arranged with ManyToManyField so this is the models.py class Category(models.Model): name = models.CharField(max_length=255, default='') def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=255) link = models.SlugField(max_length=255, unique=True, default='') # ng usah book = models.FileField(upload_to='book/pdf/') # ng usah cover = models.ImageField(upload_to='book/cover/') author = models.CharField(max_length=255) availability = models.IntegerField(default=0) description = CKEditor5Field(null=True, blank=True, config_name='special') uploader = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploader') pending = models.BooleanField(default=True) # ng usah upload_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='likes', blank=True) category = models.ManyToManyField(Category, blank=True) def ttl_like(self): return self.likes.count() def __str__(self): return self.title def delete(self, *args, **kwargs): self.book.delete() self.cover.delete() super().delete(*args, **kwargs) def get_absolute_url(self): links = self.link links = str(links) return reverse('read:detail', args=[links]) i want to count the favorite on the views.py, but i want to know how much the categories used on 1 book and ordering by the most used category choices .order_by('-fav_category'). here this the views.py in GCBV class AllBookList(ListView): model = Book template_name = 'read/list.html' paginate_by = 6 ordering = ['-pk'] def get_queryset(self): qq = self.request.GET.get('q') ss = self.request.GET.get('s') if qq is not None: … -
Difference between querysets and objects in Django
What is the difference between a query set and objects.all() in Django? After reading the documentation I am still a bit in doubt as to particularly when each of those should be used. Thank you! -
Django CustomAuthForm and default LoginForm not raising validation error
I extended the Django AuthenticationForm and created two backends to allow users to sign in with either (or both) email and username. This works perfectly if I try to sign in to the Django admin using any of the credentials. Although I can sign in on the frontend using any of these credentials, validation errors fail to show anytime the wrong credentials are used. forms.py class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(widget=TextInput( attrs={'placeholder': 'Enter your email address'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder': 'Password'})) remember_me = forms.BooleanField(required=False, label="Keep me signed in", initial=False) views.py class CustomLoginView(LoginView): form_class = CustomAuthenticationForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'login.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated: if request.user.is_personal: return HttpResponseRedirect(reverse(...)) elif request.user.is_business: return HttpResponseRedirect(reverse(...)) else: return HttpResponseRedirect(reverse(...)) return super(LoginView, self).get(request, *args, **kwargs) def form_valid(self, form): remember_me = form.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): if self.request.user.is_personal: return reverse(...) elif self.request.user.is_business: return reverse(...) else: return reverse(...) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ self.redirect_field_name: self.get_redirect_url(), 'site': current_site, 'site_name': current_site.name, 'title': _('Log in to your account'), **(self.extra_context or {}) }) return context backends.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model User = get_user_model() class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): … -
Link the current user to a field in ModelForm django
Overview I'm working on a commerce site using django. The logged in user has the ability to create a listing. I'm using django model to create a model and ModelForm for forms. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500) starting_bid = models.IntegerField() image_url = models.URLField(blank=True) category = models.CharField(max_length=15, blank=True) listed_by = models.ForeignKey(User, on_delete=models.CASCADE) The last field in Listing(models.Model) is used to store the user who listed the listing which should be based on the current logged in user. forms.py from django import forms from .models import Listing class ListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "starting_bid", "image_url", "category"] forms.py without the listed_by field is working as intended. views.py def create(request): """Renders a Form to Create a Listing""" if request.method == "POST": # Create a form instance and populate it with data from the request: form = ListingForm(request.POST) if form.is_valid(): # Save a new Listing object from the form's data. listing = form.save() # Redirects the users to the main page return HttpResponseRedirect(reverse("index")) # If the form is not valid, render the template with errors return render(request, 'auctions/create_listing.html', {"form": form}) # Create a form instance … -
Django media image full path for PIL
i am trying to get the full path of an uploaded django image (to the media folder) to use it with PIL but it returns FileNotFoundError code: from PIL import Images img_dir = Image.objects.all().first() img = img_dir.image1.url im = Image.open(img) how can i solve this error? -
Pagination with function based view with dictionary
I'm trying to paginate the pages with the help of Paginator. Have written this so far but I don't understand what would I pass in the context. Simply doing this doesn't work, I think my knowledge with Paginator is limited. customerproducts = customerproductsjsondata.json() customerproducts_list = customerproducts['data'] paginated_products = Paginator(customerproducts_list, 20) -
Return all model results, but filter out the ManyToManyFields
I'm trying to filter out the results from a model so all fields return, but I can filter just one ManyToManyField in the model. I'd only like it to filter out on the page, and not in the Admin. I've found some great information about ManyToMany filtering but, for some reason, nothing that helps in this particular case. So I guess I'm either doing it very wrong, or I'm missing an important search term. I've tried filtering in models, in views, and in the template. Here's a minimal example to help explain: # models.py class Foo(models.Model): name = models.CharField(unique=True, max_length=255) bars = models.ManyToManyField(Bar) class Bar(models.Model): thing = models.CharField(max_length=12) is_public = models.BooleanField(default=False) # views.py class FooDetail(DetailView): def get_queryset(self): # Would I filter in here? return super(FooDetail, self).get_queryset() I would like the Foo model to return all foos, but for each foo only includes bars that are true for is_public Where do I filter out the Bar results for the Foo model? I found this question which is basically what I'm asking, but the answer is specific to that question and shows it filtered in the Serializer. So I don't understand how/where to apply that answer here where I'm not doing any … -
Access denied to mysql database when lauched from Django's dbshell
I have just installed mysql in my mac system, and I have configured my Django settings.py for the mysql data base DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '/usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop', #changed in production 'USER': data['mysql']['username'], 'PASSWORD': data['mysql']['password'], 'HOST': '', 'PORT': '', } } When I launched the below command calling dbshell from manage.py, I received an error stating that the data base access what denied python manage.py dbshell mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1044 (42000): Access denied for user 'jianwu'@'localhost' to database '/usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop' CommandError: "mysql --user=jianwu --password=xxxxxx /usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop" returned non-zero exit status 1. Any ideas of what I have missed? -
What configurations to be made to enable a web application handle thousands of requests per second - Django/Gunicorn/Postgres
I want to deploy a web application with Django backend and Postgresql DB running on Nginx and Gunicorn. What are the configurations to be made to enable this application to handle around 1000 requests per second without any delay. Generally, each request takes less than a second to process. So, I also want these requests/calls to hit on API within a second to process in less than 2 seconds without consuming more CPU. This is a doubt which arose while learning. So, I don't have any code snippets or configurations to share. Thanks much in advance. -
saving default fields in a ManyToMany relationship
User class User(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) job = models.ManyToManyField(Job, blank=True, related_name="users", default = JobDefault) where JobDefault() returns a string. def JobDefault(): return "Artist" class Job(models.Model): job = models.CharField(max_length=60, null=True, default = JobDefault()) def __str__(self): return self.job So there's a m2m field involving User and Job but I want to set a default "Artist"(which is what JobDefault() returns) as the job if a user does not specify a job. Django seems to have a bug which prevents the setting of initial values of the model every time an instance is created. I tried implementing this by overriding the save method of User: def save(self, *args, **kwargs): if not self.job.all(): self.job.add(JobDefault()) super(User, self).save(*args, **kwargs) but returns an error when I try saving a User object: raise ValueError('"%r" needs to have a value for field "%s" before ' ValueError: "<User: hello@gmail.com>" needs to have a value for field "id" before this many-to-many relationship can be used I also tried using Postsave: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') def SetDefaultName(self, **kwargs): User = kwargs['instance'] if not User.job.all(): User.job.add(JobDefault) User.save() but returns this error when I try to run any manage.py command: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') NameError: name 'User' is not defined Is there … -
Django subdomains using django_hosts
I'm getting a NoReverseMatch at / 'ccc' is not a registered namespace when using django_hosts. I've followed tutorials from How to Use django-hosts Library, How to Create Infinite Domains Using Django Hosts, and I'm getting the NoReverseMatch error -
Password is never valid - Django
So I'm trying to build custom login functionality for an API, I'm trying to achieve this using tokens but I'm running into some problems. It always says password not valid so the password valid condition never turns to true for some reason even if the password is valid, Here is my code: class UserTokenHandler(APIView): def get(self, request, format=None): username = request.GET['username'] password = request.GET['password'] user = User.objects.filter(username=username) if user.exists(): if User.objects.get(username=username).password == password: chosen_token = '' for i in range(20): lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] random_choice = random.randint(1,3) if random_choice == 1: chosen_token += lower_case[random.randint(0, len(list) -1)] elif random_choice == 2: chosen_token += numbers[random.randint(0, len(list) -1)] elif random_choice == 3: chosen_token += upper_case[random.randint(0, len(list) -1)] token = UserLogin.objects.create(token=chosen_token, user=user) token.save() print(password) print(username) return Response({'Token': chosen_token}) else: print(password) print(username) return Response({'Error':'Invalid Password'}) -
Get the Request Body in DRF API
I am passing a value in my API POST request like this { "reason": "string" } And my view is like this, class UpdateReason(GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = serializers.ReasonSerializer queryset = Food.objects.all() def post(self, request, *args, **kwargs): self.get_serializer().instance = service.update(self.get_object()) return Response({"success": True}) serializer.py class ReasonSerializer(serializers.ModelSerializer): class Meta: model = Food fields = ("id", "reason") read_only_fields = ("id",) In the post, I have to get the value of the reason and pass it to the service. How can I execute this? -
How to ask for audio input directly in website without recording audio , then downloading it and then uploading it in django
I am trying to create a website , which converts speech to text (Python). I need to use that program in a website(html,css,js) but I am not able to figure out how to ask for audio input directly from microphone instead of first recording it , then uploading it -
Django file not found error when the file is there
I am working on a social media app. i have a signal that resizes the post image after upload. signals.py @receiver(post_save, sender=Post) def create_uuid(sender, instance, created, **kwargs): if created: img_dir = instance.media.url img_dir_list = img_dir.split("/") img_ext = img_dir_list[-1].split(".")[0] im = Image.open(img_dir) new_width = 0 for x in range(0, 3): new_width += 200 new_height = int(new_width/image.width * image.height) image = im.resize((new_width, new_height)) image.save(f"{settings.MEDIA_URL}posts/{img}{new_width}x{new_height}.{img_ext}") instance.save() models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) media = models.ImageField(null=False, blank=False, upload_to="posts")) caption = models.CharField(max_length=100, default="", null=True, blank=True) date = models.DateTimeField(default=timezone.now, null=True, blank=True) when i add a post and run the signal. it gives me FileNotFoundError but i can see the file in my media folder. how can i fix this? -
Django for loop in template
I have two datasets: ButikPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=True, IsActive=1, URL=shop_page_slug) SubPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=False, URL=shop_page_slug) In my Template I try to filter these two lists that if one ButikPages Query has SubPages it should a drop down menu if not a link menu. <ul class="navbar-nav"> {% for page in ButikPages %} {% for parentpage in SubPages %} {% if page.IsActive == 1 and parentpage.Parent_id != page.ID %} <li class="nav-item"><a class="nav-link" href="/{{ page.Slug }}/">{{ page.PageTitle }}</a></li> {% else %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">{{ page.PageTitle }}</a> {% if parentpage.Parent_id == page.ID and parentpage.IsActive == 1 %} <ul class="dropdown-menu"> <li><a class="dropdown-item" href="/{{ parentpage.Slug }}/">{{ parentpage.PageTitle }}</a></li> </ul> </li> {% endif %} {% endif %} {% endfor %} {% endfor %} </ul> That works if a Menu just has one entry, but if I have two SubPages it appears two time, which is what I understand because the two for loops. But how can I access the SubPages without the second loop? regards. -
Django bootstrap dropdown button in navbar not working
I've tried other questions with similar topic with many different links to bootstrap but it was not working for me, none of them. Any clues why my dropdown button does not roll down when clicked (also does not when hovered either as this was the case for some people). Thanks for any help. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> </head> <body> <header> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> <li class="nav-item "><a class="nav-link" href="{% url 'milk_app:about' %}">About</a></li> <!-- If the user is logged in, either as HOST or TENANT he gets these buttons available --> {% if user.is_authenticated %} … -
Can not save form with CreateView (Django, Python)
I am trying to save form to database but it doesn't work. These are my codes. Views.py class HotelAdCreate(AuthorsAccessMixin,CreateView): model = HotelBookingAd form_class = HotelBookingAdForm template_name = "account/article-create-update.html" def form_valid(self,form): form.save() return super(HotelAdCreate).form_valid(form) Forms.py class HotelBookingAdForm(forms.ModelForm): class Meta: model = HotelBookingAd fields = '__all__' def clean_sales_price(self): sales_price = self.cleaned_data["sales_price"] purchase_price = self.cleaned_data["purchase_price"] if sales_price > purchase_price: raise forms.ValidationError("error.") print("error") return sales_price I've tried different options, but I don't have enough skills to handle this problem. Can anyone help me? -
Is it possible to work with Django on Windows and Reactjs on WSL on the same computer at the same time?
I have set up an environment for Django on my windows machine and I have React and Nodejs on Windows-subsytem-for-Linux. I want to build a pet project using Django for backend and React for front end. Is it possible on develop with these settings or should I install both of them on the same environment before starting?