Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
foreach queryselector in javascript
I hope you are doing well, I am working with django, problem is I have a list of items that contains a menuToggle my script code is like this <script> function menuToggle1(){ document.querySelectorAll('.menupost').forEach(function(element) { element.classList.toggle('active'); }); }; </script> so when I click on one of them , I see all the menu of all items. so I don't want to see all menutoggle when I click on just one of them.I think you understand my question, I hope you guys can help me. -
On click run query function script Django
In my Django project, on my HTML page, I have a script which runs Query depending on the other values ($("#id_report").val() values). Function runs 'on click'. Problem is, when I click on '#id_person' dropdown menu to select an option which I get from query, I run query again and my selection gets reset. <script> $("#id_person").click(function () { var value = $("#id_report").val(); var url = $("#PostForm").attr("data-person-url"); $.ajax({ url: url, data: { 'value': value, }, success: function (data) { $("#id_person").html(data); console.log(data); } }); }); </script> How can I run this only when I click on dropdown, not when I select (then it runs again because it's a click) -
I want to order my list by most liked content, for e.g. most liked thing shows on top and most disliked at bottom,, help me please
I want to order my list by most liked content, for e.g. most liked thing shows on top and most disliked at bottom,, help me please i'm using django 3 and in my DETAIL view i want to oder the queryset by likecount field. The main goal is to odering the post with mostlikes . Like, i want to show the most liked content on top. It's like todays top 10 content(mostliked). i have tried many ways but can't figure it out. I hope you guys can help me. ==MODEL== this is a model page class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateField(auto_now_add=True) class Content(models.Model): name = models.CharField(max_length=255) body = models.TextField() post = models.ForeignKey(Post, related_name="contents", on_delete=models.CASCADE) liked =models.ManyToManyField(User, default=None, blank=True, related_name='liked') ==VIEWS== this is a view page class Home(ListView): model = Post template_name = 'home.html' class Detail(DetailView): model = Post template_name = 'detailview.html' ordering = Content.objects.annotate(like_count=Count('liked')).order_by('-like_count') ==HOME.HTML== {% for item in object_list %} <br> <a href="{% url 'detail' item.pk %}"> {{item.title}} </a> <br> {{item.body}} <hr> {% endfor %} == I WANT TO SHOW 'ORDER BY - MOST LIKED' CONTENT ON THIS DETAIL PAGE ==DETAILVIEW.HTML== {% if not post.contents.all %} no contents yet {% … -
how to generate a custom id for specific type of users when the user signup in django?
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] customer = models.BooleanField(default=False) vendor = models.BooleanField(default=False) id = models.AutoField(primary_key=True, editable=False) userid= models.CharField(max_length=100, unique=True) objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.vendor == True and self.is_superuser == False: if not self.userid: self.userid = "VEN" + str(self.id + (10 ** 5)) # generating the uid and allocating the value self.userid.save() else: pass else: pass forms.py class CustomUserCreationForm(UserCreationForm): """ A Custom form for creating new users. """ class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] def save(self, commit=True): user = super().save(commit=False) user.customer = True if commit: user.save() return user """ For Vendor users forms""" class VendorCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] def save(self, commit=True): user = super().save(commit=False) user.vendor = True if commit: user.save() return user views.py #Vendor Signup def VendorSignup(request): vendorform = VendorCreationForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) if vendorform.is_valid(): new_user = vendorform.save() new_user.is_active = False new_user.save() return redirect('login') else: vendorform = VendorCreationForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform}) I want to generate a customID (that starts with VEND0001)for the vendor users only when (they're signup with vendorform) and shouldn't generated … -
Django AdminEmailHandler on daphne logs
I can use Django's AdminEmailHandler just fine for my API Errors. But I can not get it to work in my daphne. All I can do so far is showing my error logs in my console. I tried numerous attempts like: 'loggers': { 'daphne': { 'handlers': ['console', 'mail_admins'], }, } It did not work though. Basically, I want to get notified if my websockets and the process within produced errors -
How to store a list of keys of another model in a model in django?
Imagine that we have 2 tariffs and two entity classes: Person and Items. The first tariff contains several people and several objects, and people and objects are not related to each other. The second tariff also stores people and items, etc. How should I store this model? ManyToManyField creates its own object for each pair (Person, Item), isn't that optimal? I don't understand, is it really more efficient to store all kinds of pairs between two fields than to store two lists of keys? (I want to keep a list of Person keys and a list of Item keys.) How to store a list of keys of another model in a model in -
JavaScript function is not defined in Django
I have a small Django project. I have a JS script in the HTML file for one of my apps: <script type="text/javascript"> function intervalSelector() { let intervalField = document.getElementById("intervalField"); let hourField = document.getElementById("hourField"); let minuteField = document.getElementById("minuteField"); intervalField.addEventListener("change", function () { if (intervalField.value === "Hourly") { hourField.disabled = true; minuteField.disabled = false; } else { hourField.disabled = false; minuteField.disabled = false; } }); } </script> This function is called by a button element further down in the HTML document: <button style="background-color: orange; color: white; float:left; margin-right:5px;" class="btn" type="button" onclick="intervalSelector()" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample"> Schedule </button> The function gets three elements by their Id in the HTML document: <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="intervalField"> <option selected>Interval</option> <option value="1">Daily</option> <option value="2">Hourly</option> </select> <input name="hour" class="form-control" type="number" min="0" max="23" value="23" id="hourField"> <input name="minute" class="form-control" type="number" min="0" max="59" value="57" id="minuteField"> When I run my webapp, and click the button that calls the function, it says that the intervalSelector function is not defined. Any ideas on what the problem could be? -
Django MPTTModel Tree structure gets corrupted inside Redis Cache upon concurrent creation and retrieval operations
Usecase: We've got a case where one of our models Content represents hierarchical data for our organization and for maintaining this hierarchy we've used django-mptt package which is based on the Modified Preorder Tree Transversal algorithm and for making the response time faster for the client, we've introduced the Redis Cache via django-cacheops package for our models. Img src = http://www.sitepoint.com/hierarchical-data-database-2/ Problem: As we've used MPTTModel for maintaining the hierarchical structure of our data inside the database, when concurrent CREATE and READ requests are made by the clients we end up with Corrupted data inside our Redis Cache. Reason: When we do a create operation on the tree, The MPTTModel Package actually creates the instance of the object inside the database and build/maintains the tree and while the MPTTModel package is building/maintaining the tree at the same time a read request is made to that instance which is then resulting in corrupted data inside the Redis Cache Note:- our system architecture is based on Microservice Architecture due to which we've got a couple of requests being made by different Microservices. Has anyone faced such an issue before and what solution can we use to resolve this problem? -
why can't python import a file from a relative path?
I found this helpful: How to access a module from outside your file folder in Python? But python is unable still to find the folder. I have a django folder structure that looks like this: todoproject pythonDiscordChatbot processLessons.py todoapp testChatFunctions.py I'm trying to import a function called 'routes' into testChatFunctions.py, but I keep getting this error: File "c:\Users\Kaij\Documents\chatSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>tSiteDjango\todoproject\todoapp\tesssLesson import *tChatFunctions.py", line 6, in <modd 'pythonDiscordChatbot'ule> atSiteDjango> & C:/Users/Kaij/Documents/djangoTests/django_tailwind_project/env/Scripts/ from pythonDiscordChatbot.procechatSiteDjango/todoproject/todoapp/testChatFunctions.pyssLesson import * ModuleNotFoundError: No module nametSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>d 'pythonDiscordChatbot Here's what I have tried: # Bring your packages onto the path import sys, os sys.path.append(os.path.abspath(os.path.join('..', 'pythonDiscordChatbot'))) # Now do your import from pythonDiscordChatbot.processLesson import * # from pythonDiscordChatbot.processLesson import routes routes("hello", "website_180.02.1") Thank you -
Cannot login a normal user in a django website having a custom user model
I have made a Custom user model for my website. I have used AbstractBaseUser to make the model and also set it up at the settings. The creation of user and superuser is working fine without any problems and also a super user can login from the admin page. However when I am trying to make a normal user to login in the website is returns User none. But the normal user exists in the datatbase. I am using the authenticate to make a user login since I have used AbstractBaseUser. I am unable to unserstand why is this saying that the user doesn't exist. Please rectify me if I have written some wrong codes. models.py (the custom user model), here the is_active is false but I manually activate it after regd so the problem is not because of this class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique= True) full_name = models.CharField(max_length=255) phone_no = models.CharField(max_length=10, blank= True) address = models.CharField(max_length=500, blank= True) plan = models.CharField(max_length=255, blank= True) age = models.CharField(max_length=2, blank= True) date_joined = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField( default=False) is_active = models.BooleanField( default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.email managers.py (custom user model manager) … -
How can I register with 2 categories of users and save the status in the database?
This is what my current code looks like, but the status is not saved in the database. Even if in models I default = 'Admin' in the database it appears at status: '-'. Why? I want to add the status to the database to know which category users belong to models.py STATUS_CHOICES = Choices( ('Client', 'Client'), ('Master', 'Master') ) class User(AbstractUser): email = models.EmailField(error_messages={ 'unique': 'A user is already registered with this email!'}, verbose_name='email address', max_length=255, unique=True, ) confirmed_password = models.CharField( max_length=128, verbose_name='confirmed_password') status = models.CharField( max_length=100, choices=STATUS_CHOICES, verbose_name='status', default="Admin") username = models.CharField(max_length=254) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] forms.py class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password', 'confirmed_password', 'username') views.py def RegisterUser(request): master = EditUserForm(request.POST) if request.POST: if master.is_valid() and request.POST["status"] == "Master": master.save() messages.success(request, "It was successfully registered master") return render(request, "registration/index.html") elif master.is_valid() and request.POST["status"] == "Client": master.save() messages.success(request, "It was successfully registered CLIENT") return render(request, "registration/index.html") else: return render(request, "registration/register.html", {}) else: master = EditUserForm() return render(request, "registration/register.html", {'master': master}) register.html <h1>Registration Page</h1> <form action="" method="post"> {% csrf_token %} {{ master.as_p }} <input type="submit" name="status" value="Master" /> <input type="submit" name="status" value="Client" /> </form> -
Django drf-spectacular How to split api descriptions for public and private use?
I want to make 2 different documentations. One is for public with few api methods and no authz. Another one is for private usage with all api methods and only for authorized users. -
Django: multiple dates form
so in my .html file i inserted two inputs for two different dates (end and start) From: <input type='date' name='fromdate'/> To: <input type='date' name='todate'/> <input type='submit' value='Submit'/> and in my models.py i have this model class MyDatesInput(models.Model): dates = ArrayField(models.DateTimeField() ) i need to use the dates for an api call like this: http://history.openweathermap.org/data/2.5/history/city?lat={lat}&lon={lon}&type=hour&start={start}&end={end}&appid={API key} how do i link all of this together? -
how to query filter self foreign key
query = Services.objects.filter(parent_id__isnull=True,sub_service__type=0) When im filtering sub_service__type=1 It returns correct output. i.e. type 1 for sub_service, But when i change it to sub_service__type=0 filters doesnot work. Instead it returns me every output. i.e. type 0,1 Instead of type 0 Heres Code: # MODELS class Services(models.Model): type_ = ((1, 'INCLUSIVE'), (0, 'EXCLUSIVE')) service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='sub_service') type = models.SmallIntegerField(blank=True, null=True, choices=type_) # VIEWS @action(detail=False, methods=['get'], permission_classes=(AllowAny,)) def service_list(self, request): query = Services.objects.filter(parent_id__isnull=True,sub_service__type=0) serializer = SubServiceSerializer(query , many=True).data return Response(serializer.data) # SERIALIZER class SubServiceSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class ServiceSerializer(serializers.ModelSerializer): sub_service = SubServiceSerializer(many=True) class Meta: model = Services fields = "__all__" -
Django - how to use many variables in a template tag value
I want to add two variables as the value on an input tag but the syntax I am currently using only renders the first variable. How can I make both variables show up? Current code loan={ amount": 200000, "due_date": "12/12/2021", } <input class="block" id="address" name="address" type="number" value="{{ loan.amount }} {{ loan.currency }}"> This currently outputs nothing -
AuthenticationForm.is_valid() always return False
I'm new to Django. form.is_valid() always return False. from django.contrib.auth.forms import AuthenticationForm class SignInForm(AuthenticationForm): pass Test method is below. form = SignInForm({'username': 'user2', 'password': 'example2'}) self.assertTrue(form.is_valid()) form.is_valid() always return False. Why??? -
Find user name and last name Query Django
In my Django app I have module 'users' which I use to create profiles. I need help on how to query and find user name and last name depending on Profile in 'users'. users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) I'm not sure, but how can I find 'user.first_name' and 'user.last_name' using only Profile. Something like: queryset = User.objects.values('first_name').filter(Profile=Profile_var) -
Limiting the queryset displayed after the foreign key in the template - Django
I know how to return all objects by a foreign key in a Django template. But how to limit their number to the last 3? Is it possible? Example Models.html class Person(models.Model): ... class Tag(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) name = models.CharField(max_length=10) Template.html {% for tag in person.tag_set.all %} ... {% endfor %} What is expected (only the last 3 objects)? {% for tag in person.tag_set.all[:3] %} ... {% endfor %} -
when i make a post it shows this errorField ‘id’ expected a number but got ‘d’. NOTE: the post get created but i get this error
I have tried a lot of things to resolve this issue but they are not working that why i wanna ask somebody that better than me here. Ive tried using a slug field it doesnt show that, but i wanna use id that when it starts showing the error. NOTE: the post get created perfectly well and that it then shows this error but the posts was made. I treid making the post using a forms from my frontend let me show some code views.py def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.creator = request.user form.save() # ← no commit=False messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { 'form': form } return render(request, 'blog/AddPost.html', context) # this is the blog list view def blog_list(request): posts = Blog.objects.filter(status='published').order_by('-created') categoriess = Category.objects.all() context = { 'posts': posts, 'categories': categoriess, } return render(request, 'blog/bloghome.html', context) #this is the blog detail view def blog_detail(request, post_id): post = get_object_or_404(Blog, id=post_id) # post = Blog.objects.filter(slug=blog_slug) categories = Category.objects.all() comments = post.comments.filter(active=True) new_comment = None if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) … -
How to stack filters if parameters exist or not?
If I have something such as this: tasks = Task.objects.filter( Q(datetime__contains=date) & Q(user=uid) if uid!=0 else & Q(member=mid) if mid!=0 else & Q(job=jid) if jid!=0 else ) It will stack/mix the filters dependent on what function parameters are passed, but obviously that doesn't work, what is the best way to continue? -
Fill form when select an element of a datalist
I am trying to fill a form with the data of a local mongodb database. When the user selects a value of the datalist, I want to fill the form with the values of that selected option. I have managed to show the different possible values in the datalist, so the database is well connected already. modificar_centro_educativo.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Rellenar Centros Educativos</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </head> <body> <div class="container"> <form action="/polls/centro_educativo/" method="GET"> <div class="row"> <div class="col"> <label for="centros" class="form-label">Nombre centro</label> <input list="centros" name="browser"> <datalist id="centros" onchange="/polls/centro_educativo/"> {% for result in Centro_educativo_contacto%} <option>{{result.nombre_centro}}</option> {% endfor %} </datalist> <label for="FormControlNombre_contacto" class="form-label">Nombre contacto</label> <input type="text" class="form-control" id="FormControlNombre_contacto" name="nombre_contacto"> <label for="FormControlUbicacion" class="form-label">Ubicación</label> <input type="text" class="form-control" id="FormControlUbicacion" name="ubicacion"> <label for="FormControlTelefono" class="form-label">Telefono</label> <input type="text" class="form-control" id="FormControlTelefono" name="telefono"> <label for="FormControlEmail" class="form-label">Email address</label> <input type="email" class="form-control" id="FormControlEmail" name="email"> </div> <div class="col"> <label for="FormControlGrados" class="form-label">Grados</label> <input type="text" class="form-control" id="FormControlGrados" name="grados"> <label for="FormControlConocimientos_generales" class="form-label">Conocimientos Generales</label> <input type="text" class="form-control" id="FormControlConocimientos_generales" name="conocimientos_generales"> <label for="FormControlToken_moodle" class="form-label">Token moodle</label> <input type="text" class="form-control" id="FormControlToken_moodle" name="token_moodle"> <label for="FormControlUrl_moodle" class="form-label">Url moodle</label> <input type="url" class="form-control" id="FormControlUrl_moodle" name="url_moodle"> <label for="FormControlUsuario_moodle" class="form-label">Usuario moodle</label> <input type="text" class="form-control" id="FormControlUsuario_moodle" name="usuario_moodle"> <label for="FormControlContrasena_moodle" class="form-label">Contrasena moodle</label> <input type="password" class="form-control" id="FormControlContrasena_moodle" name="contrasena_moodle"> </div> </div> <input … -
Django: "AssertionError: 401 != 200" error when user updates profile [closed]
I'm a beginner. I've been strictly following this tutorial to implement user profiles in Django: https://vhutshilo.medium.com/?p=dc7732c96607 Everything has been going well, up until when implementing the ability to update your own profile. All of this is in the test folder. This is the code that gives me an error: '''User updating their own profile''' def test_profile_update(self): #Register register_url = reverse('accounts:register') register_data = { 'username': 'bean', 'password': 'boom12345' } self.client.post(register_url, register_data, format='json') user = User.objects.get(username='bean') self.client.force_login(user) url = reverse(('accounts:profile'), kwargs={'username':'bean'}) data = { 'name': 'Bean', 'bio': "I don't know what to write" } response = self.client.put(url, data, format='json') And the error code: FAIL: test_profile_update (accounts.tests.test_api.AccountAPITestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\varga\Downloads\Rattarium\backend\accounts\tests\test_api.py", line 157, in test_profile_update self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 401 != 200 What's wrong? It's the exact code from the tutorial, and everything up until this point has been working. Thanks in advance. -
ValidationError - Django Q Query - is not a valid UUID
I am trying to get value from User Model, my requirement is that or condition should be in same query. User.objects.get( Q(premium_referral=form.cleaned_data.get('referral_code')) | Q(id=form.cleaned_data.get('referral_code')) ) But it give error ValidationError at /register ['“XUSB5” is not a valid UUID.'] The above query works perfect for id but not for premium_referral field Bellow is the model class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True,blank=True, unique=True) -
Populate Python object with Django Form
I am trying to use a Django form to populate a Python object (not a Django model). I have the feeling I can only either: build a simple form and populate manually use a Django model as proxy The extra difficulty is the form send a GET request The class class Search: def __init__(self): self.min_area = 0 self.max_area = 999 The form from django import forms class MainSearchForm(forms.Form): min_area = forms.IntegerField(label="Minimum", required=False) max_area = forms.IntegerField(label="Maximum", required=False) The view from django.http import HttpResponse from django.template import loader from front.forms.search.main import MainSearchForm from front.gears.search import Search def main(request): search = Search() form = MainSearchForm(request.GET) # manual populating i want to avoid if form.is_bound: search.min_area = form.cleaned_data['min_area'] search.max_area = form.cleaned_data['max_area'] tpl = loader.get_template('front/search/main.html') ctx = { 'form': form } return HttpResponse(tpl.render(ctx, request)) For now, I am populating manually in the view but I am quite sure there is a better way to do it. Am I missing a part of the documentation ? -
Django - method save() put button value to database
I have a problem. I used this [link][1] to complete my exercise, but I dont know, how to do it practically. [1]: https://stackoverflow.com/questions/69964943/how-to-put-button-value-to-database-django/69965390#69965390 I have a few buttons like this: {% for up in ups%} <div id="{{up.name|cut:' '}}" class="m-l-0"> {% for under in unders%} {% if up.pk == under.up.all.0.pk %} <button id="under{{ under.pk }}" class="under overflow-hidden btn btn-lg btn-primary ml-3" style="display:none" value="{{under.nazev}}({{under.up.all.0.nazev}})" type="button">{{under.nazev}}</button> {% endif %} {% endfor %} </div> {% endfor %} and views.py def form_create(request): if request.method == "POST": catch = request.GET.get('name') if request.POST.get(catch, False): novy = Trying(up=request.POST.get(catch)) novy.save() return render(request, 'index.html') and this is models.py class Trying(models.Model): up = models.CharField(max_length=100, null=True, blank=False, verbose_name="Up") I have also models Up and Under. And in under is ForeignKey to Up. I am desperate. I was trying previous question, but its not working. I will be glad for every point. Thank you!!!