Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django many-to-many filter and count
I'm using Django 2.2 I have a model structure class Product(models.Model): data = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class ProductRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) tags = TaggableManager() class TrackingData(models.Model): d = models.CharField(max_length=200) product = models.ForeignKey(Product, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) Where TaggableManager() is a many-to-many field by django-taggit library. I have the following tags tags = ['tag1', 'tag2'] I want to filter the TrackingData by the tags from the ProductRelation and get the count of tracking data for each tag. Each ProductRelation object can contain many tags. The example table would be like # ProductRelation user | product | tags --------+----------+--------- user1 | product1 | tag1, tag2 user2 | product2 | tag2, tag3 I'm able to filter the tracking data like from functools import reduce from django.db.models import Q import operator t = TrackingData.objects.filter( product__productrelation__user=u ).filter( reduce( operator.or_, ( Q(product__productrelation__tag__name__icontains=x) for x in tags ) ) ) But how will I get the count by tags? -
Django ModuleNotFoundError can't import model file
I am new to Django and want to create dummy data so using faker library with sqlite db. Created models.py and DummyData.py . models.py from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=200) surname = models.CharField(max_length=200) email = models.EmailField(max_length=200, unique= True) def __str__(self): return "Object created " + "Name :-" + self.name + " Surname :-" + self.surname + " Email :-" + self.email for creating fake data made DummyData.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'Course.settings') # 1. method from .models import User # 2. method from appTwo.models import User Both ways I am not able to import Users class from models getting error like Method 1 output ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package Method 2 output ModuleNotFoundError: No module named 'appTwo created empty init.py in appTwo folder. File structure is as above But I can able to import models.py using method 2 in Terminal, So I am little bit confuse. -
How can i use for loop in Django to have different titles and texts?
here is my html code. I wanna use for loop to have different texts in different titles. I wanna put each minor sentence in each title! not all 5 sentences in one title! {% for num in list %} <h3>COVID 19 is coming down. {{ num }} </h3> {% for sen in text %} <div><p>{{ sen }}</p></div> {% endfor %} {% endfor %} and here are my views. def index(request): date = dt.datetime.today().date _list = [1, 2, 3, 4, 5] text = ['This minor text', 'This is major text', 'This is fifth text', 'This is my text', 'This is the last text'] return render(request, 'index.html', {'date': date, 'list': _list, 'text': text, }) -
Django tags with html tab element
i'm trying to use tabs with django. the blocks work when I call them up using a button, for example. the base html excerpt therefore looks like this: <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-A-tab" data-toggle="tab" href="#nav-A" role="tab" aria-controls="nav-A" aria-selected="true">A</a> <a class="nav-item nav-link" id="nav-B-tab" data-toggle="tab" href="#nav-B" role="tab" aria-controls="nav-B" aria-selected="false">B</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-A" role="tabpanel" aria-labelledby="nav-A-tab">{% block A%}{% endblock %}</div> <div class="tab-pane fade" id="nav-B" role="tabpanel" aria-labelledby="nav-B-tab">{% block B%}{% endblock %}</div> </div> I now understand why that doesn't work. Since django does not render the part {% block A%} {% endblock%} as long as it is not called ... hence my consideration I use the href property so that the code looks like this. <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-A-tab" type="submit" data-toggle="tab" href="{% url 'a:A' %}" role="tab" aria-controls="nav-A" aria-selected="true">A</a> <a class="nav-item nav-link" id="nav-B-tab" data-toggle="tab" type="submit" href="{% url 'a:B' %}" role="tab" aria-controls="nav-B" aria-selected="false">B</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-A" role="tabpanel" aria-labelledby="nav-A-tab">{% block A%}{% endblock %}</div> <div class="tab-pane fade" id="nav-B" role="tabpanel" aria-labelledby="nav-B-tab">{% block B%}{% endblock %}</div> </div> unfortunately that doesn't help. Does somebody has any idea? many thanks -
Creating Dynamic Tuple for Sending Mass Email Django using send_mass_mail
I see a lot of documentation and example to create mass email like below message1 = ('That’s your subject #1', 'That’s your message body #1', 'from@yourdjangoapp.com', ['to@yourbestuser1.com', 'to@yourbestuser2.com']) message2 = ('That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com']) message3 = ('That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com']) send_mass_mail((message1, message2, message3), fail_silently=False) I want to send mass email to N number of users returned from my queryset with the same message. I am using the code below to send mass email. However , it is very slow and would want to know if any efficient methods exists or since am using gmail for testing, its going to be slow. def sendMassPasswordResetEmail(request): schoolval = user_school.objects.filter(username=request.user.id).values_list('schoolCode',flat=True)[0] clsval = student_group.objects.filter(schoolCode=schoolval).values_list('classVal_id').distinct() student = studentclass.objects.all().prefetch_related('student_group_set__username').filter(student_group__classVal__in=clsval).distinct() addStudentlink = True #groups = student.values('student_group') userinschool = User.objects.filter(user_school__schoolCode=schoolval,user_type=1).values('username') html_content = render_to_string('dashboard/registration_email.html') # render with dynamic value text_content = strip_tags(html_content) # Strip the html tag. So people ca for recipient in userinschool: subject, from_email, to = 'Account Activation xxxxx', 'xxxxxgmail.com.com',recipient.get('username') print(recipient.get('username')) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request,'dashboard/add-student.html',{'students':student, 'addStudentlink':addStudentlink}) -
Heroku CLI not working within pycharm terminal
I am new to django and working on a django project, using pycharm as the editor. I am trying to deploy it on heroku. I installed heroku cli on my windows os, and tested it using command prompt, and it is working. But within pycharm's terminal, when I type "heroku", it does not recognize it. What am I missing? -
Handling Authentication in Django + GraphQL + Vuejs
I'm currently developping an application (SPA) with this stack : Django - GraphQL (graphene-django) - Apollo - VueJS I ended up at a point where I want to set up the authentication and I feel completely lost. I think there are 2 ways : Using the builtin Session system from Django but I don't know how to get the state of it (Am I logged in or not) in the frontend (VueJS where I could have a state variable in Vuex) and even if it's possible. Using JWT I'm currently trying JWT but once again, I feel completely lost since I've read many articles that say it is not a good idea to store the tokens in localStorage or in the sessionStorage. I began that way following several tutorials and I faced one problem, how do I get a token when the first one expires ? In terms of state, I could handle a state variable in Vuex that looked into localStorage,... But since I've read it's not good that way (XSS attacks,...), I decided to do it with cookies. Again, I'm lost ! While I managed to get the cookie once, with the jwt_cookie() : It expires quite fast … -
Python Pandas number column range 1-999999 messes up formats above 1000 like 1 000,000 and it cannot be converted to num from string
My problem is, I've got an excel file containing a huge amount of data, and some columns are supposed to be number fields. These columns contain numbers ranging from 1-99999. Handling these numbers is a real pain, in fact I have no solution how to, as I cannot convert them from string to number at all. My end goal would be to be able to do arithmetic operations with these columns, mainly multiplication and division. Right now I get a typeerror saying "str" or "float" cannot be matched with "/", so when I'm trying to divide these columns' values, it wont let me. First off, numbers above 1000 are totally messed up in the original report file. There is a whitespace in front of them, so for instance it is not like '1000', but ' 1000,000' (disregard the '' in this cases, just trying to help spot the leading whitespace). Also, there's this ,000 part that I cant understand. For numbers below 1000 there's nothing like that, however, for numbers above 1000, without exception it trails them with this decimal separator and 3 decimal places all filled with 0. Picture: I've been trying to sort this for 2 days now, … -
How to delete objects and their historical records at once in django?
I have an object called PTORequest which have a history field for storing HistoricalRecords of it. history = HistoricalRecords() I have not mentioned cascade_delete_history=True while creating history column which would automatically cascade history records. How do I delete all the objects and their historical records from PTORequest table without doing model changes and migrations? One thing I can think of is this: for i in PTORequest.objects.all(): print i.history.all().delete() print i.delete() Is there any other efficient way to do this? I'm using Django 1.11 -
aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN' When trying to use redis
I have redis 5.4. and I am gettign this error: aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN' I am following the tutorial on the django-channels website. This is the consumer code: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) I run my server using python manage.py runserver 0.0.0.0:8080 -- noreload maybe it has to do something with that, I open the page on the 5656 port and it is hosted on 8080 as I am using vagrant and those are the set ports in the VagrantFile. -
Continue Execution After HttpResponse Django
I want am working with a webhook that times out . To acknowledge receipt I have to send a 200 ok response . Then continue my execution. Code looks something like this def webhook(request): return HttpResponse(status=200) print(“ok”) -
Problem with rendering datepicker in django bootstrap template
In my Django bootstrap template, I am rendering a text field like below to insert the record --- Employee Contact: {{ form.econtact }} --- Like code below --- Employee Date of Birth: {{ form.edob }} </div --- I want to do the same for the date but I am unable to do please help with a date picker to choose date only I am trying this code from this answer How to use the bootstrap-datepicker in Django app? but it is not working template.html --- {{ form.date }} --- JavaScript --- $(function () { $('#datetimepicker1').datetimepicker({ format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker. }) }); --- Please help. -
Floating Point Exception with 'Openseespy' in Python
While trying to import module from 'openseespy - (v3.2.2.3)' on a Ubuntu VM machine(cloud), I'm running into 'Floating Point Exception', refer to the screenshot below. Apparently, the same module works fine on a local machine with Ubuntu VirtualBox (it’s a VM machine on a Windows laptop). Note: I'm using Python 3.8.0 -
update users logging in through API in django admin
I have made a APP in which users log in through a microsoft graph API now i want every user that has logged in updated in django Admin users just like normal django auth would do. -
Error while eb create - argument of type 'NoneType' is not iterable
this is the first time I am deploying a web application through AWS. I followed this tutorial - https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html While creating a new environment with -> eb create, I got this error. ERROR: TypeError - argument of type 'NoneType' is not iterable Can anyone please help me know what's the issue This is what I have done so far: PS E:\projects\portfolio> & e:/projects/portfolio/eb-virt/Scripts/Activate.ps1 (eb-virt) PS E:\projects\portfolio> pip freeze > requirements.txt (eb-virt) PS E:\projects\portfolio> mkdir .ebextensions Directory: E:\projects\portfolio Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 8/26/2020 10:26 AM .ebextensions (eb-virt) PS E:\projects\portfolio> deactivate PS E:\projects\portfolio> eb init -p python-3.6 django-tutorial You have not yet set up your credentials or your credentials are incorrect You must provide your credentials. (aws-access-id): A*****************Q (aws-secret-key): V*****************************i Application django-tutorial has been created. PS E:\projects\portfolio> eb init Do you wish to continue with CodeCommit? (Y/n): y Enter Repository Name (default is "portfolio"): portfolio Successfully created repository: portfolio Enter Branch Name ***** Must have at least one commit to create a new branch with CodeCommit ***** (default is "master"): portfolio_branch1 Successfully created branch: portfolio_branch1 Do you want to set up SSH for your instances? (Y/n): y Type a keypair name. (Default is aws-eb): aws-eb-portfolio Generating public/private … -
got problem in the ajax form submission code
<form action="" method="post" class="f-color" id="email-form"> {% csrf_token %} <label>Name</label> <input type="text"> <label>From</label> <input type="email"> <label>Message</label> <button type="submit">Sent</button> </form> <div class="mt-5" id="spin" style="display: none;"> <div class="loader"></div> </div> <div id="msg"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).on("submit", "#email-form", function(event){ event.preventDefault(); $('#spin').show(); $.ajax({ url: "{% url 'contact' %}", type: "POST", data: $("#email-form").serialize(), success: function(data){ $("#spin").hide(); if(data.status == "success"){ $("#msg").html("<p class='alert alert-success'>we will get back to you as soon as possible</p>" ); $("#email-form").reset(); } } }) }) }) </script> using this code I can submit the form successfully, but after the form submission the message(msg) not showing, the 'if condition statement' is perfectly working (for the testing I gave the alert, the alert was worked) another problem is form reset, for this I'm using $("#email-form").reset(); but the form dose't reset how can I solve these problems -
when i send data through my api i get this Error TypeError at /api/add/ Object of type UserInfo is not JSON serializable
i have two models one is for User and another is UserInfo, i am inserting additional information of user to a model that have foreignkey relationship with user model. when i add additional information to the api ,the data is getting stored but i get error instead of response. serilaizers.py class UserCreateSerializerCustom(UserCreateSerializer): class Meta(UserCreateSerializer.Meta,): model = User fields = ( 'id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', ) ## User Additional Info Serializers class UserAdditionalSerializers(serializers.ModelSerializer): user = UserCreateSerializerCustom() class Meta: model = UserInfo fields = ( 'user', 'address', 'zipcode', ) Views.py class UserAdditionalView(generics.ListCreateAPIView): queryset = UserInfo.objects.all() serializer_class = UserAdditionalSerializers # authentication_classes = (TokenAuthentication) def post(self,request,*args,**kwargs): token = request.META['HTTP_AUTHORIZATION'].split(" ")[1] print(token) us = Token.objects.get(key=token).user user1 = User.objects.get(email=us) user,_ = UserInfo.objects.get_or_create(user=user1) user.address=request.POST['address'] user.zipcode=request.POST['zipcode'] user.save() return Response({'user':user}) urls.py path('add/',views.UserAdditionalView.as_view()), models.py class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) #phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') #phone = PhoneNumberField(unique=True,blank=False,null=False) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email class UserInfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) address = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) def __str__(self): return str(self.user) My expected response is { "user": { "id": 3, "email": "test@test.com", "username": "test", "first_name": "test", "last_name": "test", "phone": "+1(123)-456-7890" }, "address": "kjbnjklqnja", "zipcode": "69996" } … -
DRF Viewset set action detail=false for exixting routes
@action(detail=False) def update(self, request): serializer = self.serializer_class(user, request.data) . . . . return Response(res) How to set detail=False for existing routes in Django Rest Framework? I don't need the primary key for this route to work, currently I'm sending a dummy value in the URL for this route. It works but still I wanna know if there is a way to bypass it by setting detail=False. If we set @action for it, it throws an error Cannot use the @action decorator on the following methods, as they are existing routes: Is there any solution for this? Thanks in advance! -
Celery task hangs after calling .delay() in Django
While calling the .delay() method of an imported task from a django application, the process gets stuck and the request is never completed. We also don't get any error on the console. Setting up a set_trace() with pdb results in the same thing. The following questions were reviewed which didn't help resolve the issue: Calling celery task hangs for delay and apply_async celery .delay hangs (recent, not an auth problem) Eg.: backend/settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", RABBIT_URL) CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", RABBIT_URL) backend/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) app/tasks.py import time from celery import shared_task @shared_task def upload_file(request_id): time.sleep(request_id) return True app/views.py from rest_framework.views import APIView from .tasks import upload_file class UploadCreateAPIView(APIView): # other methods... def post(self, request, *args, **kwargs): id = request.data.get("id", None) # business logic ... print("Going to submit task.") import pdb; pdb.set_trace() upload_file.delay(id) # <- this hangs the runserver as well as the set_trace() print("Submitted task.") -
Remove current URL autofill in fetch()
I'm new to web developing and I'm having a bit of trouble with my first website. I'm using Django REST Framework on the backend for the API and React.js on the frontend. I'm on URL 127.0.0.1:8000/course/1 and I'm trying to make a call to the API to retrieve the information of course 1. The API is in 127.0.0.1:8000/api/courses/1, so I use: fetch('localhost:8000/api/courses/1') The problem is that it apparently makes a GET request on 127.0.0.1:8000/course/1/127.0.0.1:8000/api/courses/1 which obviously doesn't exist. The problem is that for some reason it automatically appends the argument of fetch to the current URL. I tried this from the home URL with fetch('api/course/1') and it works. What should I do? This is the complete code: import React, { Component } from 'react'; export class Course extends Component { constructor(props) { super(props); this.state = { course: {} } this.getCookie = this.getCookie.bind(this); this.fethCourse = this.fetchCourse.bind(this); } getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie != '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = … -
Django server is slow on wsl
Django server takes huge time to load/reload in wsl(Ubuntu). Running the same app on linux is fine. Is wsl it takes around 30-40 secs to load/reload. Sometimes even more. I tried setting path /etc/wsl.conf , there was no improvement. -
capture image and save it to database with django
I am trying to make a web app with django in which it clicks an image from the camera and saves the image to a database. How can that be implemented? if there is a source code available, kindly share a link to it. thank you -
Django-folium Integration ERROR (__init__() takes 1 positional argument but 2 were given)
Django beginner here.trying to display folium maps on my webpage. but getting this error: Screenshot of error Django version===3.0.2 code for this is as follows: views.py from .models import Product from .forms import Productform # Create your views here. import folium from django.views.generic import TemplateView class FoliumView(TemplateView): template_name = "folium_app/map.html" def get_context_data(self, **kwargs): figure = folium.Figure() m = folium.Map( location=[45.372, -121.6972], zoom_start=12, tiles='Stamen Terrain' ) m.add_to(figure) folium.Marker( location=[45.3288, -121.6625], popup='Mt. Hood Meadows', icon=folium.Icon(icon='cloud') ).add_to(m) folium.Marker( location=[45.3311, -121.7113], popup='Timberline Lodge', icon=folium.Icon(color='green') ).add_to(m) folium.Marker( location=[45.3300, -121.6823], popup='Some Other Location', icon=folium.Icon(color='red', icon='info-sign') ).add_to(m) figure.render() return {"map": figure} Templates\folium_map.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {{map.header.render|safe}} </head> <body> <div><h1>Here comes my folium map:</h1></div> {{map.html.render|safe}} <script> {{map.script.render|safe}} </script> </body> </html> I WOULD ALSO APPRETIATE IF SOMEBODY COULD TELL ME HOW TO MAKE ANNOTATIONS ON THE MAP DISPLAYED please annswer ASAP -
Django Rest Framework: Custom Views
i have a django installation with currently two apps ( common / destinations ) and i want to create custom api views across these apps. in common i have a model country models.py app common from django.db import models # Create your models here. class Country(models.Model): CONTINENTS = ( ('Europe', 'Europe'), ('Asia', 'Asia'), ('Africa', 'Africa'), ('northamerica', 'North America'), ('southamerica', 'South America'), ('australia', 'Australia') ) name = models.CharField(max_length=120) code = models.CharField(max_length=2) continent = models.CharField(max_length=11, choices=CONTINENTS) content = models.TextField() image = models.FileField() models.py app destination from django.db import models # Create your models here. class Destination(models.Model): name = models.CharField(max_length=120) code = models.CharField(max_length=3) country = models.ForeignKey("common.Country", on_delete=models.CASCADE) image = models.FileField() serializers.py app destination from rest_framework import serializers from common.serializers import CountrySerializer from .models import Destination class DestinationSerializer(serializers.ModelSerializer): country = CountrySerializer() class Meta: model = Destination fields = ("id", "name", "code", "country", "image") views.py app destination from rest_framework import views from rest_framework.response import Response from .serializers import DestinationSerializer, ImageSerializer from .models import Destination # Create your views here. class DestinationView(views.APIView): def get(self, request, code): destination = Destination.objects.filter(code=code.upper()) if destination: serializer = DestinationSerializer(destination, many=True) return Response(status=200, data=serializer.data) return Response(status=400, data={"Destination not found"}) When i make a API call /api/destination/PMI everything works. i get my destination … -
Create and Update API for Project and Task (One to Many relationship) Django REST API (bulk create and update)
Does anyone have a good example of creating an API where I can create a project and add multiples tasks to it? class Project(models.Model): name = models.CharField(max_length=30) class Task(models.Model): priority = models.CharField(max_length=30) todo = models.CharField(max_length=30) project = models.ForeignKey(Project, on_delete=models.CASCADE) I would like to be able to create a project and at the same time provide a list of tasks for the project. Json post would look something like this { name: "Project", tasks: [ {priority: "High", todo: "Create front-end page" }, {priority: "High", todo: "Connect back-end " }, {priority: "High", todo: "Deploy server " } ] } With this Json I hope to create project with name="Project name" and after creating project I would like to add the tasks which uses the project as foreign key. From this API I hope to be able to project model with field name = "Project name" and creating the other 3 tasks model using given fields priority, todo, and project as a foreign key.