Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How I can get object with more than two parameter
I have a django model called ShopAccountInfo. The model has fields called login_id, shop, user(auth.user.model). And I want to use ShopAccountInfo.objects.get() by login_id, shop, user. I made a model instance has login_id="a", shop=0, user=me (Let's just call it 'me') So I called, ShopAccountInfo.objects.get(user=me, login_id="a", shop=0) But DoesNotExist error occured like, accounts.models.DoesNotExist: ShopAccountInfo matching query does not exist. But when I called it with filter like, ShopAccountInfo.objects.filter(user=me, login_id="a", shop=0).first() It returned correctly, I don't think the parameter is wrong, but I wondered get doesn't call with more than three, Because I tried ShopAccountInfo.objects.get(user=me, login_id="a", shop=0) and it returned instance well. Do you know about this? Thanks. -
Change url of an existing project. and redirect to the new url
Everybody. I have a project in django. With a url that was changed old url http://domain/knowledge/schulung/agile-testing-for-the-whole-team changed to: http://domain/trainer/schulung/agile-testing-for-the-whole-team the problem arises that there are users who already have url with /knowledge/. In django I want everyone who enters with the old url to be redirected to the new url. try this method: url(r'^knowledge/', RedirectView.as_view(url='/trainer/')), this leads me to: http://domain/trainer/ I need to go to : http://domain/trainer/schulung/agile-testing-for-the-whole-team Is there a method to do this? Thank you for reading. -
Django- Creating a dynamic path for file upload in models.py
I am having a model : class Attendance(models.Model): course = models.CharField(max_length=30) year = models.IntegerField(_('year'), choices=year_choices, default=current_year) sec = models.CharField(max_length=10) subject = models.CharField(max_length=30) file = models.FileField(upload_to=setFilePath, validators=[validate_file_extension]) and my setFilePath method goes like this : def setFilePath(instance, filename): return 'attendance-record/{course}/{year}/{sec}/{subject}/'.format(course=instance.course, year=instance.year, sec=instance.sec, subject=instance.subject) but I am not sure of this working ! Can anyone correct me, I want my file destination to be specific like this only and those fields are given in other column of tables I have searched how to do this and found some ways which includes using 1. two Save method 2. Postgres way Though I am using postgres I want the dir path to be same as this. -
Django - No module named 'myblog.wsgi' while using gunicorn
My project directory: yiling_blog ├── LICENSE ├── README.md ├── myblog │ ├── db.sqlite3 │ ├── manage.py │ ├── myblog │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── admin.py │ │ ├── admin_config.py │ │ ├── asgi.py │ │ ├── migrations │ │ ├── models.py │ │ ├── settings.py │ │ ├── static │ │ ├── urls.py │ │ ├── views.py │ │ └── wsgi.py │ ├── statics │ └── templates ├── requirements.txt └── venv The problem is, I can just use command /home/ubuntu/yiling_blog/venv/bin/gunicorn --bind 0.0.0.0:8000 myblog.wsgi:application after I run cd /home/ubuntu/yiling_blog/myblog, but it does not work in other directories. But I need to put this command in gunicorn.conf for supervisorctl to run in background, it does not support cd /home/ubuntu/yiling_blog/myblog|/home/ubuntu/yiling_blog/venv/bin/gunicorn --bind 0.0.0.0:8000 myblog.wsgi:application What should I do to solve this problem? Related files: wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblog.settings') application = get_wsgi_application() wsgi configuration in settings.py: WSGI_APPLICATION = 'myblog.wsgi.application' gunicorn.conf [program:gunicorn] directory=/homg/ubuntu/yiling_blog/myblog ## command will be change to /home/ubuntu/yiling_blog/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/yiling_blog/app.sock myblog.wsgi:application command=/home/ubuntu/yiling_blog/venv/bin/gunicorn --bind 0.0.0.0:8000 myblog.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn [unix_http_server] file=/home/ubuntu/yiling_blog/app.sock chmod=0766 -
Django Dynamic Inline Formset without any fields in the parent model not working
i am new to Django and i have been trying to create a dynamic inline form but ran into an issue. I am trying to create an inline form with user-customisable number of inline forms (models: DataSheetProperties) with foreign key to models: ProvisionalData. However, in the parent model (ProvisionalData), I do not want the user to fill in any fields, but for me to do the filling of the fields in the backend. Meaning, the user should only see the child model (DataSheetProperties) and be able to add or remove instances of that inline form as they see fit. The rendering of the form is okay, but when i press the 'save' button, I can't seem to save it and it does not even run through the form_valid() method in the views.py. I figured it was because there was no fields in the form of the parent model for the user to fill in, hence django does not recognise that the form was being submitted. Hence, I tried to add in a field into the forms.py (ProvisionalDataCreateForm) under the Div() section of the __init_ method. After adding the field, I was able to save the inline form successfully. However, I … -
Django Singleton File API
I'm attempting to create a sort of "cache" where an API uploads a file to the cache, and whenever a new file is uploaded it will replace the current file in the cache. Only one file will be held at a time, and I can clear the cache when needed. I'm not sure how to implement a singleton model that I upload to via an API. Any pointers appreciated. -
Django 1.11 middleware how to redirect properly
I have a difficulty with the middleware that I cannot get to sort out. The project I am working on is supposed to redirect all requests to visit any part of the site to add_company page if the user has not setup its company. To do this I am writing a custom middleware. The following code, however, does not work: class ProjectTrackingMiddleWare(MiddlewareMixin): ''' Note that this Middleware should come after all other middlewares in order to ''' def __init__(self, get_response=None): ''' One-time configuration called when the web-server starts ''' self.get_response = get_response def __call__(self, request): ''' To be executed on every request. ''' the_request = self.process_request(request) response = self.get_response(request) return response def process_request(self, request): the_user = request.user print ('the_user: ', the_user) ## CASE 1: User is not authenticated --> Redirect to login page if the_user. return HttpResponseRedirect(reverse('accounts:login')) # <-- This part works if the_user and not the_company: print ('the company: ', the_company) return HttpResponseRedirect(reverse('project_profile:add_company')) #<-- Does NOT redirect correctly if the_user.projects.all().count() > 1: request.project = the_user.projects.all().order_by('-date_modified')[0] return request The middleware does not redirect to add_company page. Instead, if as a logged-in user who has not setup a project try to visit a page, Django lets me visit the page: When … -
Django Sites Framework on Localhost Based on Port (8001, 8002, 8003)
I'm developing on localhost, assigning each port (8001, 8002, 8003) to correspond to each site (site1.com, site2.com, site3.com). How do I get the Django sites framework to recognize these ports as sites, or cause them to correspond? -
Why is using Type[T] with TypeVar not working correctly here?
I have the following type-annotated Django code: from typing import Optional, Type, TypeVar from django.db import models T = TypeVar("T", bound=models.Model) def get_obj_or_none(model: Type[T], model_id: int) -> Optional[T]: try: return model.objects.get(pk=model_id) except model.DoesNotExist: return None But when I run mypy on this, I get the error: error: "Type[M]" has no attribute "objects" error: "Type[M]" has no attribute "DoesNotExist" But if I then change my code to this and run mypy again, I get no errors: from typing import Optional, Type from django.db import models def get_obj_or_none(model: Type[models.Model], model_id: int) -> Optional[models.Model]: try: return model.objects.get(pk=model_id) except model.DoesNotExist: return None Why doesn't the first example work? I would really prefer to use it since the second example doesn't tie the return value in any way to the model parameter. -
Creating a whitelist with django-cors-headers
I am developing a django 2.0.1 application and i need to create a whitelist. So I am trying to install the python pakage django-cors-headers 3.2.1, and I following the instructions like https://pypi.org/project/django-cors-headers indicates, but the package seems like does not work, I can not get any behavior differences in my application. -
django 3.0 logout does not work , user is able to bypass login decorator even after logged out
i've been facing some sort of bug with the django 3.0 built in logout function. Here is some of my code: In my user app url: from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name= 'users/login.html'),name = 'login'), path('logout/', auth_views.LoginView.as_view(template_name= 'users/logout.html'),name = 'logout'), ] Basically that is all there is to it. Login works fine , however when i logout , it seems as though the login information is not truly deleted from the browser , or still residing within the browser cache. Therefore , even after clicking the logout button , i am still able to access my home page , which has a login decorator as such : @cache_control(no_cache=True, must_revalidate=True, no_store=True) @login_required def home(request): return render(request, 'rnd/rndhome.html') Is there any solution for this issue that im facing? It would help me a great load if you could provide some code snippets for me to understand whats going on , thank you! -
Python Django :TypeError: view must be a callable or a list/tuple in the case of include()
Please i am new to python and Django, am building a website and I ran into this code error while using Django built in login and logout view. I dont know if it has to do with my imports . Can someone please help me out? This is my url imports and codes from django.conf.urls import url, include from . import views from django.contrib.auth.views import LoginView, LogoutView urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^accounts/login/$', LoginView(), {'template_name': 'blog/login.html'}, name='login'), url(r'^accounts/logout/$', LogoutView(), {'template_name': 'cadmin/logout.html'}, name='logout'), url(r'^post/add/$', views.post_add, name='post_add'), url(r'^post/update/(?P<pk>[\d]+)/$', views.post_update, name='post_update'), ] My Views.py imports from django.shortcuts import render, redirect, get_object_or_404, reverse from blog.forms import PostForm from django.contrib import messages from blog.models import Post, Author, Category, Tag from django.contrib.auth import views as auth_views And here is are the functions i defined in my views.py def home(request): if not request.user.is_authenticated(): return redirect('login') return render(request, 'cadmin/admin_page.html') def login(request, **kwargs): if request.user.is_authenticated: return redirect('/cadmin/') else: return auth_views.login(request, **kwargs)``` The output throws an error that view must be callable File "C:\Users\LENOVO\Desktop\TGPB\cadmin\urls.py", line 7, in <module> url(r'^accounts/login/$', LoginView(), {'template_name': 'blog/login.html'}, name='login'), File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\conf\urls\__init__.py", line 13, in url return re_path(regex, view, kwargs, name) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\urls\conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple … -
Django errors when running via Virtual Environment: Exception in thread django-main-thread:
Django errors when running via Virtual Environment: Exception in thread Django-main-thread. I am doing this in Venv and not sure where I am going wrong? Can someone please help? Initially, I ran into this issue when I accidentally upgraded Django when PyCharm prompted it but after that, I created a Venv and moved my files over but the error seems to be persistent. (venv) users-MacBook-Pro:myproject $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/Documents/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Users/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Users/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/venv/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): File "/Users/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/Users/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File … -
Related Field got invalid lookup: icontains in django adminsite
I am trying to search the name of the students in Django admin site, but everytime i search the name of the student i get this error Related Field got invalid lookup: icontains this is my admin.py @admin.register(StudentPaymentSchedules) class StudentPaymentSchedulesAdmin(admin.ModelAdmin): list_display = ('Fullname','Grade_Level','Payment_Schedule','Amount','Student_Payment_Date','Paid_Amount','Balance','Remarks','Status',) ordering = ('pk','Students_Enrollment_Records__Education_Levels') search_fields = ('Students_Enrollment_Records__Student_Users',) list_filter = ('Students_Enrollment_Records__Education_Levels',) def Fullname(self, obj): return obj.Students_Enrollment_Records.Student_Users def Grade_Level(self, obj): return obj.Students_Enrollment_Records.Education_Levels this is my models.py class StudentPaymentSchedules(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Students_Enrollment_Records=models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Payment_Schedule = models.DateField(null=True, blank=True) Amount = models.FloatField(null=True,blank=True) Student_Payment_Date = models.DateField(null=True, blank=True) Paid_Amount = models.FloatField(null=True,blank=True) Balance = models.FloatField(null=True,blank=True) Remarks=models.TextField(max_length=500,null=True,blank=True) Status=models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) Student_Types = models.ForeignKey(student_type, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Remarks = models.TextField(max_length=500,null=True,blank=True) -
Count numer of elements in a set of objects
I have a question about getting the count of objects after following 2 foreign key relationships, as an annotation of a QuerySet. Let's say I have the following models: class TaskList(models.Model): name = models.CharField(max_length=64) class Batch(models.Model): task_list = models.ForeignKey(TaskList) length = models.IntegerField() done = models.BooleanField(default=False) class Task(models.Model): batch = models.ForeignKey(Batch) task_name = models.CharField(max_length=32) # some more fields.. Batch has a set of Tasks. An object Task is created when the corresponding task is done. I can get the number of Questions of every poll by doing this: TaskList.objects.all().annotate(total_tasks=Sum('batch_set__length')) How can I get the number of Tasks a TaskList has? I tried doing TaskList.objects.all().annotate(total_tasks=Count('batch_set__task_set')) but it did not work. There doesn't seem to be anything in the documentation on annotations about following a foreign key relationship more than once, or about a way to annotate the batches. -
How to handle form errors in Django when posting to different view?
Normally, it seems, Django developers create forms where the GET and POST request is handled by the same view. If we POST to a different view however how does one return the errors to the same URL that made the request? Googling around I found surprisingly little on this. On Stackoverflow in fact I found only a single comment (5th down) in this answer which was well voted for asking the same question but receiving no answer - Proper way to handle multiple forms on one page in Django. I'd have thought this would be done all over the web with the django web framework but I'm beginning to question whether the community just considers it a bad idea for whatever reason. -
Django Connection reset by peer 0.0.0.0:8000
System check identified no issues (0 silenced). January 30, 2020 - 23:18:31 Django version 3.0.2, using settings 'GroverLeagues.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [30/Jan/2020 23:18:36] "GET / HTTP/1.1" 302 0 ---------------------------------------- Exception happened during processing of request from ('72.23.224.222', 53076) Traceback (most recent call last): File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/home/lakepry/groverenv/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/home/lakepry/groverenv/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer I'm deploying my first django application following Digitalocean's tutorial on deploying with postgresql database and it won't let me access my webpage in a browser. In the browser it says, "This site can't be reached". Port 8000 is allowed through the firewall as well. Any ideas on what to do? -
Django - How to load a specific image on a specific facebook share button
I am trying to implement a facebook share button in an online store made with Django. The goal is to share a post of the product with the respective image. I am currently using the meta tag like so: base.html <head> ... <meta property="og:type" content="website" /> <meta property="og:url" content="https://www.naturalessencial.com/" /> <meta property="og:title" content="--------" /> <meta property="og:description" content="------" /> <meta property="fb:app_id" content="-------" /> {% block extrahead %}{% endblock %} <meta property="og:image" content="https://www.naturalessencial.com/static/img/logo_share.png"/> ... </head> and in my product detail page I extend the base.html file and so I have the following: product_detail.html {% block extrahead %} {% with image=product.primary_image %} {% oscar_thumbnail image.original "660x600" upscale=False as thumb %} <meta property="og:image" content="https://www.naturalessencial.com{{ thumb.url }}"/> {% endwith %} {% endblock %} so after the product detail page is rendered I have the following: Product_detail.html (Rendered) <head> ... <meta property="og:type" content="website" /> <meta property="og:url" content="https://www.naturalessencial.com/" /> <meta property="og:title" content="--------" /> <meta property="og:description" content="------" /> <meta property="fb:app_id" content="-------" /> <meta property="og:image" content="https://www.naturalessencial.com/image_path"/> <meta property="og:image" content="https://www.naturalessencial.com/static/img/logo_share.png"/> ... </head> <body> ... <script> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="fb-share-button" data-href="https://www.naturalessencial.com/{{product.url }}" data-layout="button" data-size="large"> </div> ... … -
How to strip quotes around Django generated html?
I'm trying to display a hyperlink in a form based on a value taken from a database. As far as I can tell Django doesn't support this natively, so instead I'm trying to generate the html manually. In the modelform I'm overriding the init method: def __init__(self, *args, **kwargs): super(ChangeForm, self).__init__(*args, **kwargs) self.fields['hyper_change'] = forms.CharField(max_length=480) self.fields['hyper_change'].initial = f'<a href="https://website.com?sys_id={str(self.instance.change_id)}">{str(self.instance.change_id)}</a>' The value is read in the template: {{ change_formset.0.hyper_change.value }} The problem is that the generated html is quoted, so the complete string is displayed. Is there a way to strip the generated quotes? I've tried using a custom filter to replace the quotes, but that didn't work sadly. -
Join and aggregate Django models
I'm having the following model structure in Django. class Group(Model): name = CharField() class Category(Model): name = CharField() class User(Model): name = CharField() group = ForeignKey(Group) class Answer(Model): user = ForeignKey(User) category = ForeignKey(Category) answer = BooleanField() From this data, I want to count how many positive answers I have for each category and for each group. A bit like this: results = {} for category in Category.objects.all(): results[category.name] = Group.objects.annotate( total=Count( 'user__answer', filter=Q( user__answer__answer=True, user__answer__category=category ) ) ) But is there a better way to do this? Can this be done with a single query? -
What's the difference in "MaxRequestsPerChild" (Apache/Prefork) and "maximum-request" WSGI?
MaxRequestsPerChild - every x connections, process will be recreated maximum-request - every x connections, process will be recreated What would be the difference using the two? MaxRequestsPerChild would it be for apache connections and maximum-request for apache destined for django? Sorry for my english :)) -
Custom page permission
In Django CMS how can you add a custom permission that runs for a specific page? I know there are page permission but haven't found much about overriding them / giving custom field based permissions. Essentially, I only want the field viewable if a model field for the owning user is filled out. Ideally, a redirect instead of an error would be returned. Django CMS docs are horrible. -
Django 3.0 (templates) upload photo -> send to external API -> get response -> redirect to prefilled form
I have a view in which a user can upload a photo. After submitting it, the photo goes to the external API where it's being OCRed and what come back are values with which I would like to prefill forms that are on another view. The number of forms depends on how many results the OCR API returned. What's problematic is that I don't know any good way how to send those values returned by OCR API from one view to another. I feel like I am missing some django function that would do that for me. When I google it, the message framework pops up which doesn't seem proper in this situation. -
Heroku Django App + Azure PostgreSQL DB - slow connections
I have an app hosted on heroku and moved my DB to azure recently, because of the way SSL is handled by heroku postgres. Even though my new Azure Postgres is plenty more potent than the former heroku:postgres equivalent, I am encountering severe slow downs. I have setup PGBouncer to use connection pooling but I am still not seeing the the performance improve. Any clues as to what I could try? -
How can i create a backdoor entry for a website?
I have tried creating a route called '/admin' but i understand that using a route to handle backdoor entry that web admin can use to access 'administrator dashboard' in my case is not a good practice . Custom routes i.e '/admin' or '/some_route' can handle the entry to web admin dashboards but how do i ensure it cannot be publicly accessed and easily guessed . For instance, it's almost impossible to know the backdoor route to popular websites i.e stack overflow, twitter and many websites.