Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not getting time according to my timezone
i live in India and right now the time is 5:14 AM 8-10-2020 but using this time in my project i am getting a different time Oct. 7, 2020, 11:41 p.m. from django.utils.timezone import now timeStamp=models.DateTimeField(default=now) -
Serving up multiple protected media files on one page in Django
I have read about using "X-Sendfile" or "X-Accel-Redirect" on various server softwares to allow a page to be given access to a protected file, working alongside code like this in a view: response = render(request, 'mypage.html') response['X-Accel-Redirect'] = '/protected/foo.png' return response But I'm wondering how this would work (if at all possible) if you had multiple protected files: response['X-Accel-Redirect'] = '/protected/foo.png, /protected/bar.png' Would that work? Reference questions: SO 1, SO 2 -
no such file or directory "credentials.json"
I know other people have had this error, but my issue seems different from any I could find. I am trying to get data from a google sheet using questsheet.py, and posting that data to the caller. If I run my questsheet.py file by itself as a standalone, printing the data, it works fine. If I run it the way it's intended (this is using the evennia engine but it's basically all python with Django/twisted) I get this: FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json' Here is a pastebin of my code: https://pastebin.com/h2tYhXh5 Both my credentials.json file and my questsheet.py file are in the same folder. I've been learning python for a bit over six months. Still pretty new. -
Creating a LIVE ftp progressbar using ftp.apixml.net's js library
I want to create a live progress bar for an FTP upload using http://ftp.apixml.net/ 's FTP.JS. But the problem is when it is uploaded it does not shows complete. And not even Progress. from what I have read of progress bars It can be created with PHP,AJAX I read other answers but couldn't find one related with this js library. (It works little differently.!) // Script from http://ftp.apixml.net/ // Copyright 2017 http://ftp.apixml.net/, DO NOT REMOVE THIS COPYRIGHT NOTICE var Ftp = { createCORSRequest: function (method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; }, upload: function(token, files) { var file = files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.addEventListener("load", function() { var base64 = this.result; var xhr = Ftp.createCORSRequest('POST', "http://ftp.apixml.net/upload.aspx"); if (!xhr) { throw new … -
custom registration serializer IntegrityError: NOT NULL constraint failed
i'am trying to create a custom Registration serializer and add phoneNumber field ,i followed some examples in questions asked in here,so while adding a new user i get this error. here is my serializer what i did wrong ? class AccountSerializer(RegisterSerializer): phoneNumber=serializers.IntegerField(required=True) def validate_phoneNumber(self,phoneNumber): return phoneNumber def get_cleaned_data(self): return { 'phoneNumber': self.validated_data.get('phoneNumber', ''), 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.phoneNumber = self.cleaned_data.get('phoneNumber') user.save() return user -
DjangoDash plot showing in scrollable but short div
So I am new to DjangoDash and Plotly and trying to learn to build a simple dashboard. But the issue is when I am just following the second example from https://dash.plotly.com/basic-callbacks, the div is cropped and scrollable when displaying the whole page. This is the output of the page in local is As you can see, the div for displaying the plot is cut off and showing the next paragraph which I put as a test. The code in .py is exactly same as the second example, linked above. The only difference is instead of using dash.Dash(...), I am using DjangoDash(...) In html, my code is {% extends "base.html" %} {% load static %} {% block content %} <h2>Test</h2> <div class="container"> {%load plotly_dash%} {%plotly_app name="testPlot"%} </div> <div> <p>This is another test</p> </div> {% endblock %} It would really be appreciated if anyone can tell me the reason this is caused. Thank you in advance! -
Django - I'm getting "This field is required" error on UPDATING an object
When I try to use a form to edit an object that includes an image upload I get "This field is required". A similar form works fine to create the object, but when I retrieve the object and attempt to modify other fields, it fails on the image. #-------models.py: class Star(models.Model): firstname = models.CharField(max_length=32) lastname = models.CharField(max_length=32, blank=True) portrait = models.ImageField(upload_to='images/') #------views.py: class StarForm(forms.ModelForm): class Meta: model = Star fields = ["firstname", "lastname", "portrait"] def staredit(request, star_id): instance = Star.objects.get(pk=star_id) form = StarForm(request.POST or None, instance=instance) context = { "form": form, } return render(request, "stars/edit.html", context) def starchange(request): form = StarForm(request.POST, request.FILES) if form.is_valid(): newstar.save() context = { "message": "The form was posted", } return render(request, "stars/edit.html", context) else: context = { "message": form.errors, } return render(request, "stars/edit.html", context) #-----edit.html <form action="/starchange" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {{message}} Error message: portrait This field is required. -
Change default Django site on digitalocean to my app from the gunicorn file
I'm struggling with configuring my gunicorn file correctly, I would greatly appreciate any help. I setup a digitalocean server with django preloaded. I then added my domain and it's all working fine on the default django app. Now I have a django app i made and put on a private github repository that I want the server to run, I cloned this into the django project but when I go to edit the gunicorn file to point to that instead of the default app it fails to start presumably because I incorrectly edited the file. What is best practice for where to clone the repository to ? Should I clone the github repository into the django folder and delete the django_project folder that comes as default so I have django ├WebApp |├WebsiteName ||├__pycache__ ||├static ||├__init__.py ||├asgi.py ||├settings.py ||├urls.py ||└wsgi.py |├dashboard |├homepage |├users |├manage.py |└requirements.txt └gunicorn.socket What would I need to change the gunicorn in order to make this work correctly? my repository is called WebApp and the folder structure inside as follows WebsiteName ├__pycache__ ├static ├__init__.py ├asgi.py ├settings.py ├urls.py └wsgi.py dashboard homepage users manage.py requirements.txt Default digitalocean django app Folder structure django ├-django_project |├-django_project ||├-__init__.py ||├-__pycache__ ||├-settings.py ||├-settings.py.orig ||├-static ||├-urls.py … -
TemplateSyntaxError at /blog/second Invalid filter: 'get_val'
this is my function in views where I am separating comments and replies and changing reply into a dictionary def blogpost(request,slug): variable=Post.objects.filter(slug=slug).first() comments=Comments.objects.filter(post=variable,parent=None) replys=Comments.objects.filter(post=variable).exclude(parent=None) replyDict={} for reply in replys: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno]=[reply] else: replyDict[reply.parent.sno].append(reply) return render(request,"blog/blogpost.html",{'blog':variable,'comments':comments,'user':request.user,"replys":replyDict}) here I am displaying my replies {% for reply in replys|get_val:comment.sno %} {{reply}} {% endfor %} here i am parsing my dictionary to find a proper pair for the sno from django import template register=template.Library() @register.filter(name='get_val') def get_val(dict,key): return dict.get(key) -
Linking one table to each user in Django
I am working on a Django project where I need to link one table(model) to each user. Assume MyTable_1 maps to user_1 and so on. The primary key for MyTable will be a DateField which contains continuous dates from the time user signed-up. MyTable_1 for User_1 |-----------|----------|-------------|-----------------| | Date(PK) | food_ate | game_played | ran_today | |-----------|----------|-------------|-----------------| | 10/01/20 | rice | chess | Yes | |-----------|----------|-------------|-----------------| | 11/01/20 |sandwhich | tennis | No | |-----------|----------|-------------|-----------------| MyTable_2 for User_2 |-----------|----------|-------------|-----------------| | Date(PK) | food_ate | game_played | ran_today | |-----------|----------|-------------|-----------------| | 16/03/19 | pizza | rugby | Yes | |-----------|----------|-------------|-----------------| | 17/03/19 | pasta | football | Yes | |-----------|----------|-------------|-----------------| And so on for every new user created. User logs in those information in MyTable. How can I implement this? I am using PostgreSQL and have written custom User Model. -
Is there any way to pass an ID from URL to views.py using generic views?
I need to pass id from the url slug. I am using generic views. This is my code for urls.py: path('category/<int:pk>/details/', CategoryDetailView.as_view(), name='category-details'), and I need to pass the <int:pk> value into views.py, so I can filter my queryset with this id. My views.py code: class CategoryDetailView(DetailView): model = Category def get_context_data(self, *, object_list=Expense.objects.get_queryset(), **kwargs): queryset = object_list return super().get_context_data( summary_per_year_month = summary_per_year_month(queryset.filter(category_id= <int:pk> )) ) -
Django with Docker error 'SessionStore' object has no attribute '_session_cache'
I have an app in which I use Django authentication. When I use it locally with classic python manage.py runserver All works fine, but when I try to run it from docker I get a TypeError Exception Value: argument 1 must be str, not PosixPath Which is triggering from this piece of code in my template {% if user.is_authenticated %} And then I get this error, During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: Any idea what happening here? -
How to display a DIV during a period of time? Javascript
I have a queary in Django that shows all the posts of the current user Ordered by the starting date of the post. I want to display a DIV in the html template that says: “Will start soon” ,15 minutes before the Starting time of the post. Does anybody knows in Javascript how can I display that html div During the last 15 minutes before the post starts? I have two fields for making this script works: Start_date and start_time Thank you very much! Any idea is welcome! -
open edx mobile rest Api
oauth2 is not avilable in django admin how can I add oauth2 to the django admin I have tried with pip install django-oauth-toolkit and then added that to the common.py INSTALLED_APPS = ( ... 'oauth2_provider', ) but I got an error how can I fix it Thanks -
Django-Q and request.POST data
I have a budget app I am working on and using Django and Django-Q. I want to create a schedule to post automatically an expense based on a Django-Q schedule I create. The issue I am having is understanding the logic of using three positional arguments in my Djano-Q Schedule. The three positional arguments are request, budget_id and category_id. I want to post data to my add_expense view, which will create an initial expense based on the form data, and then create a Django-Q schedule to trigger an expense creation to run every month with that same data going forward. Can anybody help shed some light on this process? Thanks. -
TemplateDoesNotExist for detail.html but works for index.html (Django Tutorial Part 3)
I'm at my wit's end trying to fix this super strange error where one template works perfectly fine but the other doesn't??? I'm following the Django tutorial and when it comes to the part where I'm supposed to raise a 404 error the prompt tells me that detail.html does not exist at the given source even though it DOES. my views.py file: from django.shortcuts import render from django.http import Http404 from .models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index1.html', context) def detail(request, question_id): question = Question.objects.get(pk = question_id) return render(request, 'polls/detail.html', {'question': question}) the error: Internal Server Error: /polls/1/ Traceback (most recent call last): File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\Scripts\mysite\polls\views.py", line 15, in detail return render(request, 'polls/detail.html', {'question': question}) File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Admin\Appdata\Local\Programs\Python\Python38\Scripts\env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: polls/detail.html The following is what shows up on the webpage: Template-loader postmortem Django tried loading these templates, in this order: Using … -
Django Admin Million Data - Admin page takes too long to open
I have a million lines of data on my website. I am very waiting when I want to reach this page via admin. Maybe 40-50 seconds. I did the pagination 20, but nothing changed. Currently the default is 100. Its my admin code @admin.register(PollVote) class PollVoteAdmin(admin.ModelAdmin): list_display = ['title','referer','vote','ip', 'created_date'] ordering = ('-created_date',) search_fields = ['ip'] raw_id_fields = ['title'] What can I do to speed up this page in Admin? -
django.core.exceptions.ImproperlyConfigured: WSGI application 'DjBlog.wsgi.application' could not be loaded; Error importing module
I started a website building project With Django, but you ran into a problem with the WSGI server and but I haven't change any thing Please anyone who knows the answer, let me know this is the code that I wrote settings.py INSTALLED_APPS = [ # 'django.contrib.admin', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'mdeditor', 'haystack', 'blog', 'accounts', 'comments', 'oauth', 'servermanager', 'owntracks', 'compressor', # 'corsheader', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheader.middleware.CorsMiddleware', 'django.middleware.gzip.GZipMiddleware', 'corsheaders.middleware.CorsMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.http.ConditionalGetMiddleware', 'blog.middleware.OnlineMiddleware' ] ROOT_URLCONF = 'DjBlog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'blog.context_processors.seo_processor' ], }, }, ] WSGI_APPLICATION = 'DjBlog.wsgi.application' wsgi.py """ WSGI config for DjBlog project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') application = get_wsgi_application() the eror Traceback (most recent call last): File "D:\DjangoBlog\venv\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "D:\DjangoBlog\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Issue With Python and Django Time Zone Format
I recently added in my settings.py USE_TZ = True to get Celery working on my Django project and now in my other views that use the datetime.strptime command , it is adding the -04:00 since my time zone is America/Newyork. I don't need the time zone for this field. How do I remove the TimeZone from this ? Here is my code below. Thank you new_event.start = datetime.strptime(str(obj.start_date) ,"%Y-%m-%d %H:%M:%S") new_event.end = datetime.strptime(str(obj.end_date) ,"%Y-%m-%d %H:%M:%S") -
How to check if an admin inline form field has been changed and obtain those changed values?
I can check whether a field has changed in the save_model method by inspecting form.changed_data. With this I obtain a list of the fields names which have been changed. I need the same but with inline forms, I need to check if one inline form was changed and obtain those values. What I have Models class Case(TimeStampedModel, models.Model): pass class CaseFile(TimeStampedModel, models.Model): case = models.ForeignKey(to=Case, on_delete=models.CASCADE, verbose_name=_("Case")) Admins class CaseFileInlineAdmin(admin.TabularInline): model = CaseFile extra = 1 class CaseAdmin(admin.ModelAdmin): inlines = [CaseFileInlineAdmin] Problem I need to know when the user modified some input value from inline form CaseFileInlineAdmin inside CaseAdmin and obtain the changed values. -
ValueError at /posts/user/first-post-check/remove/ invalid literal for int() with base 10: ''
I have this function to remove photos from album, but getting this error invalid literal for int() with base 10: ''. The add to album is very much similar and it works fine, but the remove function is putting out this error. Can anyone help with this? Traceback: File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\danny\Study\Test\posts\views.py" in post 611. album = PhotoAlbum.objects.get(id=album_id) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in get 399. clone = self.filter(*args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in filter 892. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 910. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in add_q 1290. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in _add_q 1315. child_clause, needed_inner = self.build_filter( File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in build_filter 1251. condition = self.build_lookup(lookups, col, value) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in build_lookup 1116. lookup = lookup_class(lhs, rhs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\lookups.py" in __init__ 20. self.rhs = self.get_prep_lookup() File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup 70. return self.lhs.output_field.get_prep_value(self.rhs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py" in … -
How i can filter all the info open?
There are 2 models class info(models.Model): name = models.CharField() class state(models.Model): shopkeeper = models.ForeignKey(info) state = models.CharField(max_length=5,blank=False) date_register = models.DateTimeField(auto_now_add=True) There are the records on DB. How can I get all the info objects who last Status is Open. For example in image they will be only 85,84,81,82. The id 85 and 79 is not returned in the query because they have a last register on Close -
Django resync autoincrementing pk with restored database
I am working on a feature that requires me to use pg_restore to restore a database so I have enough historical data to do what I need to locally. The problem with this is when I create a new instance of any model, I end up with an IntegrityError as the pk is not unique. This has something to do with auto-incrementing behavior of pks when creating, but it doesn't seem like Django is using that last row to "resync" the next number so what I'm left with is Django trying to create a new instance with pk of 1361 despite there being 31k rows. How can I set the next value to what the next value actually should be, and is there a reliable way to do this after every restore? -
how can I use react router with 'django'
I wanna use react as frontend with django as backend I tried urlpatterns = [ path('api/',include('api.urls')), path('admin/', admin.site.urls), path('',include('frontend.urls')), ] frontend is the app contains react frontend app urls urlpatterns = [ path('/',index) ] def index(request): return render(request,'frontend/index.html') i wanna use index.html any other route -
Querying for Users with identical ManyToMany fields
This is more of a design question. My problem is that I wish to query for users that have identical selections in their manytomany fields. Is there a build-in method or combination of methods I can use to achieve this? Otherwise, I have a solution but it wouldn't be ideal. Thank you! My Solution- Upon the form submission, I was thinking on also storing a corresponding key which will be an integer created based on their selections. Then I can query to see if these keys are equal.