Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Problem in month-wise aggregation for more than twelve months
This is my model: class Purchase(models.Model): date = models.DateField(default=datetime.date.today,blank=False, null=True) total_purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True) I want to perform monthly wise aggregation of total_purchase field in the above model. I tried the below: import datetime import calendar import collections import dateutil start_date = datetime.date(2018, 4, 1) end_date = datetime.date(2019, 3, 31) results = collections.OrderedDict() result = Purchase.objects.filter(date__gte=start_date, date__lt=end_date).annotate(real_total = Case(When(Total_Purchase__isnull=True, then=0),default=F('Total_Purchase'))) date_cursor = start_date z = 0 while date_cursor < end_date: month_partial_total = result.filter(date__month=date_cursor.month).aggregate(partial_total=Sum('real_total'))['partial_total'] # results[date_cursor.month] = month_partial_total if month_partial_total == None: month_partial_total = int(0) e = month_partial_total else: e = month_partial_total z = z + e results[date_cursor.month] = z date_cursor += dateutil.relativedelta.relativedelta(months=1) return results But the result is displaying only for twelve months if I select the daterange for more than twelve months Its calculating the total for the same months together. ** For example ** I want to perform the below: April 2800 May 2800 June 2800 July 2800 August 7800 #(2800 + 5000) September 7800 October 13800 #(7800 + 6000) November 13800 December 13800 january 14000 (13800+200) february 14000 march 15000 (14000+1000) April 18000 (15000+3000) may 20000 (18000 + 2000) For months selected April to November in the same year. If I choose for months greater then 12 … -
AttributeError: module 'django.contrib.auth.views' has no attribute 'add_comment_to_post'
I completed all the steps from the following website: https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/ everything seems correct, and for some reason the server cannot be run on cmd. Below is the error displayed: 32\Scripts\mysite\urls.py", line 26, in <module> path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), AttributeError: module 'django.contrib.auth.views' has no attribute 'add_comment_to_post' Editing urls.py, views.py, forms.py was done several times, and also comment model was added to the database with: "python manage.py makemigrations blog", and "python manage.py migrate blog" urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('accounts/login/', views.LoginView.as_view(), name='login'), path('accounts/logout/', views.LogoutView.as_view(next_page='/'), name='logout'), path('', include('blog.urls')), path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'), views.py: from django.shortcuts import render from django.utils import timezone from .models import Post, Comment from .forms import PostForm, CommentForm from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.contrib.auth.decorators import login_required def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) @login_required def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) … -
Point in the right direction for login page
I started on my first xcode project recently and I was hoping for some help with my login page. When looking online I have solutions that use firebase but in my case I would like to pull from my webapp (django). I understand that I have to set up a route in my django app but how should I go about requesting a session? Thank you ahead of time. -
How do I display an image from numpy array in django
Suppose I have constructed an image using numpy. img = np.random.randint(low=0, high=255, shape=(100, 100), dtype='uint8') And I have a view function in view.py def index(request): template = loader.get_template('visionit/index.html') context = {'img': img } return render(request, 'visionit/index.html', context) How do I show it in the webpage? N.B. There is a way, where I can save img with as a jpg file, get the url of the file and use it to display on the webpage. But I think there is a better solution to show image directly from memory without saving it to disk. -
CSS doesn't load properly in django project
When I runserver the project doesn't load my css which is stored: homepage/static/style.css where homepage is a directory in my main python project folder. I've followed every step in https://docs.djangoproject.com/en/2.2/howto/static-files/ but it doens't load. So I tried to run in console: python manage.py collectstatic , reload server page and finally css is displayed properly. Good, problem solved? Nope. the css I had was just for testing (bg-color: blue) when I changed the css file writing the actual css I want displayed nothing changed, the background is still blue. I wrote the new css in the file that was properly displayed. Still display bg-color: blue; I tried to run collectstatic again, no change. Reloaded server, opened a new one, no change. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} <link href="{% static 'style.css' %}" rel="stylesheet" type="text/css" > /* homepage/static/style.css is the relative path, with this path no css is loaded, with 'style.css' it loads the test version of css (bg-color: blue;)*/ <title>Homepage</title> </head> <body> {% block content_h %} {% endblock %} /*the block is displayed fine */ </body> </html> I've made a new css file called style1.css with … -
How to create an object with two forms in two views which fills different fields?
I have two views in my app (each with a ModelForm) and I want to create an object with the values returned by the two forms. How can I proceed ? views.py : def index(request): derog_indiv_form = DerogationIndividuForm(request.POST or None) if derog_indiv_form.is_valid(): # Some code return render(request, 'derog_bv/index.html', {'derog_indiv_form':derog_indiv_form}) def raison(request): derog_raison_form = DerogationRaisonForm(request.POST or None) if derog_raison_form.is_valid(): # Some code return render(request, 'derog_bv/raison.html', {'derog_raison_form':derog_raison_form}) forms.py : class DerogationIndividuForm(ModelForm): class Meta: model = Derogation fields = [ 'individu' ] labels = { 'individu': ('Individu :') } class DerogationRaisonForm(ModelForm): class Meta: model = Derogation fields = [ 'type_derogation' , 'createur' ] -
Error when trying to inspectdb legacy database with existing collection in mongodb populated with data
Error: # Unable to inspect table 'reportcollection' # The error was: 'NoneType' object is not subscriptable using python manage.py inspect I see other tables including default tables for user and so on, but in the end I get this error, I already took a look at https://docs.djangoproject.com/en/2.2/howto/legacy-databases/ -
How to turn on and off a choice field
I got a code where a choice field is going to start locked, as the code below says, but i need to add some kind of lock so when I need it can be turned on, change the settings and then turn off again by pressing the same lock. I got already the lock in JS on the HTML but can't figure it out to call this widget. ''' unit = forms.ChoiceField(choices=UNITS, required=False, widget=forms.Select(attrs={'disabled':'disabled'})) ''' -
"OperationalError: database is locked" when deploying site to Azure
I have built a django website and a part of it is Microsoft authentication link. When I upload the site to azure cloud and click on the "log in" link, I recieve the following error: OperationalError at /login database is locked Request Method: GET Request URL: http://bhkshield.azurewebsites.net/login Django Version: 2.2.2 Exception Type: OperationalError Exception Value: database is locked Exception Location: /home/site/wwwroot/antenv3.6/lib/python3.6/site-packages/django/db/backends/base/base.py in _commit, line 240 Python Executable: /usr/local/bin/python Python Version: 3.6.7 Python Path: ['/usr/local/bin', '/home/site/wwwroot', '/home/site/wwwroot/antenv3.6/lib/python3.6/site-packages', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Fri, 14 Jun 2019 13:19:22 +0000 I am using sqlite3 (setting.py code piece): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I don't understand why I get this error because I don't insert or commit anything to the database. My website consists only of a one page that has a sign in link (4 views: home, contex intialize, login and callback). That's it. Has anyone encountered this type of error and can help? If you need me to provide more files' content, let me know which files and I will. -
How to display Django json object in Datatables?
I am using Django, Using the DataTables plugin I want "reference table " to display in the customer column, "id0" and id1" etc. to display in the Id column and "code1" and "cdeo2" in the Kod column. I can do this with a for loop in my HTML, but this messes up my DataTable formatting and removes the search box and prev/next buttons from the table. How can I get these value to populate the cells in the data table? I want to display all_data with Datatables in Django. But i get error. Could you please share all code or Could you please solve the problem in My project ? Python Code : Reference.py Urls.py from django.urls import path, include from Referans.Views import guncelleView,silView,detayView,olusturView,referansView from django.conf.urls.i18n import i18n_patterns import uuid app_name ="Referans" urlpatterns = [ path('', referansView.referans_listele , name="referans"), path('test/json/', referansView.test_json, name='test_json'),] -
When implementing my api, I'd like for it be view able in xml format. Not just JSON
I'm creating a web api for the polling app Django gives us as practice for myself. I was able to go pretty far, but I am stuck with wanting to give an option for formatting with xml. I tried using 'DEFAULT_PARSER' and 'DEFAULT_RENDER' and it didn't really workout the way I wanted it to. I just want to give an option like I have for JSON on there.\ This is my api/views class from rest_framework import generics from . serializers import QuestionSerializer, ChoiceSerializer from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter, SearchFilter from polls.models import Choice, Question class QuestionList(generics.ListAPIView): serializer_class = QuestionSerializer queryset = Question.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) filter_fields = {'id': ['gte', 'lte', 'exact'], 'pub_date': ['gte', 'lte']} ordering_fields = ('id', 'question_text', 'pub_date') search_fields = ('pub_date', 'question_text') class ChoiceList(generics.ListAPIView): serializer_class = ChoiceSerializer queryset = Choice.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) # trying to do greater than or less than filter fields stuff filter_fields = {'id': ['gte', 'lte', 'exact'], 'votes': ['gte', 'lte', 'exact']} ordering_fields = ('id', 'votes', 'choice_text', 'question',) search_fields = ('choice_text', 'question') this is api/serializers class from rest_framework import routers, serializers, viewsets from polls.models import Question, Choice # serializer is the way you can see the list of info … -
How to replace %20 with - in django urls
I have a url which contains %20. I want to replace it with - with the help of regex I already tried replace method url(r'^timeanalysis/(?P<name>[\w|\W]+)'.replace('%20','-'), timeseries.timeanalysis, name='timeanalysis') I don't want to change my database. -
How to say "is not equal" in test ? Assert is not equal
I am testing my code in django and i have a case where i want to test if it is NOT equal. How can i do that ? i am using the doc from django here : https://docs.djangoproject.com/fr/2.2/topics/testing/tools/ Another example in react we have ".not" to say not equal. I tried with '.not' or with assertNotEqual class SimpleTest(TestCase): def test_details(self): response = self.client.get('/customer/details/') self.assertEqual(response.status_code, 200).not() class SimpleTest(TestCase): def test_details(self): response = self.client.get('/customer/details/') self.assertNotEqual(response.status_code, 200) I expected to have one condition who test the no egality between my variable and my status code. Thank for your help. -
How to send a context in a view based on class
i am trying to send a context to a view bassed on class as i said in the title. This is my class view: class RegisterUser(CreateView): templates = Templates.objects.get(isSelected=True) model= settings.AUTH_USER_MODEL form_class = RegisterForm template_name = "register/register.html" success_url = reverse_lazy('login') I want to send 'templates' to a context and then to the html. But i dont know how to do it. Anyone can help me? thank you! -
Django: Multiply inside query set
I wonder if the way I calculate quantity * price_grossis the right way to do it. Or is there a better way to multiply these values inside the Ticket.objects. query set? event = Event.objects.get(pk=4) test = Ticket.objects.filter(event=event).values('quantity', 'price_gross') result = 0 for x in test: result += x['quantity']*x['price_gross'] print(result) -
Django- Nginx/Gunicorn timeout on POST request
I'm setting up an Ubuntu EC2 instance by following this droplet tutorial. Everything seems to be working fine on my local development machine but I am getting timeout errors(502,504) on my EC2 instance. I checked my gunicorn logs and there was a [CRITICAL] WORKED TIMEOUT message so I increased the "timeout" parameter for gunicorn to 300 and set the proxy_connect_timeout to 75s and proxy_read_timeout to 300s on my site's nginx config even though the process should have taken much less time than that. I think the error is not with the process taking the time but some misconfiguration in my nginx or gunicorn config. GET requests that retrieve data from the DB seem to be working fine but POST requests that write to the DB don't seem to work. Here are my config and log files Gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/standalone_ntp_backend ExecStart=/home/ubuntu/standalone_ntp_backend/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/standalone_ntp_backend/standalone_ntp_backend.sock standalone_ntp_backend.wsgi:application --timeout 300 [Install] WantedBy=multi-user.target /etc/nginx/sites-available/www.example.com.conf server { listen 80; listen [::]:80; server_name example.com www.example.com; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; # include proxy_params; proxy_connect_timeout 75s; proxy_read_timeout 300s; proxy_pass http://unix:/home/ubuntu/standalone_ntp_backend/standalone_ntp_backend.sock; } client_max_body_size 50m; } /var/log/nginx/error.log 2019/06/14 12:10:40 [error] 1062#1062: *3 upstream timed out … -
How to resolve this, without providing any default value?
When I am trying to run python3 manage.py makemigrations it shows : You are trying to add a non-nullable field 'topic_id' to journey_template without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: enter code here from django.db import models class Topic_Table(models.Model): topic_id=models.IntegerField(primary_key=True) topic_name = models.CharField(max_length=100, blank=True) weightage = models.CharField(max_length=15, blank=True) grade = models.IntegerField( null=True) subject = models.CharField(max_length=100, blank=True) sequence = models.IntegerField(null=True) month = models.CharField(max_length=15, blank=True) class Journey_template(models.Model): student_id = models.IntegerField(default=1) topic_id = models.ForeignKey('Topic_Table',on_delete=models.CASCADE) subtopic_id = models.IntegerField() journey_template_key = models.IntegerField(primary_key=True) How would I fix this? -
Django -> django.db.backends DEBUG enabled keep printing (%.3f) %s; args=%s
When I set the logger level to DEBUG on django.db.backends it keeps printing this message [14/Jun/2019 18:47:53] [DEBUG] [django.db.backends -> utils.py -> execute -> 90 -> (%.3f) %s; args=%s] [14/Jun/2019 18:47:53] [DEBUG] [django.db.backends -> utils.py -> execute -> 90 -> (%.3f) %s; args=%s] [14/Jun/2019 18:47:53] [DEBUG] [django.db.backends -> utils.py -> execute -> 90 -> (%.3f) %s; args=%s] [14/Jun/2019 18:47:53] [DEBUG] [django.db.backends -> utils.py -> execute -> 90 -> (%.3f) %s; args=%s] [14/Jun/2019 18:47:53] [DEBUG] [django.db.backends -> utils.py -> execute -> 90 -> (%.3f) %s; args=%s] My logger format is 'format' : "[%(asctime)s] [%(levelname)s] [%(name)s -> %(filename)s -> %(funcName)s -> %(lineno)s -> %(msg)s]", Python version 3.7 Django version 1.11.20 Any idea what this is about ? -
How to add a custom field to Django user module?
This is the image of the default Django User fields. This image has the default Django user fields such as username, email address, first name and last name. I want to add a custom field such as a phone number to the existing fields. How can I achieve this? Thank you! -
django python manage.py runserver throws errors
I am trying to create my first project using django in a virtual environment. When I run python manage.py runserver, I get the below errors. Windows 7 (64 bit) `(myDjangooEnv) C:\Users\sbhamidi\Desktop\AtomProjects\My_Django_Stuff\first_project> (myDjangoEnv) C:\Users\sbhamidi\Desktop\AtomProjects\My_Django_Stuff\first_project>python Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. quit() (myDjangoEnv) C:\Users\sbhamidi\Desktop\AtomProjects\My_Django_Stuff\first_project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\sbhamidi\AppData\Local\conda\conda\envs\myDjangoEnv\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\sbhamidi\AppData\Local\conda\conda\envs\myDjangoEnv\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) ImportError: DLL load failed: The specified procedure could not be found. ` -
Data migrations of files object (FieldFile) in Django
I'm having trouble in data migrating tables that contains FieldFile object. I use a special method to create ObjectFile. def create_object_file(file): return = ObjectFile.objects.create( name=name, content_type=file.content_type, extension=extension, uploaded_by=object_user, md5sum=file.md5sum, file='' ) File is a FieldFile. I need to register it without a file since I don't have the files yet. -
Django model based form display ForeignKey as checkboxes
I want to display Track model names (that is ForeignKey() field in Playlist model) as list of checkboxes in template. I know what is "CheckboxSelectMultiple", but I dont know how to implement it in my situation. Here is my "Playlist" model: class Playlist(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension]) tracks = models.ManyToManyField(Track) favourite = models.BooleanField(default=False) def __str__(self): return self.title Here is my "Track" model: class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension]) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension]) favourite = models.BooleanField(default=False) def __str__(self): return self.title Here is form: class AddPlaylist(forms.ModelForm): class Meta: model = models.Playlist fields = ['title', 'description', 'tracks', 'miniature', 'favourite'] widgets = { 'description': Textarea(attrs={'cols': 30, 'rows': 10}), } -
How to install django-CMS 3.6 with python3 & django2 using djangoCMS-installer?
As per this: https://github.com/nephila/djangocms-installer , djangocms-installer supports django CMS 3.6 and Django 2.1 but after running djangocms -f -p . mysite it sets up django CMS 3.6 with Django 1.11 not Django 2.1, is there any way to make it happen using djangocms-installer? -
Cant able to Deploy django app in AWS cloud
I'm facing some issues when I am trying to deploy my Django App in AWS. I have 100$ credit on my aws credit but its showing some credit issues also. -
Django calling stored procedure, transaction not committing or failing to execute
I have this code that is running based on a django manage command. Its helping with the loading of a bunch of data using temp tables, and pandas library def MergeAce(table=None,user=1,db_instance=None): if db_instance: db = db_instance else: return False with connections[db].cursor() as cursor: result = cursor.execute(f"spMergeAce {user} , '{table}'") cursor.commit() return result I know I am not calling the parameters correctly, and currently callproc does not work with pyobdc. However, It seems like some of the code runs but some of it doesn't. This is a sample of the procedure its calling. Please note it using a merge statement. -- ============================================= -- Author: <Pickle,Travis> -- Create date: <June 13 2019> -- Description: <Create and update ace from temp table> -- ============================================= ALTER PROCEDURE [dbo].[spMergeAce] -- Add the parameters for the stored procedure here @user int = 1, @table varchar(50) AS BEGIN SET NOCOUNT ON; declare @query nvarchar(max) = '' -- ,@user int = 1, @table varchar(50) = 'cat' set @query = N' with cte as( SELECT aclid, hash, ConfigLine, RN = ROW_NUMBER() OVER(PARTITION BY aclid, hash, ConfigLine ORDER BY aclid, hash, ConfigLine) FROM [dbo].['+ @table + '] new) delete from cte where RN > 1; MERGE [dbo].[ACE] AS TARGET USING …