Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Model instance, whenever a datetime object is passed it is stored as tuple. Not happens always
I am experiencing a strange behaviour in my views.py file: in my user model i have date_something = models.DateTimeField(blank=True, null=True) The below is the code related in views.py match = User.objects.get(email='test@test.com') match.date_something = datetime.datetime.now(tz=pytz.timezone("UTC")) or timezone.now() # just want to check whats is stored from above line check = match.date_something locals()['check'] output: in the runserver console (datetime.datetime(2019, 10, 10, 8, 20, 10, 787399, tzinfo=<UTC>),) So here we see that the check is a tuple. Because of this when i am trying to save the model match.save() it says TypeError: expected string or bytes-like object I checked this code in dango Shell_plus and it gives the right results. In [2]: import datetime ...: import pytz ...: ...: match = User.objects.get(email='test@test.com') ...: match.date_something = datetime.datetime.now(tz=pytz.timezone("UTC")) ...: check = match.date_something ...: ...: locals()['check'] Out[2]: datetime.datetime(2019, 10, 10, 8, 25, 59, 533597, tzinfo=<UTC>) -
Django 2.2 : Integrity Error: Foreign Key Constraint Failed
While submitting a Complaint Form, I am trying to set the value of the grievant to the user logged in, but I am getting a Foreign key Constraint error. I am setting the initial value of grievant using form.inital. Please help. models.py class User(AbstractUser): is_grievant = models.BooleanField(default=False) is_department = models.BooleanField(default=False) class Grievant(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) Registeration = models.IntegerField(default=0000) Room = models.CharField(max_length=50) Hostel = models.CharField(max_length=100) def __str__(self): return self.student.username class Complaint(models.Model): grievant = models.ForeignKey('grievance_app.Grievant',on_delete=models.CASCADE,related_name='complaintee',primary_key=True) department = models.ForeignKey('grievance_app.Department',on_delete=models.CASCADE) text = models.TextField() heading = models.CharField(max_length=200,blank=False,null=False,default='Problem') media = models.ImageField(upload_to='media/',blank=True) created_date = models.DateTimeField(default=timezone.now()) status_choices = [('D','Done'),('P','Pending'),('N','Not Accepted')] status = models.CharField(choices=status_choices,max_length=1,default='N') class Meta(): verbose_name_plural = 'Complaints' def change_status(self,choice): self.status = choice self.save() def __str__(self): return self.heading def get_absolute_url(self): return reverse("complaint_detail",kwargs={'pk':self.pk}) forms.py class ComplaintForm(forms.ModelForm): class Meta(): model = Complaint fields = ('department','heading','text','media',) views.py @method_decorator([login_required, grievant_required], name='dispatch') class CreateComplaintView(CreateView): login_url = '/login/' redirect_field_name = 'complaint_detail.html' template_name = 'create_complaint.html' form_class = ComplaintForm model = Complaint def set_grievant(self): ComplaintForm(initial={'grievant':self.request.user.is_active.username}) form.save() -
Questions about the use of 2D arrays in django templates
I want to draw a histogram (dynamic data generation) with echarts. I pass two-dimensional array data from view.py to the template, but I found that the array generated by django's templating language is a bit different from the "array" in html. view.py def get(self, request, param1): ... express = PerRnaExpression.objects.get(transcript_id="MSTRG.12393.2") x_indica_tissues = [["V2"], ["V4"]] return render(request, "Transcript_Content.html", {"express": express, "x_indica_tissues": x_indica_tissues, }) PS:express is two-dimensional array, such as [[15.7667285, 9.452281, 12.95694325, 14.987118, 12.264012], [13.0935945, 10.0311545, 12.2275855, 19.301165, 18.359003]] Transcript_Content.html <script type="text/javascript"> var myChart = echarts.init(document.getElementById('chart-express')); var option = { title: { text: "indica tissues" }, tooltip: {}, dataset: { source: [ ['product', 'glume', 'leaf', 'panicle', 'root', 'stem'], {{ x_indica_tissues.0|add:express.indica_tissues.0 }}, {{ x_indica_tissues.1|add:express.indica_tissues.1 }} ], }, xAxis: {type: 'category'}, yAxis: {}, series: [ { type: 'bar', }, { type: 'bar', }, ] }; myChart.setOption(option); </script> The value of {{ x_indica_tissues.0|add:express.indica_tissues.0 }} is ['V2', 15.7667285, 9.452281, 12.95694325, 14.987118, 12.264012]. The result of the above is that I can't see any graphics. If I replace the expression with the value of the expression, the histogram can display normally. Can't I use a two-dimensional array, do I have to pass the data to the template after all the operations are completed in view.py?Can I … -
Python django annotate count always 1
I have a problem with Django, i run this django request, but the annotation seems to be incorrect. def find_team_from_match_request(match_request: MatchRequest) -> Optional[Team]: """Find a team from a MatchRequest""" sport: Sport = match_request.criteria.sport rank_group: int = match_request.group.get_rank(sport) max_users: int = sport.playerPerTeam - match_request.group.count_users() interval: int = match_request.get_rank_interval() team: Team = Team.objects.annotate( num_users=Count('groups__users'), num_groups=Count('groups'), rank=Round('groups__users__sportsStats__rank'), rank_sum=Sum('groups__users__sportsStats__rank'), rank_distance=Func(Abs('rank') - rank_group, function='ABS') ).filter( match_id__isnull=True, sport=sport, num_users__lte=max_users, rank__lte=(rank_group + interval), rank__gt=(rank_group - interval), rank_distance__lte=interval ).order_by( 'rank_distance', 'rank' ).first() if team is not None: print('team from match request', team) print('max_users', max_users) print('num_users', team.num_users) print('num_groups', team.num_groups) print('rank', team.rank) print('rank_sum', team.rank_sum) print('rank_distance', team.rank_distance) print('num users all', team.count_users()) return team For an example, running this function I have these outpout max_users 4 num_users 1 num_groups 1 rank 1360 rank_sum 1360 rank_distance 240 num users all 3 team from match request Team object (1) So, when i use the function to count the users in a team (count_users) i get num_users == 3, but the count found by django is 1, i don't understand why. And here is my models: class Team(models.Model): """Team model""" sport = models.ForeignKey(Sport, on_delete=models.DO_NOTHING, related_name='teams') groups = models.ManyToManyField(Group, related_name='teams') match = models.ForeignKey(Match, on_delete=models.DO_NOTHING, related_name='teams', null=True, blank=True) def count_users(self) -> int: """Count the associated users of … -
'NoneType' object is not iterable after explicit check
I get this error even if i explicitly check if it is not none. def to_representation(self, instance): representation = super(UserSerializer, self).to_representation(instance) representation['companies'] = [] #return representation if instance.companies.all() is not None: for entry in instance.companies.all(): company = UserCompanySerializer(entry).data representation['companies'].append(company) return representation -
Django save QuerySet into session
I'm trying to save filtered QuerySet data into request.session. I try do this with pickle but i need to serialize QuerySet before putting data into request.session Is there a easy way to save QuerySet object inside session? My attempts: with pickle: pickle without pickle [output is string]: # save data product_data = Product.objects.filter(Q(title__icontains=search_sequence)) product_data = serializers.serialize('json',product_data) request.session['product_data'] = product_data # recieve data if 'product_data' in request.session: product_data = request.session['product_data'] Thanks for all suggestions. -
A way to test methods with multiple database connections
How can I test a method (e.g. a serializer) which accesses two databases in Django? One is a default postgresql database and the other is a database with personal information. From the existent answers (for example Test isolation broken with multiple databases in Django. How to fix it?) I see that I can use TestCase, but the problem is that TestCase doesn't create separate databases in each test and uses existent ones that doesn't fit my needs. So actually I want to use APITestCase, but according to the docs it has no support for multiple database connections. Could you please help me to come up with any workaround? -
How to run a group of celery tasks? Apps aren't loaded yet
For example, I have a two tasks: a and b. I need to run them in parallel. I create a group of tasks and try run it. But I get error proj/app/tasks.py @app.tasks def a(): pass @app.tasks def b(): pass django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Application app is registered in INSTALLED_APPS and all migration complited proj/proj/__init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) proj/proj/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) from celery import group from app.tasks import a, b run_group = group(a.s(), b.s()) run_group() Traceback File "/home/m0nte-cr1st0/test_projects/oddsportal/oddsportal/__init__.py", line 5, in <module> from .celery import app as celery_app File "/home/m0nte-cr1st0/test_projects/oddsportal/oddsportal/celery.py", line 26, in <module> from app.tasks import a, b File "/home/m0nte-cr1st0/test_projects/oddsportal/app/tasks.py", line 14, in <module> from .models import Link, Prediction, PredictionBK File "/home/m0nte-cr1st0/test_projects/oddsportal/app/models.py", line 2, in <module> from django.contrib.auth.models import AbstractUser -
I changed codes in the running django project on the aws but changes are not reflecting
i have running django project on aws server with website hosted on same server i changed some coding and uploaded it to the server using sftp server but changes are not reflecting on the website and uploaded file is not working -
How to safely send large files using Django REST API?
I'm trying to automate a file transfer service where I use a simple bash script to upload video files from a remote client to a local server using a Django REST API when clients put a video in their local folder. Problem is, these videos are large and sometimes their internet connection isn't stable. What would be the best way to ensure my files are safely getting sent over and possibly resend the files if an error occurs? I know there are many ways to check if original and transferred files are similar and if internet connection is problematic but are there better more robust practices out there? -
A custom decorator to be called before every view using middleware
I have a custom decorator in a file and I need that every api call this decorator. I don't want to write @decorator_name before every view. I think this can be done using middleware but I am not sure how to do it/ I have tried middleware like this class DefaultAccountMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): return update_latest_account(view_func)(self, request, *view_args, **view_kwargs) This is the decorator: def update_latest_account(f): @wraps(f) def decorator(self, request, *args, **kwargs): user_id = request.user.id print('hi') user = User.objects.filter(id = user_id).first() if user is not None: account_id = request.META.get("HTTP_ACCOUNT_ID", None) user.latest_account_id = account_id user.save() return f(self, request, *args, **kwargs) return decorator -
Mezzanine project structure - virtual env in project folder?
So I'm attempting to deploy my mezzanine site, but I have run into some issues with settings not being installed properly on the digitalocean server. After checking some videos, like this one: https://www.youtube.com/watch?v=RIOUwi-1DCg I notice that he and others have their virtual env inside the project folder, next to the mezzanine project. Is this the correct way to structure the project? In my case, the virtual env is in a seperate Env folder with my other virtualenvs under my main directory on Windows 7. If someone could clarify what the structure should look like, and perhaps why, I would be grateful. -
How to configure wsgi for gunicorn?
Django version: 2.2.4 Python version: 3.6 When I try to run "gunicorn --bind 127.0.0.1:9000 config.wsgi:appname", I get following error: [2019-10-10 12:00:12 +0530] [9398] [INFO] Starting gunicorn 19.9.0 [2019-10-10 12:00:12 +0530] [9398] [INFO] Listening at: http://127.0.0.1:9000 (9398) [2019-10-10 12:00:12 +0530] [9398] [INFO] Using worker: sync [2019-10-10 12:00:12 +0530] [9401] [INFO] Booting worker with pid: 9401 Failed to find application object 'appname' in 'config.wsgi' [2019-10-10 12:00:12 +0530] [9401] [INFO] Worker exiting (pid: 9401) [2019-10-10 12:00:12 +0530] [9398] [INFO] Shutting down: Master [2019-10-10 12:00:12 +0530] [9398] [INFO] Reason: App failed to load. My WSGI file looks like this: import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "appname")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() I set up this Django project using cookiecutter Django. As I am new to this kindly let me know of any newbie mistakes. -
Gunicorn not forwarding reason phrase from Django Response
I am hosting my Django app with Gunicorn. What happen is as follow A sample response from Django would be as follow @require_http_methods(['POST']) def register(request): body = json.loads(request.body.decode('utf-8')) try: email = body['email'] except: return HttpResponse(status=400, reason="Email must be provided.") During the development, the Django app are run with command python manage.py runserver and have no issue at all with it. It always response with 400 Email must be provided However, in the production environment, it is hosted as follow Procfile web: gunicorn app.wsgi release: python manage.py migrate wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() Yet, when making a request, the response left as below. 400 What am I missing out to not letting the reason being forwarded properly? -
Django 'FloatField' is not callable
I keep getting these annoying highlights in my model field declarations When I hover mouse over it, it say 'FloatField' is no callable. This is happening for all field types except for CharField. The project runs fine and I'm able to migrate the model to DB but these highlights are annoying. Hoe can I get rid of them? Please advise. from django.db import models class ProjectModel(models.Model): name = models.CharField(max_length=50) project_id = models.IntegerField(blank=True) discipline_id = models.IntegerField(blank=True) demo_field = models.FloatField(verbose_name='flow(kg/s)', null=True, blank=True) def __str__(self): return str(self.id) -
"Album.singer" must be a "Singer" instance
Tracebck Please refer this link for trace back 2.Even I changed the lable name in forms.py it is taking default name I tried This code to make it fix but not solved.name = forms.CharField(label='Singer') forms.py class AlbumForm(forms.ModelForm): title = forms.CharField(max_length=50,label='Album title') class Meta: model=Album exclude = ['singer'] class SingerForm(forms.ModelForm): class Meta: model = Singer fields = ['name'] label = {'name':'Singer'} views.py class AlbumSinger(View): def get(self,request,pk=None): singer_form = SingerForm(instance=Singer()) album_form = AlbumForm(instance=Album()) context = { 'singer_form':singer_form, 'album_form':album_form } return render(request, 'album/multi_form.html', context) def post(self,request,pk=None): context = {} singer_form = SingerForm(request.POST,instance=Singer()) album_form = AlbumForm(request.POST,instance=Album()) if singer_form.is_valid and album_form.is_valid: singer_form.save() new_album = album_form.save(commit=False) new_album.singer = singer_form new_album.save() return HttpResponseRedirect('/album/') context = { 'singer_form' : singer_form, 'album_form' : album_form } return render(request, 'album/multi_form.html', context) -
How to have a redirection on a new tab when I click in a button in django?
Hi I have this line which is an instant redirection on a page, it’s HTML + Django link together <li><a href= "{{ OGC_SERVER.default.WEB_UI_LOCATION }}">GeoServer</a></li> My goal is to have a this page open on a new tab when I click on it, I tried to add a target= "_blank Like this <li><a href= "{{ OGC_SERVER.default.WEB_UI_LOCATION }}" target= "_blank">GeoServer</a></li> But it didn’t change anything. I would like to know if there’s a way to do this -
How can I fetch Apple Watch data into a Python project(Django) and any possibility to sync manually entered data into apple watch?
I need to Sync the manually entered data from the Python-Django project automatically with Apple Watch. Also, need to fetch data automatically from the apple watch. I am not sure the apple watch data can get from this API: GET https://api.appstoreconnect.apple.com/v1/devices/{id} -
python crash course chapter 18 why models, admin, urls not working
In python crash course chapter 18, I got the projects working, both learning_log and Pizzeria(page 412, exercise 18-4), I got both admin sites. But when I tried to run models.py, it says "ImproperlyConfigured", and admin.py it came out "ModuleNotFoundError: No module named 'learning_logs'". Also at the next section, the urls.py is not working, I finished to the page 416, couldn't get the Figure 18-3. I followed every steps in the book and went back double checked a few times, I also checked the update of the book from website, couldn't figure out why they are not working. please help! -
DJANGO AUTHENTICATION (SSO) WITH AZURE AD AND OAUTH2.0
I have built a Django application, and I am suppose to implement SSO for this app, because we have azure ad setup i am following this https://pypi.org/project/django-azure-ad-auth/ blog post to have sso enabled in my application. In the azure ad i have create the application, i have the client id tenant id, on configuring these parameters, the app doesnt work correctly. Please help. -
Login required decorator is not working Properly in the django?it will not redirect properly to the login page if user is not registered or logged in
So in my django frame work i made the login page other pages in the project.Now i want say if some other third party user try to run my any webpage on that specific time my website ask him/her for login before accessing my any website page,to resist that i used the login required decorator but when i logged in and copy my other webpage url and paste in the new window it will not show the login page just straight open that webpage in the new window.HOW DO I FIX IT????HELP ME OUT PLEASE....... URLS OF MY WEBPAGES:- path("loggedin/",views.loggedin,name="loggedin"), VIEW PAGE:- from django.contrib.auth.decorators import login_required This is my index page where user can register his/her self and after that they will login and go to the next page...... def index(request): return render(request,'userside/index.html') And this is the page which comes after the index(main dashboard) page @login_required(login_url='userside/loggedin') #@staff_member_required def mainpage(request): return render(request,"userside/mainpage.html") The other webpage of my project @login_required(login_url='/userside/loggedin') def criminalsinfo(request): crimins=Criminals.objects.all() return render(request,'userside/criminalsinfo.html',{'crimins':crimins}) -
forgot password with django and graphql?
I'm using django as the backed with graphql,im trying to implement forgot password,and change password,im using django-graphql-jwt for login ,everything's is works,but i didn't see any documentation about the forgot password with graphql. -
How to find the correct relationships between my tables?
I'm trying out a new django social media project which has User, Status and Comment. The relationship between them is such that, User has a relationship to Status, User has relationship to Comment and there also exists a relationship between Status and comment. So to achieve this I built four tables, i.e, User, Comment, Status and UCSModel. Where UCSModel is the table which has the foreign keys of the rest three tables. UCSModel is more like the relations table consisting of all ID's So here is my models.py from django.db import models class User(models.Model): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=200) password = models.CharField() def __str__(self): return self.username class Comment(models.Model): comment = models.CharField() def __str__(self): return self.comment class Status(models.Model): status = models.CharField() def __str__(self): return self.status class USCRelation(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE) status = models.ForeignKey(Status, null=True, on_delete=models.CASCADE) Being new to Django, I wanted to know if there is any better way of building relationships between tables. Especially when all the three tables are interrelated to each other like in my case above. -
Django Test case for deleting a post returns Https 200 instead of 302
I am writing a test case for a Posts app in my Django project. I have defined views for adding a new post, listing the posts, view details of the post, edit a post and delete a post. Adding a new post redirects the page to the detailed view of that page and deleting a post redirects the page to the list view. While writing tests for the same, I am getting https response code 302 for the new post as expected, but for the delete post, I am only getting an https response 200 while it should be 302. Adding necessary code below. Please feel free to ask any more code related to this if needed. Is there any concept that I am missing? Any lead is welcome. Thanks in advance. Test.py from django.test import TestCase from .models import Post from django.urls import reverse, reverse_lazy class PostTest(TestCase): def setUp(self): '''This function inserts dummy data into database to check during testing''' self.post = Post.objects.create(title='Test', content='abcd', author='testauthor@testing.test') def test_post_content(self): post_object = Post.objects.get(pk=1) expected_object_title = f'{post_object.title}' expected_object_content = f'{post_object.content}' expected_object_author = f'{post_object.author}' self.assertEqual(expected_object_title,'Test') self.assertEqual(expected_object_content, 'abcd') return self.assertEqual(expected_object_author, 'testauthor@testing.test') def test_post_list_view(self): response = self.client.get(reverse('lists')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Test') self.assertTemplateUsed(response, 'index.html') def test_post_details(self): response … -
django keep populating Form data in table
I am pretty new to django I need to keep adding form data in to the html table in same page. I can populate one time but i need to keep adding each time. refer below gif: sample data What I need is i need to add the data i have added second time to populate in the table in second row. please help me on this Form.py from django import forms class vm_provisioning_form(forms.Form): name = forms.CharField() email = forms.EmailField( ) views.py from django.shortcuts import render from django.http import HttpResponse from Forms import forms def vm_provisioning(request): form_vm_provisoning_info = forms.vm_provisioning_form() hidden_values = [] if request.method == 'POST': values = [] form_vm_provisoning_info = forms.vm_provisioning_form(request.POST) if form_vm_provisoning_info.is_valid(): # DO SOMETHING CODE print("VALIDATION SUCCESS!") name = form_vm_provisoning_info.cleaned_data['name'] email = form_vm_provisoning_info.cleaned_data['email'] values.append([name, email]) return render(request, 'Forms_template/vm_provisioning/vm_provisioning_form.html', {'forms': form_vm_provisoning_info,'data': values }) return render(request, 'Forms_template/vm_provisioning/vm_provisioning_form.html', {'forms': form_vm_provisoning_info}) form_vm_provisoning_info.html <!-- templates/vm_provisoning/form_vm_provisoning_info.html --> <!DOCTYPE html> {% extends 'Forms_template/base.html' %} {% block title %}Login in registration{% endblock %} {% block content %} <h1> Vm provisoning form</h1> <div class="container"> <h1>Please Fill details here!</h1> <form method="POST"> {{ forms.as_p }} {% csrf_token %} <section> <!-- hidden_data= forms.CharField(widget=forms.HiddenInput(), required=False) --> {% if data %} <table border="1"> <tr> <th>Name</th> <th>email</th> </tr> <!-- <p>{{ data }}</p> …