Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert list to json?
I have a queryset; queryset = tagReferenceLocationInfo.objects.select_related('ref').filter(tag_id__in=id_list, date__gte=startDate, date__lte=endDate) I got this queryset result data as a list; data = list(queryset) How can convert this list as a json? -
how to change a char field to list field or array field in Django model?
I want the Char field "device_id" to be changed to a list field or an array field without loosing the current data present in the field , so it can hold multiple device ids. class User(AbstractBaseUser, PermissionsMixin): id = ShortUUIDField(primary_key=True, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) phone = models.CharField(max_length=50, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) device_id = models.CharField(max_length=255, blank=True, null=True) Usecase :I need the user to be associated with multiple devices here after -
how to have pagination in a bootstrap modal, such that when it refreshes the modal stays there?
how to have pagination in a modal, such that when it refreshes the modal stays there? Currrently because of the django logic {%%} the page will refresh and it will go to page 2, but the modal would be hidden, I have to open it again. Is there a way to keep the modal there after refresh? Or if better, is there a way to do pagination without using django, through perhaps using javascript instead Django Views.py (this handles the backend for the pagination) paginator = Paginator(album_array, 5) page_number = request.GET.get('page') try: page_obj = paginator.page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) if page_number is not None: if int(page_number) > 1: page_obj.previous_page_number = int(page_number) - 1 else: page_obj.previous_page_number = False if int(page_number) < paginator.num_pages: page_obj.next_page_number = int(page_number) + 1 else: page_obj.next_page_number = False html: <!-- Pagination --> {% if page_obj.has_other_pages %} <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}"><span class="page-link">Prev</span></a></li> {% else %} <li class="page-item disabled"><span class="page-link">Prev</span></li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a href="?page={{ i }}"><span class="page-link">{{ i }}</a></li> {% … -
Is it possible to use the DISTINCT tag on a filtered query?
I am currently working with Django models and I would like to do the following : First, I do a qs = model.objects.all() (where model is the name of my model) Then, I apply some filters on that qs like qs = qs.filter(id_file__startswith=file_id) for instance Finally, I would like to do a raw request (so I can use 'DISTINCT') to get all the distinct places in the "id_place column": for row in qs.raw(f"SELECT file_id, id_place as place FROM {board} group by place"): place = row.place.lower() l_place.append(place) But the problem is that it does the raw request directly in the database, not in the filtered qs. I know it can be done with : places = qs.values("id_place") l_places = set() for row in places: l_places.add(row['id_place']) But I find it not flexible enough for what I would like to do next, and I don't like the fact that I am not using the "DISTINCT" tag that would make this a lot easier and cleaner. Do you have any idea how I could do this ? Thank you in advance! -
Email Activation (Django Project)
I tried to make Account Activation in my Django Project but when i try register user and my code gives error have and does not send the email to given account. SMTPSenderRefused at /accounts/register/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n27sm15044097pfv.142 gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://localhost:8000/accounts/register/ Django Version: 3.2 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n27sm15044097pfv.142 gsmtp', 'webmaster@localhost') Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py, line 871, in sendmail Python Executable: /Users/barkhayotjuraev/Desktop/Django Apps/GreatCard/env/bin/python3 Python Version: 3.8.6 Python Path: ['/Users/barkhayotjuraev/Desktop/Django Apps/GreatCard', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/barkhayotjuraev/Desktop/Django ' 'Apps/GreatCard/env/lib/python3.8/site-packages'] Server time: Wed, 05 May 2021 07:22:03 +0000 i have turned off two step verifications and turned on Less secured apps -
How to make user profile fields like phonenumber, gender, publically hidden in a social media app using django?
in a Social media app how to make phone number field as a private/public field. class User(AbstractBaseUser, PermissionsMixin): groups = models.ForeignKey(Group,on_delete=models.CASCADE) email = models.EmailField(max_length=255,unique=True,) phone = PhoneField(null=False, blank=False, unique=True) phone_visibility = models.BooleanField(default=False) def get_phone_no(self): if self.phone_visibility: return(self.phone) else: return ('') -
How to detect unused python packages in DJango/Docker project using VS Code?
I have been working for moth on a Django project testing and learning and now have 73 packages listed in my requirements.txt many of these packages are not used and I want to remove them Moreover, some packages seems to conflict when I try to install a new one (django-sql-exlplorer) I've read about a first solution that is to use an new env with empty requirement.txt and missing pakcages will prone error ut I use DOcker and this seems to be painful another way, that seems to be easier is using Pycharm option that can inspect code Python: How to detect unused packages and remove them Is there a similar way doing this second method using VS Code? -
NameError at /astrologiaviva Name 'astrologiaviva' is not defined
someone could help to understand this error? NameError at /astrologiaviva name 'astrologiaviva' is not defined The index.html render a page with 3 buttons. I would like to load and display text[0] if you click on the first button, text[1] if you click on the second one and text[2] if you click on the third one. Hopefully this is enough for somone to help me, thanks! <script> window.onpopstate = function(event) { console.log(event.state.section); showSection(event.state.section); } function showSection(section) { fetch(`/${section}`) .then(response => response.text()) .then(text => { console.log(text); document.querySelector('#content').innerHTML = text; }); } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { const section = this.dataset.section; history.pushState({section: section}, "", `/${section}`); showSection(section); }; }); }); </script> <body> <h1>Hello!</h1> <button data-section="astrologiaviva">Astrologia viva</button> <button data-section="aprendizajelibre">Aprendizaje libre</button> <button data-section="arte">Arte</button> <div id="content"> </div> </body> this is urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.name, name="section") ] this is views.py from django.http import Http404, HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "singlepage/index.html") texts = ["ABC", "GHJ", "XYZ"] def name(request, name): if name == astrologiaviva: return HttpResponse(texts[0]) elif name == aprendizajelibre: return HttpResponse(texts[1]) elif name == arte: return HttpResponse(texts[2]) else: raise Http404("No such section") -
Django: How to use a custom social-auth backend?
I have overridden the GoogleOAuth2 class in django social-auth. Currently the new class is in views.py. But I cannot find how to add it to AUTHENTICATION_BACKENDS in settings.py I have tried like this: AUTHENTICATION_BACKENDS = ( '_auth.backends.YouTubeOAuth2', <---------- new backend 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) And adjusted the template: window.open('{% url 'social:begin' 'youtube' %}', '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes'); In the end of the Google auth process comes an error: ModuleNotFoundError at /api/oauth/complete/google-oauth2/ No module named '_auth' -
In Django ModelSerializer unable to mark a field required as false
I am trying to make a field investor required as False in Django Restframework's ModelSerializer. class WatchListSerializer(serializers.ModelSerializer): class Meta: model = WatchList fields = ['id', 'investor', 'property'] extra_kwargs = { 'investor' : { 'required' : False } } However, both the fields are defined as ForeignKeys in the model. As you can see in above implementation I am trying to override the default implementation of field investor using extra_kwargs. Unfortunately, it still asking to provide the value for investor. Here is the model Watchlist - class WatchList(BaseModel): investor = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=True) property = models.ForeignKey(Properties, on_delete=models.PROTECT, blank=False, null=True) class Meta: unique_together = (('investor', 'property',)) def __str__(self): return f'Watch List Object {self.id}:' -
how can i convert str to float (the value of foreignkey)
please how can i convert Foreignkey value string to float ? in models.py i create a following code, the target is to get the value of foreingkey as float then use it to calculate the value of redevance. class production(models.Model): nom= models.CharField(max_length=70, blank=False, null=True) choix_type = ( ('','selectionner le type de projet '), ('exploration/production','exploration/production'), ('developpement/production','developpement/production'), ('Exploitation','Exploitation'), ) forme_projet = models.CharField(max_length=50, default='', blank=False, null=True, choices=choix_type) quantite = models.FloatField(blank=False, null=True) prix = models.FloatField(blank=False, null=True) def __str__(self): return str(self.nom) if self.nom else '' def calcule_production(self): return self.prix * self.quantite class redevance(models.Model): production_projet = models.ForeignKey(production, on_delete=models.CASCADE, null=True, blank=False) cout_transport = models.FloatField(blank=False, null=True) cout_liquifaction = models.FloatField(blank=False, null=True) cout_separation = models.FloatField(blank=False, null=True) def calcule_cout(self): return (self.cout_transport + self.cout_liquifaction + self.cout_separation) - self.production_projet type error the error seems like this: thanks -
How to Create an api to extract xml file in django
I need to create an API in Django that will use to take an XML file and extract the data from it. I have created models and serialization and now I can not understand the view part(api) please help. -
Django Test ValidationError when input is not a digit
How to test ValidationError when User inserts Text for my zip code example? This is my validation in my models.py file: def validate_zip_code(value): zip = str(value) if not zip.isdigit(): raise ValidationError('Please enter a valid zip code.') And my test file in test_models.py class TestZIP(TestCase): def test_zip_code_digit(self): self.assertRaises(ValidationError, validate_zip_code, 'Random Text') Running python.manage.py test I get no Errors, but when I run coverage html and check the test percentage, I get told that this function has not been tested correctly. What am I doing wrong? -
Otree Page not found Server Error 404. How to add sub-url to the domain name?
I am using the kubernetes cluster where, I already have a domain name "https://example.com". I need to deploy the otree server by creating the sub-urls above the domain which is already purchased for hosting. Is their is something i can change in settings.py to make this change happen. enter image description here -
How to get data in the form of table in django using cloud firestore?
I'm trying to get data in the form of a table, but the data is not being fetched, I don't know how to get the record, I'm using cloud firestore to get the data -
froala editor show textarea in django admin site
I'm trying to use froala editor, but its show textarea in admin site here is my model.py code from django.db import models from froala_editor.fields import FroalaField # Froala Editor class Page(models.Model): contant = FroalaField(options={ 'toolbarInline': True, }) def __str__(self): return self.contant -
Django html variables are splitting when binding
I have a simple html template which shows permissions in a table for each group. Every cell of the table, contains a button. I want to show the name of the permission in a popover of every button! The problem is that Django variable is not working fine! <button type="submit" class="btn" title={{ permission.name }}> ... </button> As you can see in above, the title is initialized with {{ permission.name }} and I expect to see full name of permission when hovering button, but it just contains the first word! Which is not odd because this is what I saw in the inspect elements: <button type="submit" class="btn" title="نمایش" لیست="" کاربران=""> ... </button> As you can see, title is ruined! What's the problem here? Why it's not working as I expected? -
Django + Celery run task only once (at a specific time)
Let me explain what I want to do through the example. class SampleModel (models.Model): start = models.DateTimeField (** options) end = models.DateTimeField (** options) status = models.BooleanField (** options) For example, when a user is banned, the ban date (start) and the ban expiration date (end) and the (status) field that I add to check if they are banned. (This is actually just an example of different scenarios, the date a post was opened to visitors, etc.) I know that I can create tasks using "Django + Celery + Celery-beat", but what i want to do is to set the run time of the task and run it only once -
How to serializer my children model objects properly?
Here I am trying to return the children objects serialized data like this but this is not working. I got this error. raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Type is not JSON serializable How to solve this issue ? model class Type(models.Model): name = models.CharField(max_length=200, unique=True) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, null=True, blank=True) serializer class ListTypeSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Type fields = ['name', 'children'] # for some reason I can not do `return obj.type_set.values('name')` # since I have so many customized variable names. # I am displaying only name here in question. def get_children(self, obj): return ListTypeSerializer(obj.type_set.all(), many=True, context={'request': self.context['request']}).data -
display list item in HTML template
I have 2 list that I imported from my python code to the html template which is called eligable and overTimeHours. I tried displaying them like this: <ul> {% for item in eligable %} <div class="pad3"> <li>{{item}} - {{item.overTimeHours}}</li> </div> {% endfor %} </ul> but only {{item}} is displayed but {{item.overTimeHours}} did not display. here is my python code: def specificDate(response): empName = employeeName.objects.all eligable = [] overTimeHours = [] check = False if 'checkEmployee' in response.POST: n = response.POST.get("nameEmployee") specDate = response.POST.get("date") correctDate = None try: newDate = datetime.strptime(specDate, '%Y-%m-%d') correctDate = True except ValueError: correctDate = False print("This One: ",correctDate) if correctDate == True: if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists(): check = True emp = employeeName.objects.get(employee=n) t = Name.objects.get(name=emp, date=specDate) overT = Name.objects.filter(name=emp, overtime=True) for item in overT: eligable.append(item.date) totalTime = (datetime.combine(item.date, item.timeOut)- datetime.combine(item.date, item.timeIn)).seconds/3600 hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) overTimeHours.append(time) checkIn = t.timeIn.strftime("%H:%M:%S") checkOut = t.timeOut.strftime("%H:%M:%S") messages.info(response, checkIn + ' - ' + checkOut) return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable, "check":check, "overTimeHours":overTimeHours}) else: messages.info(response, 'Result does not exist') else: messages.info(response, 'Please enter correct input') else: pass return render(response, "main/specificDate.html", {"empName":empName}) -
i want to make a dropdown menu . I searched for the different techniques but my design is changing
I want to make that lead(below Dashboard) to be dropdown menu. without changing my design. The lead is under ul tag. <div class="wrapper "> <div class="sidebar" data-color="purple" data-background-color="white" data-image="../assets/img/sidebar-1.jpg"> <div class="logo"><a href="http://www.creative-tim.com" class="simple-text logo-normal"> Creative Tim </a></div> <div class="sidebar-wrapper"> <ul class="nav"> <li class="nav-item "> <a class="nav-link" href="{% url 'UserProfile' %}"> <i class="material-icons">person</i> <p>Lead</p> </a> </li> -
Multiple Choice in Models Inquiry
We are doing a React frontend and Django backend project. We will have a series of moral dilemmas that each will have separate multiple-choice options. Each separate dilemma may have anywhere between 2 and 4 multiple-choice possible answers. We are struggling to find an answer as to what the best way to do this is.. This is the super rough model that we have so far: class Dilemmas(models.Model): title = models.CharField(max_length=64) image = models.ImageField(upload_to='ethics_app/image_assets') dilemma = models.TextField() # insert multiple-choice options here that will be between 2 and 4 possible answers. def __str__(self): return self.title -
How to use functors instead of functions in django?
I have a model called Story: from django.db import models from api import settings from core.functions import UploadImage from .settings import STORY_UPLOAD_PATH get_story_upload_path = UploadImage(STORY_UPLOAD_PATH) class Story(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_story_upload_path) caption = models.TextField() expiration_date = models.DateTimeField() import datetime import uuid import os The behavior for uploading photos is the same for multiple models, thus I decided to make a functor that holds the path to upload to and pass it to the models with common behaviour. The functor: import datetime import uuid import os class UploadImage: def __init__(self, upload_path): self.upload_path = upload_path def __call__(self, instance, filename): filename = f'{datetime.datetime.now()}_{uuid.uuid4()}_{filename}' return os.path.join(self.upload_path, instance.username, filename) The serializer class: from rest_framework import serializers from models import Story, ViewedStory class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ('id', 'user', 'image', 'caption') read_only_fields = ('id', ) When I try to make migrations, I get this error: Migrations for 'stories': stories/migrations/0001_initial.py - Create model Story - Create model ViewedStory Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File … -
Debugging not working in VS Studio Code Django
I have been working through the official Django Tutorial in Visual Studio Code but I have run into an issue. Currently when I ever I set a break point at the line now = datetime.now the debugger seems to fail reach it. Attached it my urls.py code and my view.py code. from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), path("hello/<name>", views.hello_there, name="hello_there"), ] Above is the urls.py code. Below is the views.py code. import re from django.utils.timezone import datetime from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") def hello_there(request, name): now = datetime.now() formatted_now = now.strftime("%A, %d %B, %Y at %X") # Filter the name argument to letters only using regular expressions. URL arguments # can contain arbitrary text, so we restrict to safe characters only. match_object = re.match("[a-zA-Z]+", name) if match_object: clean_name = match_object.group(0) else: clean_name = "Friend" content = "Hello there, " + clean_name + "! It's " + formatted_now return HttpResponse(content) I apologize if the formatting is off, I am a beginner and new to stack overflow. -
Django - Follow Button Functionality Does Not Work
I'm attempting to create a project similar to a social networking site, where users can follow each other. The follow button on someone's profile will allow your own profile to follow that user. Currently when I click the follow button on a profile, nothing happens. There's no error either. I'm pretty stuck with where to go on this. Any help is super appreciated. Relevant parts of urls.py: path("fol/<str:username>", views.fol, name="fol"), path("following_list/<str:username>", views.following_list, name='following_list'), path("profile/<str:username>", views.profile, name="profile"), views.py - function for following: def fol(request, username): if request.method == 'GET': currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts.count(), 'profileuser': profileuser, 'follower': follower, 'totalfollower': totalfollower, 'following': following, 'totalfollowing': totalfollowing, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) else: currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if not following_each_other: f = Follow.objects.create(target=profileuser, follower=currentuser) f.save() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=request.user, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) context = { 'posts': posts.count(), …