Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WSGIRequest' object has no attribute 'user [duplicate]
This question is an exact duplicate of: Error when trying to use LoginRequiredMiddleware in Django 1 answer Terminal shows - Performing system checks... System check identified no issues (0 silenced). May 14, 2018 - 05:49:00 Django version 1.9, using settings 'tutorial.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /accounts/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view if test_func(request.user): AttributeError: 'WSGIRequest' object has no attribute 'user' I got above error when I go to my url -
Python Django - what does os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'folder.settings') do?
I am taking an online Django class now, and I don't understand some of the configuration codes. My instructor says that the following code is required in a python code that populates my database. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProTwo.settings') import django django.setup() I don't understand what these codes are doing at all, except that the second argument in setdefault() is referring to my app's settings.py file. What is DJANGO_SETTINGS_MODULE? What does it do? Why is it passed in as an arg in setdefault()? And what does django.setup() do? What does it change? Please understand that I'm pretty much a novice and can't understand many jargons. -
How to store credentials Gmail API
I've connected Gmail API to Django project. I have a problem with storing credentials of every user. What is the most correct way to store them, so every users can log in? Without storing it just creates one file for one user and that's all. Should I create a database? This is my "quickstart" file from Google: from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from django.contrib.auth.models import User # user = User # storage = (CredentialsModel, 'id', user, 'credential') As you see I tried it here but it didn't go well # credential = storage # # storage.__add__(credential) # Setup the Gmail API SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) def go(): # Call the Gmail API results = service.users().labels().list(userId='me').execute() labels = results.get('labels', []) # if not labels: # print('No labels found.') # else: # print('Labels:') # for label in labels: # print(label['name']) pass -
django-login-required-middleware WSGI error
iam trying to apply this way to my project : http://onecreativeblog.com/post/59051248/django-login-required-middleware here my settings.py ... LOGIN_URL = '/admin/login/' LOGIN_EXEMPT_URLS = ( ) MIDDLEWARE = [ ... 'project.middleware.LoginRequiredMiddleware', ] ... and here my middleware.py from django.http import HttpResponseRedirect from django.conf import settings from re import compile EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: """ Middleware that requires a user to be authenticated to view any page other than LOGIN_URL. Exemptions to this requirement can optionally be specified in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which you can copy from your urls.py). Requires authentication middleware and template context processors to be loaded. You'll get an error if they aren't. """ def process_request(self, request): assert hasattr(request, 'user'), "The Login Required middleware\ requires authentication middleware to be installed. Edit your\ MIDDLEWARE_CLASSES setting to insert\ 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\ work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\ 'django.core.context_processors.auth'." if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(settings.LOGIN_URL) I put that middleware.py on my project root. project |__db.sqlite3 |__manage.py |__middleware.py |__app |___admin.py |___views.py |___models.py but got an error. django.core.exceptions.ImproperlyConfigured: WSGI application 'project.wsgi.application' could not be loaded; Error importing module: 'No module … -
MultipleObjectsReturned in complex queryset while result should be unique
I am using Django 2.0 and running into strange issues with a queryset needs generated from a union() of two querysets: needs.get(pk="3fbdcc49-2f06-46ea-a0a3-587ac5aaf50f") --------------------------------------------------------------------------- MultipleObjectsReturned Traceback (most recent call last) <ipython-input-29-300ad17a22c2> in <module>() ----> 1 needs.get(pk="3fbdcc49-2f06-46ea-a0a3-587ac5aaf50f") /usr/local/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 405 raise self.model.MultipleObjectsReturned( 406 "get() returned more than one %s -- it returned %s!" % --> 407 (self.model._meta.object_name, num) 408 ) 409 and with the same queryset: for n in needs: print(n.pk) 3fbdcc49-2f06-46ea-a0a3-587ac5aaf50f 7c134214-6309-4881-b381-016cc00a31a5 So: needs is a queryset with two objects, one of it with its primary key (a UUID) set as 3fbdcc49-2f06-46ea-a0a3-587ac5aaf50f. But the get() function raises MultipleObjectsReturned. Any idea what causes such behaviour? Is it right to look for a UUID with its string representation? Without bothering you too much with my models, here is how I generate the needsqueryset: own_needs = models.Need.objects.filter(owner="bfd8e679-7660-4dcd-83bd-614fbd99b506") mandate=models.ListMandate.objects.get(mandated=user1, permission=models.ListMandate.CAN_BUY_NEEDS, revoked_on=None) shared_needs=models.Need.objects.filter(list=mandate.target) needs = own_needs.union(shared_needs) Thanks for your enlightenment! -
django-tables2 customize table visualization
I am working on a web app with Django (first time using this) and I have successfully rendered a table with django-tables2 and it looks like this: Sequence Epitope Score sequence1 name1 0.5 sequence1 name2 0.7 sequence2 name1 0.4 sequence2 name2 0.2 ... ... ... But I would like to switch the columns and rows to get it to look like: Sequence name1 name2 ... sequence1 0.5 0.7 ... sequence2 0.4 0.2 ... ... ... ... Is there a way to change this without changing my models? I have been searching for a while now but I can't find a way to change this. Can anyone help me with this? Here is my table from tables.py class CSVTables(tables.Table): class Meta: model = CSV_Results attrs = { 'class': 'output_table', 'th': {'class': 'output_table_header'} } template_name = 'django_tables2/bootstrap.html' fields = ('TCRsequence', 'Epitope', 'Score')#,"Submission_ID") The model is linked to a form, depending on the input from the user, there could be 10 names in 'Epitope', 50 or just 2,... . My model: class CSV_Results(models.Model): TCRsequence = models.CharField(max_length=100) Epitope = models.CharField(max_length=100) Score = models.FloatField() Submission_ID = models.ForeignKey('Info_Submission',on_delete=models.CASCADE) class Meta: verbose_name_plural = "CSV_results" My views.py: table = CSVTables(CSV_Results.objects.filter(Submission_ID__Submission_ID__exact=submission_id)) RequestConfig(request, paginate={'per_page': 50}).configure(table) And in my html I … -
Trying to include a form on another app's template with {% include %}, but getting "TemplateDoesNotExist"
Currently, I can leave a comment about a post, but I have to go to a separate comment create page. I want to include the comment form right under the post in the group detail page. I have tried to use {% include %}, but it cant seem to find the form. This is probabaly because I am trying to render the form on a different app's template than where the form.py and comment_form.html are (I create the form and the template for the form in the 'comments' app, and I'm trying to include the form in the the 'groups' app on the detail page. here are the relevant files. comments/forms.py from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) comments/comment_form.html <h2>this is the comment form</h2> <form class="post-form" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> groups/views.detail : def detail(request, group_id): group = get_object_or_404(Group, pk= group_id) posts = Post.objects.filter(group__id = group_id) form = CommentForm() return render(request, 'groups/detail.html', {'group': group, 'posts':posts, 'form':form}) groups/detail.html: {% include form %} again, it can't find the template, probabaly because I have to make the 'groups' app aware of 'comment_form.html' 's existence. … -
Failed to start Gunicorn daemon for Django Project
I am using Digital Ocean to host my Django website using Nginx and Gunicorn. This is my gunicorn status gunicorn.service: Start request repeated too quickly. Failed to start Gunicorn daemon for Django Project I have tried again and again to restart my gunicorn by running this command sudo service gunicorn restart Please tell me what wrong I am doing? and how to restart gunicorn? -
Django: Getting error in terminal when going to admin page of django localhost
I created a django project. I set all the settings. I checked all urls of the project but when I visit admin page of the django localhost, I got the following error :- Traceback (most recent call last): File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Program Files\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [14/May/2018 17:28:44] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 49823) Traceback (most recent call last): File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Program Files\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] … -
Error 404 on Every POST Request Django + Apache
I am trying to deploy a Django application with Apache Server on Red Hat 4.4.7-18. Everything is working fine except forms. Whenever I submit a form with POST request I get 404, even on Django Admin login form. Same application with same settings is working fine on Ubuntu with Nginx web server. I am using A2Hosting (https://www.a2hosting.com/). I deployed this Django app using their cPanel on a Add-on domain. Apache Version: 2.2.31 Django Version: 1.11.7 Python Version: 3.5 This is how my .htaccess file looks like: RewriteEngine on # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/djangoapp" PassengerBaseURI "/" PassengerPython "/home/username/virtualenv/djangoapp/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END RewriteBase / RewriteCond %{HTTPS} off RewriteRule (.*) https://example.com/$1 [R=301,L] When I set DEBUG=True, I get this error: Error screenshot -
Using djando auth views,TypeError: view must be a callable or a list/tuple in the case of include()
I have seen similar question urls type error views I have modified my urls.py file from django.conf.urls import url from . import views as myapp_views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^login/$','auth_views.login',name='login'), url(r'^logout/$','auth_views.logout',name='logout'), url(r'^logout-then-login/$','auth_views.logout_then_login',name='logout_then_login'), url(r'^$', myapp_views.dashboard, name='dashboard'), ] But I got File "/home/milenko/bookmarks2/account/urls.py", line 22, in <module> url(r'^login/$','auth_views.login',name='login'), File "/home/milenko/env2/bookmarks2/lib/python3.6/site-packages/django/conf/urls/__init__.py", line 13, in url return re_path(regex, view, kwargs, name) File "/home/milenko/env2/bookmarks2/lib/python3.6/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). How to solve this? -
Customising Django Admin
I have a Django site on which users can make bookings for events. I need to create a backend site for internal management staff to create events, manage events and bookings, do all sorts of other stuff. Would I be better off customising the Django admin site for the backend (it is going to be MUCH more complicated than listing instances of models, updating individual ones, adding new ones etc.) or just creating my own backend for it from scratch? My instinct is that, since I'm not going to be using any of the standard functionality of the existing Django admin, I'd be better off making my own and keeping the old Django admin for site admins to use but I'm not 100% sure. -
The social-django package shows error while trying to login to facebook
When iam trying to use the facebook social-django as a package in django its shows an error like , Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:// I am created an app in fb and its having an id and key that already added in settings.py. In fb app redirect url is like : https://localhost:8000/ -
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:
In case related_name is specify in the fields and the realted model does not have the record, django raise the following error while accessing the related_name django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Here is the example code: from django.conf import settings User = settings.AUTH_USER_MODEL class Partner(models.Model): user = models.OneToOneField(User, related_name = 'partner_user', on_delete=models.CASCADE) Now in shell from django.contrib.auth.models import * user1 = User.objects.get(pk=1) user1.partner_user Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 389, in __get__ self.related.get_accessor_name() django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no partner_user At present I am using this solution hasattr(user1, 'partner_user') and user1.partner_user or [] Any better solution ?? -
A server error occurred. Please contact the administrator. in django
settings.py """ Django settings for tutorial project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tw)pqpbi)r_z1lr0j#h1m6m)wy*8b+4-iorw#%-t3#x)6wuv8$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tutorial.middleware.LoginRequiredMiddleware' ] ROOT_URLCONF = 'tutorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N … -
Can I add the Model function property in the API?
Can I add the Model function property in the API? I have a Model: class PhysicalServer(models.Model): name = name = models.CharField(max_length=32) trade_record = models.ForeignKey(to=TradeRecord, null=True, blank=True) @property def is_applied(self): if self.trade_record == None: return False else: return True my PhysicalServerListAPIView of it: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] queryset = PhysicalServer.objects.all() the PhysicalServerListSerializer: class PhysicalServerListSerializer(ModelSerializer): class Meta: model = PhysicalServer fields = "__all__" I have a requirement, how can I add the is_applied to the list API? I mean, if I access the ListAPI, the results data will be like: { name: xxx, trade_record: xxx }, ... How can I add this? { name: xxx, trade_record: xxx is_applied: xxx }, ... -
How to use related_name of 2 models in 1 Django Template
Hi Djangonauts I am new to Django so please forgive me if there are silly mistakes in my logic or code. I have 4 models. User, Group, Post and Proof. User is just a regular user model Groups are Topics (example: Bicycling, Basketball, Canoeing...)A user chooses which group and writes a Post in that Group. Post: A post is like a "task" which the author shows how to do.(example: how to ride a bicycle on 1 wheel...). The last model is the Proof model where other users respond saying they did what the post explains how to do. Proof: When other users do what the post says. They have 2 upload 2 images click submit and their name gets added to members who did the "task" Below is my Proof models.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='postproofmade') made_at = models.DateTimeField(auto_now=True) image_of_task= models.ImageField() proof_you_made_it = models.ImageField() suggestions = models.CharField(max_length=1000) Below is my post.models.py class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post_image = models.ImageField() made = models.ManyToManyField(User, blank=True, related_name='post_made') below is my post_detail view class PostDetail(SelectRelatedMixin, DetailView): model = Post select_related … -
Using distinct() with filter() in django
I'm trying to create a query in Django that calls unique rows (using distinct) that meet some condition of a filter (using filter) here are the used files : views.py def cat_details(request, pk): current_user = request.user selected_cat = get_object_or_404(Category, pk=pk) selected_items = ItemIn.objects.all().filter(item_category=selected_cat).values_list('item_name', flat=True).distinct() all_cats = Category.objects.all() cat_count = all_cats.count() item_count = ItemIn.objects.values_list('item_name', flat=True).distinct().count() # returns a list of tuples.. #all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum'] context = { #'all_units': all_units, 'item_count': item_count, 'cat_count': cat_count, 'selected_items': selected_items, 'selected_cat': selected_cat, 'current_user': current_user, } return render(request, 'townoftech_warehouse/cat_details.html', context) The variable called selected_items is where the problem! and here is how I used this view function HTML {% extends 'townoftech_warehouse/base.html' %} {% block content %} {% load static %} <div class="card"> <div class="card-header"> الاصناف فى المخزن </div> <div class="card-body"> <h3 align="right"> {{ selected_cat }}</h3> <footer><a href="{% url 'edit_cat' selected_cat.pk%}"><button type="button" class="btn btn-dark">تعديل إسم الفئة</button></a> <a href="{% url 'category_delete' selected_cat.pk%}"><button type="button" class="btn btn-dark">مسح الفئة</button></a> </footer> </div> </div> <div style="overflow: auto;height: 280px"> <table class="table table-bordered"> <tbody> {% for item in selected_items %} <tr align="right"> <th scope="row"><a href = "{% url 'items' item.pk%}">{{ item.item_name }}</a></th> </tr> {% endfor %} </tbody> </table> </div> <br> <br> <div align="right"><a href="{% url 'cat' %}"><button type="button" class="btn btn-danger">رجوع</button></a></div> {% endblock %} whenever I try … -
Django: __str__ for displaying ManyToMany field
I have a model with a ManyToMany relationship to another model, I want to define a __str__ function that show all the related fields in the many to many field, but it just show a "None" result Model with many to many: class Historicals(models.Model): artwork_id = models.ManyToManyField(Artworks) # <-- I need this def __str__(self): return str(self.artwork_id) The Artworks model: class Artworks(models.Model): author = models.ManyToManyField(Artists) title = models.CharField("artwork title", max_length=80) def __str__(self): return self.title The result I obtain for Artworks is the title as expected, but for Historicals return artwork.Artworks.None. Any suggestions? -
How change size of CharField
This code is changing sizes of all CharFields in class. How I can change size of one CharField? formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '20'})}, } -
OperationalError: could not connect to server: Connection refused - when trying to connect to new postgresql database
I'm changing my development Django Database from sqlite to postgresql. I've changed my settings to the appropriate values: DATABASES = { 'default': { 'ENGINE': "django.db.backends.postgresql_psycopg2", 'NAME': "db.postr", 'USER': "zorgan", 'PASSWORD': config('DB_PASSWORD'), 'HOST': "localhost", 'PORT': '', } } however when I perform python manage.py makemigrations I get this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle loader.check_consistent_history(connection) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history applied = recorder.applied_migrations() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) … -
Redo queryse if is empty and pass the information to template
In a View a I modified the queryset to filter by name: def get_queryset(self, *args, **kwargs): qs = super().get_queryset() if self.request.GET.get('q'): qs = qs.search_by_keyword(self.request.GET.get('q')) return qs If there are no results to the filtered by q Queryset, I want to execute the default queryset, but also pass to the template that I done so. The issue, is if I check if is empty and redo the queryset in get_queryset(), I don't know how to know that I done this operation in template. -
Custom wagtail page model save method called twice
In a Django+Wagtail project, I have a custom method which I call from the model save() method. It works - but everytime I save an instance via the wagtail admin interface, this method is called twice - why? # models.py class ArticlePage(Page): def my_method(self): print('I will be printed twice on save...') def save(self, *args, **kwargs): self.my_method() super().save(*args, **kwargs) Env: Django 2.0.4 Wagtail 2.0.1 -
how to search in json list django
I have model with JSONField, and some of those values in this field can be lists. when I'm search after all the values how bigger than some number, 3 for example. the query returns all the lists even though the values in those lists are smaller, how can i get only the correct rows? query: Books.objects.filter(pages__t__gte=2): returns all the books with t>=2 and all the books with list as t, for example: t:[0,1] -
Accessing the parent object pointing to children objects in Many-to-Many Relationship Django
I have the following models below: class Account(models.Model): courses = models.ManyToManyField(Course) class Course(models.Model): name = models.CharField(blank=True, null=True) Can I access the account object pointing to a course from a course? Say for example: course = Course.objects.get(id=1) account_parent = course.parent_pointing_to_me