Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python split a list into vaious list by month
I have a list of objects (django model) that contain date atribute among others. day/month/year and i need to split it into groups by month and year, so if i have: list_dates = ['1-10-2018','4-10-2018','1-11-2018', '6-10-2018', '3-10-2018', '6-11-2018', '9-11-2018'] wich is actually: list_objects = [a,b,c,d,e,f,g...z] it turn into splitted_list ? {[a,b,e],[c,d,e]}# same month, same year grouped together list_grouped = {['1-10-2018','4-10-2018','1-10-2018','6-10-2018'], ['3-11-2018', '6-11-2018', '9-11-2018']} and i have not been able to find an easy or doable way to do this Hope someone has some idea of how to do this. have been trying it for days now. -
django.core.exceptions.FieldDoesNotExist: BuildingAddress has no field named 'False'
class BuildingAddress(models.Model): id = models.CharField(max_length=12,primary_key = True) address = models.CharField(max_length=30) city = models.CharField(max_length=30) zip = models.CharField(max_length=10) state = models.CharField(max_length=2) primpgon = models.BigIntegerField() numpgons = models.BigIntegerField() x = models.FloatField() y = models.FloatField() censusbloc = models.CharField(max_length=15) objectid = models.BigIntegerField() geom = models.MultiPolygonField(srid=4326) and then I am trying to import my shape file to this model. I wrote the below script. import os from django.contrib.gis.utils import LayerMapping from .models import BuildingAddress no_address_mapping = { 'id' : 'ID', 'address' : 'Address', 'city' : 'City', 'zip' : 'ZIP', 'state' : 'State', 'primpgon' : 'PrimPgon', 'numpgons' : 'NumPgons', 'x' : 'X', 'y' : 'Y', 'censusbloc' : 'CensusBloc', 'objectid' : 'ObjectID', } no_address_shp = os.path.abspath( os.path.join( os.path.dirname(__file__), 'building/WestDV_CA_BF_NoAddress_region.shp')) def run(verbose=True): lm = LayerMapping( BuildingAddress, no_address_shp, no_address_mapping, transform=False, encoding='iso-8859-1') lm.save(strict=True, verbose=verbose) And then I run this file in shell When I am try to run this file I am getting the "django.core.exceptions.FieldDoesNotExist: BuildingAddress has no field named 'False'" Error. I don't understand why this error happend. I am not creating any field name as False. But it throws the Field name false doesn;t exist -
How to add data to context object in DetailView?
I need to write a DetailView in Django. I achieved this functionality. However, I need to add some more data along with the context object. How will I achieve this. My generic view is: class AppDetailsView(generic.DetailView): model = Application template_name = 'appstore/pages/app.html' context_object_name = 'app' I need to add one more variable to the context object: response = list_categories(storeId) -
Emails sent via SentGrid are sent to the Spam Folders
While following this tutorial : https://www.youtube.com/watch?v=IGE8uhVDd-c&lc=UgwVoTSZQGrJxK8agT94AaABAg I managed to successfully send emails but unfortunately those emails are going to the Spam folders.Why are the emails going to spam? Is there any solution? I already have my settings.py specified at templates directory with Django 2.0 : settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mysite/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', ], }, },] Any help is highly appreciated. -
When session expired ,do any actions will redirect login page by Django
I use Django 1.9 and python 3.5. I set session expiry time 1800 seconds.When the session expired ,I only click the url or reload the page,the page redirect the login page.I want to do any actions on the page redirect login page.What should i do? my settings: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'zeus.middleware.SessionMiddleware', ) my middleware: # -*- coding: utf-8 -*- try: from django.utils.deprecation import MiddlewareMixin # Django 1.10.x except ImportError: MiddlewareMixin = object # Django 1.4.x - Django 1.9.x class SessionMiddleware(MiddlewareMixin): def process_request(self,request): pass def process_response(self,request,response): if hasattr(request,'user'): if request.user.is_authenticated(): request.session.set_expiry(1800) return response -
Django: Stripe ID safe in URL?
When I create a user in Stripe, I get the below data created for a user. In Django, I have a list of bank accounts that someone has created and I wanted them to be able to click on the bank account and it will take them to a page where they can enter their micro-transactions for verification. Is it good practice/safe to put the id in the url to pass it to the second page? I'm using jquery to do so. In the end the url will look something like this: https://...billing/ach-payment-verify/ba_1CXKXasdfasasdf2G5I56gyW9KQ Stripe Sample Data { "account_holder_name": "m p ", "account_holder_type": "individual", "bank_name": "STRIPE TEST BANK", "country": "US", "currency": "usd", "customer": "cus_CwPr2Da0fn4Nee", "fingerprint": "OKMIMrpIGiLUIBtE", "id": "ba_1CXKXasdfasasdf2G5I56gyW9KQ", "last4": "6789", "metadata": {}, "object": "bank_account", "routing_number": "110000000", "status": "new" } -
How to show a certain number of levels in django-mptt?
In my Django project I use django-mptt application to create hierarchical tree. Right now next code works well but I want to show only first 4 level of the tree. How to make it correctly? I am confused. views.py: context['caregories'] = Category.objects.get(id=5).get_descendants() html: {% load mptt_tags %} <ul> {% recursetree caregories %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
How can I return the created data when created success in Django
In my Django project, I have a APIView: class PhysicalServerManualGenerateOrderAPIView(CreateAPIView): serializer_class = PhysicalServerManualGenerateOrderSerialzier permission_classes = [IsFinanceAdmin, IsSuperAdmin] queryset = Order.objects.all() in the PhysicalServerManualGenerateOrderSerialzier: class PhysicalServerManualGenerateOrderSerialzier(ModelSerializer): ... def create(self, validated_data): try: order = getOrder(user=user, validated_data=validated_data) # there I create the order instance except Exception as e: order = None return order But I have a requirement, I want to return the created order's id (or other data) when I access the APIView success. -
How Can I Extract Variables from a LaTeX Doc into a Python Dictionary So That I Can Pull it into Django?
I'm pretty new to Django and LaTeX so I'm hoping that someone out there has done something like this before: I'm trying to create a Django app that can read a LaTeX file, extract all of the variables (things of this form: "\newcommand{\StartDate}{January 1, 2018}") and place them as key/value pairs into a dictionary that I can work with inside Django. The idea is that each variable in the LaTeX file starts with a place holder value. I'll be building a dynamic form that uses the dictionary to create field/values and let's a user replace the place holder value with a real one. After a user has set all of the values, I'd like to be able to write those new values back into the LaTeX file and generate a pdf from it. I've tried regular expressions but have run into trouble. I've also looked at TexSoup which seems to be very promising but I haven't been able to totally figure out yet. -
AttributeError: module 'django' has no attribute 'utiles'
I'm starting gunicorn typeidea.wsgi:application -w 4 -b 0.0.0.0:8000, But I got an error ``` Traceback (most recent call last): File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 382, in resolve found = getattr(found, frag) AttributeError: module 'django' has no attribute 'utiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 384, in resolve self.importer(used) ModuleNotFoundError: No module named 'django.utiles' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 708, in configure_handler klass = self.resolve(cname) File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 391, in resolve raise v File "/home/jummy/.pyenv/versions/3.6.4/lib/python3.6/logging/config.py", line 384, in resolve self.importer(used) ValueError: Cannot resolve 'django.utiles.log.AdminEmailHandler': No module named 'django.utiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app import(module) File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/typeidea/wsgi.py", line 16, in application = get_wsgi_application() File "/home/jummy/workspace/typeidea-env3/lib/python3.6/site-packages/django/core/wsgi.py", line 12, … -
Django Foreign Key model cant display in view JSON
When I run this, I get JSON file but the foreign key (contact numbers) are not included, I want to display one contact name/address/email with multiple contact numbers. models.py from django.db import models class PhoneBook(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100, default='address') email = models.CharField(max_length=50, default='email') note = models.CharField(max_length=100, default='note') def __str__(self): return self.name class ContactNumber(models.Model): number = models.ForeignKey(PhoneBook, related_name="contact_numbers") contact_number= models.CharField(max_length=30) def __str__(self): return self.contact_number views.py from django.shortcuts import render from .models import PhoneBook,ContactNumber from django.http import JsonResponse from django.views import View class PhoneBookList(View): def get(self,request): phonebooklist=list(PhoneBook.objects.values()) return JsonResponse(phonebooklist,safe=False) -
Django bulk_create CreateView
I have my models.py class Schedule(models.Model): name = models.CharField(max_length=255) date_from = models.DateField('') date_to = models.DateField('', null=True) desc = models.TextField(blank=True, null=True) here my views.py class Schedule(CreateView): fields = () model = models.Schedule def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return super(ModelFormMixin, self).form_valid(form) and here my template.html {{form.as_p}} this form only can do 1 time input. however I need to perform 3 times input in single form with different name & date (in my case). and form maybe look like {{form.as_p}} {{form.as_p}} {{form.as_p}} I check on documentation theres bulk_create can do multiple input in single run but i dont have idea how to deal with my template.html -
Django "get_git_revision failed: [Errno 2] No such file or directory: '.../.git/HEAD'"
I recently installed pybrake for a Django app, and now when I run my development server, I see the following error: 2018-05-29 18:32:13,414 - pybrake - ERROR - get_git_revision failed: [Errno 2] No such file or directory: '/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/.git/HEAD' After that, however, the development server seems to start up normally; here is the full terminal response: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py runserver 2018-05-29 18:32:13,414 - pybrake - ERROR - get_git_revision failed: [Errno 2] No such file or directory: '/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/.git/HEAD' 2018-05-29 18:32:15,353 - pybrake - ERROR - get_git_revision failed: [Errno 2] No such file or directory: '/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/.git/HEAD' Performing system checks... System check identified no issues (0 silenced). (0.000) SELECT typarray FROM pg_type WHERE typname = 'citext'; args=None (0.006) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid); args=None (0.031) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() May 29, 2018 - 18:32:17 Django version 1.11.9, using settings 'lucy.settings.development' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The error still irks me a bit though and I'd like to remove it. It seems like this get_git_revision function is looking in the wrong directory: the .git … -
Django docker-compose after restart requires migration again
I made this unit file. [Unit] Description=myservice Requires=docker.service After=docker.service [Service] Restart=always # Remove old containers, images and volumes ExecStartPre=/usr/bin/docker-compose -f my.yml down -v ExecStartPre=/usr/bin/docker-compose -f my.yml rm -v ExecStartPre=-/bin/bash -c 'docker volume rm $(docker volume ls -q)' ExecStartPre=-/bin/bash -c 'docker rmi $(docker images | grep "<none>" | awk \'{print $3}\')' ExecStartPre=-/bin/bash -c 'docker rm -v $(docker ps -aq)' # Compose up ExecStart=/usr/bin/docker-compose -f my.yml up # Compose down, remove containers and volumes ExecStop=/usr/bin/docker-compose -f my.yml down -v [Install] WantedBy=multi-user.target Before running this file, I create the migration like this: docker-compose -f my.yml run --rm django python manage.py migrate But, after rebooting the OS, I need to restart the migration, because they are not detected. What can be wrong? -
Django 2.0 Tutorial - Cant Acess Django-Admin Shell
When I attempt to acess the Django Shell using Django-Admin Shell, I get the error message: django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. (env2) Coreys-MacBook-Pro:mysite3 coreydickinson$ I've attempted the settings.configure() in the python shell, and I'ved tried redirecting the Django settings using django-admin.py shell --settings=mysite.settings. Neither worked. Anyone have any idea what I am doing wrong? Full error: (env2) Coreys-MacBook-Pro:mysite3 coreydickinson$ django-admin shell Traceback (most recent call last): File "/Users/coreydickinson/mysite/DJDev/env2/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/core/management/base.py", line 327, in execute saved_locale = translation.get_language() File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 187, in get_language return _trans.get_language() File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 55, in __getattr__ if settings.USE_I18N: File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/coreydickinson/mysite/DJDev/env2/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. (env2) Coreys-MacBook-Pro:mysite3 coreydickinson$ -
Django migrate does create new column
When running the migrations commands, columns are not created automatically. However, all printed results look normal. This only happens during development on the local machine, but columns populate normally on the production server. python migrate.py makemigrations python migrate.py migrate **Operations to perform:** **Apply all migrations**: admin, auth, contenttypes, group_shop, sessions **Running migrations:** Applying group_shop.0204_orderitem_order_item... OK -
Django: How to next process Stripe's ACH Verification Error
I want to be able to act on an error that happens when I run one of the commands to interface stripe. I can see the error, but can't seem to capture it. When I run a the verification for stripe's ACH payment format and use bad deposist, I get the following error: in handle_error_response raise err stripe.error.CardError: Request req_UyfXgBVRSOqUuJ: The amounts provided do not match the amounts that were sent to the bank account. How do I take this and do something meaningful with it. My code looks like this: ank_account_response = customer.sources.retrieve(request.stripe_id) bank_account_response.verify(amounts=[request._post['deposit_1'], request._post['deposit_2']]) The error appears on the last line of code. I want either set do something like output = bank_account_response.verify... or try: bank_account_response, but I can't get it to work. Thoughts? -
structure multiple apps like django for flask
I'm a bit confused about this, i'm used to working on django with multiple applications. (apps, urls, views, models for each app) (settings, wsgi for project) I do not understand how I would maintain a file structure with multiple flask apps -
Using Django-Freeze to Save ONLY a subset of the site
I have a website filled with customer pictures. Each customer's data is accessed via www.website.com/user/username. I need to create an offline version of individual user-specific site only. Freeze is working, but giving me the ENTIRE website. I've looked at the documentation and assumed the FREEZE_SITE_URL setting could be used to narrow the freeze to only a subset of the site by url, but it does not seem to function in this manner. Is there an option in django-freeze to specify a subdirectory to start the static site generation? -
How to refresh a part of the DOM HTML when querying a foreign django view
Hello Awesome People! So many questions on StackOverflow are about "How to refresh dom via jquery (from the same view/url)" It's not what I'm looking for. With a website that large of its parts are running with ajax, I wonder how to refresh a part of the HTML DOM when querying a foreign django view. Let me be clearer with some examples: I have that view that sends all_users to template def usersList(request): all_users = User.objects.all() return render(request,'administration/users-list.html',{'all_users':all_users}) In the template I loop through all_users... The 2nd <span> reflects the activation state of the user {% for u in all_users %} <span>{{forloop.counter}}.- {{u.name}} <span> <span id='user_{{u.id}}_state'> <button data-id='{{u.id}}' type='button' class='css-btn btn-circle'> {% if u.is_activate %} Active{% else %}Inactive{% endif %} </button> <span> {% endfor %} With jquery, I send a request to a specific view responsible only to activate or deactivate the account of the user. We can activate/deactivate user in many parts of the website, that's why I do so in a different view. Here's the view: def deactivateUser(request): user = request.user if user.has_perm('is_admin') and request.is_ajax() and request.method == 'POST': id_user = request.POST.get('id') targeted_user = get_object_or_deny(User,id=id_user) # get_object_or_deny is my own function it will get the object or raise … -
Optimize queryset with django
I created a function that allows to count the number that there is of status and assign it to a variable. def get_types_count_display(self): dispatches = self.route_dispatches.values_list('dispatch_id', flat=True) dispatches = Dispatch.objects.filter(id__in=dispatches) d = { "dispatches_types": list(dispatches.values('status_id')) } pendents = len([1 for e in d["dispatches_types"] if e["status_id"]==1]) delivered = len([1 for e in d["dispatches_types"] if e["status_id"]==2]) partial = len([1 for e in d["dispatches_types"] if e["status_id"]==3]) undelivered = len([1 for e in d["dispatches_types"] if e["status_id"]==4]) return dict(pendents=pendents, delivered=delivered, partial=partial, undelivered=undelivered) where d is my variable that stores the dictionary it contains {'dispatches_types': [{'status_id': 2}, {'status_id': 1}, {'status_id': 1}, {'status_id': 1}, {'status_id': 2}]} or {'dispatches_types': []} this is dynamic the problem I have is that when you go through with for again invoking the query set, the query becomes heavier. How can I optimize this function? -
javascript multiple groups select all
i'm new to javascript and I have the following javascript function called selectallrep.js: function toggle(source) { checkboxes = document.getElementsByName('report_id'); for (var i = 0, n = checkboxes.length; i < n; i++) { checkboxes[i].checked = source.checked; } } I'm attempting to get the element name 'report_id' which is part of my django form. There are several groups of report_id's which have separate for loops. The current method is selecting everything in the django form below: <div class="container"> <div class="col-md-4"> <script src= "{% static '/search/selectallrep.js' %}" type="text/javascript"></script> {% if fingrouplist is not None %} <h4><strong>Financial</strong/></br></br><input type="checkbox" onClick="toggle(this)" /> Select All</h4> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> {% endif %} </div> <div class="col-md-4"> <div class = "row"> {% if cagrouplist is not None %} <h4><strong>Care Assure</strong/></br></br><input type="checkbox" onClick="toggle(this)" /> Select All</h4> <ul> {% for app in cagrouplist %} <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> {% endif %} </div> <div class = "row"> {% if pigrouplist is not None %} <h4><strong>Performance Improvement</strong/></br></br><input type="checkbox" onClick="toggle(this)" /> Select All</h4> <ul> {% for app in pigrouplist %} <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> … -
What is the recommended Airbrake logger for Django, pybrake or airbrake-django?
On the Airbrake docs page, https://airbrake.io/docs/installing-airbrake/installing-airbrake-in-a-django-app/, there is a link to https://github.com/airbrake/airbrake-django#manually-sending-errors-to-airbrake, described as "our official Github repo". However, if you simply click "Python" on the main page (https://airbrake.io/docs/installing-airbrake/installing-airbrake-in-a-python-app/) an integration with pybrake is described, including a link for Django integration which is specific to pybrake (https://github.com/airbrake/pybrake#django-integration). This seems a bit confusing. What is the recommended way to manually log errors with Airbrake in a Django project? -
Django: How to embed get_absolute_url href tag in Jquery Autocomplete results so that they can redirected to url when click on them?
I have created autocomplete with Jquery AJAX UI and able to get results. These results are actually my posts and these posts have get_absolute_url function so that they can redirected to a url where that particular post is located. How do I embed in Jquery Autocomplete results so that they can redirected to url when click on them? Need help on javscript/Jquery part as it's not my area. var Autocomplete = function(options) { this.form_selector = options.form_selector this.url = options.url || '/rincon/autocomplete/?query=' this.delay = parseInt(options.delay || 300) this.minimum_length = parseInt(options.minimum_length || 3) this.form_elem = null this.query_box = null } Autocomplete.prototype.setup = function() { var self = this this.form_elem = $(this.form_selector) this.query_box = this.form_elem.find('input[name=query]') // Watch the input box. this.query_box.on('keyup', function() { var query = self.query_box.val() if(query.length < self.minimum_length) { return false } self.fetch(query) }) // On selecting a result, populate the search field. this.form_elem.on('click', '.ac-result', function(ev) { self.query_box.val($(this).text()) $('.ac-results').remove() return false }) } Autocomplete.prototype.fetch = function(query) { var self = this $.ajax({ url: this.url , data: { 'query': query } , success: function(data) { self.show_results(data) } }) } Autocomplete.prototype.show_results = function(data) { // Remove any existing results. $('.ac-results').remove() $("#query").on('input', function() { if ($(this).val().length >= 3) return; $('.ac-results').empty(); }); var results = … -
Not logging in as a registered user
I seem to not be logging in as a user which has been registered. I've extended User from contrib.auth to CustomUser, so that I could add some extrafields to my models. I am using modelForms and class based views. What am I misunderstanding in djangos conventions for logging in ? views.py: class LoginUserView(CreateView): form_class = LoginUserForm template_name = "account/login.html" def login_Render(self, request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return render(request, 'account/login.html', {'form',form}) forms.py: class LoginUserForm(forms.ModelForm): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ['username','password'] def validLogin(self): return True urls.py : urlpatterns = [ path('login', LoginUserView.as_view() , name='login'), index.html : {% block content %} <div class="" style="display:flex; flex-direction:column;" id="first-appID"> {% if user.is_authenticated %} <h1>Welcome to your Home Page {{ user.username }} </h1> </br>This is your home page <p><a href="{% url 'logout' %}">logout</a></p> aaaaaand this is what it looks like on my end: