Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ListView - template for loop does not display any items
This is what I want to achieve: well_list.html <thead> <tr> {% for item in well_info %} <th>item</th> {% endfor %} </tr> </thead> project/urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.urls import path, re_path, include from eric_base import views urlpatterns = [ path('contextual/', include('eric_base.urls')), path('well_list/', views.well_list) ] views.py from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from . import models class WellInfoListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo models.py from django.db import models from django.urls import reverse # Create your models here. class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) region_location = models.CharField(max_length=100) spud_date = models.CharField(max_length=100) well_bore = models.CharField(max_length=100) rig_name = models.CharField(max_length=100) status = models.CharField(max_length=100) def get_absolute_url(self): return reverse("") Since I correctly defined context_object_name = 'well_info' in views.py, and I used {% for item in well_info %} in the html, I was expecting that I would get at least something from the model attributes. But when I run this code, I don't get anything. The header row just disappears like the following screenshot: I want the table headers to have the attribute names defined in models.py, but apparently its not grabbing anything from … -
How to Filter nested list through URL in Django RestFramework
I have a course model and insde it I have a categories list … I want to be able to filter the categories Here's my serilaizers class CourseSerial(serializers.ModelSerializer): categories = serializers.SerializerMethodField(read_only=True) image = VersatileImageFieldSerializer( sizes=[ ('full_size', 'url'), ('thumbnail', 'thumbnail__100x100'), ('medium_square_crop', 'crop__400x400'), ('small_square_crop', 'crop__50x50') ] ) class Meta: model = Course fields = ('id','name_a','name_e','short_desc_a', 'short_desc_e','image','categories') def get_categories(self, obj): cats = CourseCategories.objects.filter(course=obj.id) return CourseCategoriesSerial(cats,many=True). class CourseCategoriesSerial(serializers.ModelSerializer): class Meta: model = CourseCategories fields = '__all__' and here's the results "active": 1, "creation_date": "2018-02-24", "creation_user": 1, "categories": [ { "id": 1, "active": 1, "creation_date": "2018-02-24", "course": 1, "category": 140, "subcategory": 159, "creation_user": 1 }, I have a course categories model and it's nested in the course serilaizers...my models.py look like: class Course(models.Model): name_a = models.CharField(max_length=100) name_e = models.CharField(max_length=100) active = models.IntegerField(blank=True, null=True) creation_date = models.DateField(blank=True, null=True) creation_user = models.ForeignKey('User', models.DO_NOTHING, db_column='creation_user') class Meta: managed = True db_table = 'course' class CourseCategories(models.Model): course = models.ForeignKey(Course, models.DO_NOTHING) category = models.ForeignKey('Lookups', models.DO_NOTHING,related_name='course_category') subcategory = models.ForeignKey('Lookups', models.DO_NOTHING,related_name='course_sub_category') active = models.IntegerField(blank=True, null=True) creation_date = models.DateField(blank=True, null=True class Meta: managed = True db_table = 'course_categories' I want to be able to filter the nested list, URL filter.. like api/course/?categories__category=140 -
Django: using Javascript to append chat to chatbox for a user
I am using Djano (1.11) channels 2.0 and have a messaging system. Currently, I am displaying the chat of 2 users in two different colors. I can post to the chat board, but it always looks like it came from user 1 even if user 2 sent it. This is my sudo working code (chatItems.append(<div class="textcontainer lighter">${msgData.msg}</div>)) I tried something like this, but it didn't work: `chatItems.append({% if user == messenger.user %} <div class="textcontainer lighter">${msgData.msg}</div>{% endif %})` html page chat: <div class='container'> <div id="board" class="section grey lighten-3" style="height: 68vh; padding: 5px; overflow-y: scroll" > {% for messenger in object.messengermessage_set.all %} {% if user == messenger.user %} <div class="textcontainer lighter"> {{ messenger.message }} <span class="time-right">{{ message.timestamp | date:"SHORT_DATETIME_FORMAT" }}</span> </div> {% else %} <div class="textcontainer darker"> <span class="time-right">{{ message.timestamp| date:"SHORT_DATETIME_FORMAT" }}</span> {{ messenger.message }} </div> {% endif %} {% endfor %} </div> javascript: $(document).ready(function(){ // alert("jquery world") var formData = $("#form") var messageInput = $("#id_message") var chatItems = $('#board') var loc = window.location var webSocketEndpoint = 'ws://' + loc.host + loc.pathname // ws : wss var socket = new WebSocket(webSocketEndpoint) socket.onmessage = function(e){ console.log('message', e) // alert(e.data) var msgData = JSON.parse(e.data) console.log(msgData.user) console.log('inbetween') console.log(msgData) chatItems.append(`{% if user == messenger.user %} <div … -
Django logging during migration
I have numerous complex data migrations set up in Django and would like to set up logging to see how they complete and catch errors. I could do this with regular python logging but Django has this semi-built-in and I was hoping the Django logging would work with migrations. However the following setup does not seem to work. Where am I going wrong or does Django logging only work during serve and test? In a migration file: import logging logger = logging.getLogger('rdm') stuff logger.warning('message') more stuff In Settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'rdm_logfile': { 'level': 'DEBUG', # should capture everything (warning, info, etc.) 'filters': ['require_debug_false','require_debug_true'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR,'django_rdm.log'), 'maxBytes': 1024*1024*100, # 100MB 'backupCount': 5, 'formatter': 'simple' }, }, 'loggers': { 'rdm': { 'handlers': ['rdm_logfile'], }, } } -
refrence sent id through a sql statment
i want to reference sent Id that is coming from the frontend def list(self, request): queryset = Course.objects.raw('select * from course inner join course_categories on (course.id = course_categories.course_id) where category_id = {}').format(???????) serializer = CourseSerial(queryset, many=True) return Response(serializer.data) I want to handle a sent id and put it in my sql statement -
Locale on FullCalendar not works
I have a system with Django. In my template, the lasts scripts are: <script src="{% static 'plugins/moment/min/moment.min.js' %}"></script> <script src="{% static 'plugins/fullcalendar/js/fullcalendar.min.js' %}" ></script> <script src="{% static 'plugins/fullcalendar/js/locale-all.js' %}" ></script> {% block extra_footer %}{% endblock %} In my page, I start calendar as here, like this: {% block extra_footer %} <script> $(function() { $('#calendar').fullCalendar({ lang: '{{ LANGUAGE_CODE }}', }); }); </script> {% endblock %} When I inspect html code, the LANGUAGE_CODE is ok (for exemple: fr). But the calendar just appears in English, How can I fix it? -
404 errors when trying to get Django imagekit thumbnails
I try to generate some thumbnails using Django 2 and the imagekit library. When I want to get the thumbnails in templates, it returns me a image URL 404 error. The uploaded image is on the server, at the right place. Here's my model : class Article(models.Model): [...] uploaded_image = models.ImageField('Image miniature (upload)', upload_to='img', max_length=255, null=True, blank=True) optimized_image = ImageSpecField(source='uploaded_image', format='JPEG', options={'quality': 60, 'optimize':True}) My code in my template : {% thumbnail '700x219' article.optimized_image -- alt=article.name %} And my Nginx configuration settings for this website : location /static/ { alias /home/user/myproject/site/static; } location /media/ { alias /home/user/myproject/site/media; } The static fils are serving correctly. First, I found my generated thumbnails URL strange : https://www.mywebsite.com/media/CACHE/images/CACHE/images/img/my-img_ODSHuRU/b15da1962adc1c7a8031923bbf0fecb1/c2dd3587bf0c19faba27636f458188c3.jpg It is repeating the /CACHE/images path... So I watched at my Django's settings : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I don't see what I've done wrong. I probably failed my media directory configuration, or my Nginx configuration is not right too. Is anybody has already had this trouble before ? Have you got some clues ? Thanks for your help :) -
ModelSerializer In Django Rest is not recognizing model
I have created a Rest Model Serializer but the Django is not recognizing my model serializer. I can't determine what the issue is. Here is my code: Help would be appreciated since my other models seem to be working. Serializer: [ Model: Output from Python: -
Django - purpose of using super() and object.all()?
I found the code in this link: class questionmanager(TemplateView): template_name = 'questionmanager.html' questions = Question.objects.all() def get_context_data(self, **kwargs): context = ({ 'questions': self.questions, }) return context linebreak--- class QuestionListView(ListView): model = Question def get_context_data(self, **kwargs): context = super(QuestionListView, self).get_context_data(**kwargs) return context I just have two questions: what's does Question.objects.all() do, and what is the purpose of super(QuestionListView, self).get_context_data(**kwargs) at all?? Also, I've seen many other codes in which arguments for super() is empty. What's the difference between passing in arguments in super(), and not passing in? For Question.objects.all(), my guess is that it's storing all the attributes defined in models.py's class Question. Am I right? -
Deploy Dockerized Django Project on Elastic Beanstalk
i have created a new Django project with Dockerfile, docker-compose.yml and dockerrun.aws file. That's how my project structure looks like: dockerproject -.idea -dockerapp -views.py -urls.py -models.py -... -dockerproject -templates -venv -db.sqlite3 -docker-compose.yml -Dockerfile -Dockerrun.aws -manage.py -requirements Here is the code of my Dockerfile, docker-compose.yml(from docker docs "Compose and Django") and dockerrun.aws: Dockerfile: FROM ubuntu:15.04 FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ EXPOSE 8000 docker-compose.yml: version: '2' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres dockerrun.aws: { "AWSEBDockerrunVersion": "1", "Volumes": [ { "ContainerDirectory": "/var/app", "HostDirectory": "/var/app" } ], "Logging": "/var/eb_log" } If I run the Docker Container via Docker-machine (Kitematic) locally, the Django website runs fine by entering the following url in the browser: ip address from the dockermachine:8000/index.html But if I zip all the project files(project structure, see above) into a zip file and upload it to elastic beanstalk, then it comes an degraded status with the following error message: Application deployment failed at 2018-07-18T19:18:34Z with exit status 1 and error: Hook /opt/elasticbeanstalk/hooks/appdeploy/enact/00run.sh failed. Here is the Elastic Beanstalk configuration to deploy the … -
troble with media folder pythonanywhere
pythonanywhere cant find files in me media folder But I have this file! roots in my settings.py STATIC_URL = '/static/' STATIC_ROOT = '/home/dimabytes/my-first-blog/static' MEDIA_ROOT = '/home/dimabytes/my-first-blog/media' MEDIA_URL = '/media/' me web page at pythonanywhere -
How to add a parameter for a function in Django models
I need to change my existing function from this HTML <a href="{{ store.get_visit_url }}">...</a> models.py class Store(models.Model): def get_visit_url(self): return reverse('boutique:visit', kwargs={'store_domainKey': self.domainKey}) to something like this HTML <a href="{{ store.get_visit_url|store }}">...</a> models.py class Store(models.Model): def get_visit_url(self, store): return reverse('boutique:visit', kwargs={'store_domainKey': store.domainKey}) I wanna put a different store object in the function so that the link can work dynamically with many different store objects. The codes at the bottom box is something like what I wanna do, it didn't run. How can I do that with correct syntax? -
Django - how does get_absolute_url work?
My webpage looks like the following: When I press "Submit" button, the page is "redirected" to some different page. If I don't specify get_absolute_url method in my models.py, I will get ImproperlyConfigured error. If I set where to redirect to in my models.py, upon clicking the Submit button, it will be directed to that page. What I don't understand is, how does only the Submit button redirected to whatever the link I set up on my models.py? Why clicking on the links on the sidebar doesn't redirect to it? Why does get_absolute_url method acts only upon clicking Submit button, but not the others? practice_add_well.html <!DOCTYPE html> {% extends "base.html" %} {% block content %} <h1>Test Page for BHA</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class='btn btn-primary' value="Submit"> </form> {% endblock %} models.py from django.db import models from django.urls import reverse class WellInfo(models.Model): name = models.CharField(max_length=100) region_location = models.CharField(max_length=100) spud_date = models.CharField(max_length=100) well_bore = models.CharField(max_length=100) rig_name = models.CharField(max_length=100) status = models.CharField(max_length=100) def get_absolute_url(self): return reverse(# some link....) views.py from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from . import models class WellInfoCreateView(CreateView): template_name = 'practice_add_well.html' context_object_name = 'bha_inputs' model = models.WellInfo … -
Just getting into the game
Short and simple: I have just started to work with static websites. I want to progress on to dynamic websites, written in Python, on Django framework, and hosted by google domains. I have a great collection of resources online to learn, however, I wonder what other aspects I'm leaving out, in order to persue a job in the field. I.e. REST and such. Any suggestions are welcome and appreciated. -
django web-config azure gives error "RuntimeError: populate() isn't reentrant"
I deployed my locally developed Django web app into azure trough GitHub and when i try to run the URL i get the following error in web.config file Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\home\python364x64\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "D:\home\python364x64\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "D:\home\python364x64\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File ".\ptvs_virtualenv_proxy.py", line 107, in get_venv_handler handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER')) File ".\ptvs_virtualenv_proxy.py", line 65, in get_wsgi_handler handler = handler() File "D:\home\site\wwwroot\env\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "D:\home\site\wwwroot\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\home\site\wwwroot\env\lib\site-packages\django\apps\registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: this is my web.config file: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <customErrors mode="Off" /> </system.web> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_venv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="FinTech.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.webServer> <httpErrors errorMode="Detailed" /> <handlers> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python364x64\python.exe|D:\home\python364x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> … -
Permission denied when django writes to external device
I have a django file server. The server works perfectly on my laptop & localhost (with external hard drive) but when I transferred it to my Raspberry Pi running Raspbian, it starts acting up. I did a lot of googling and tried every possible solution but it does not work. Here is my problem: I have connected an external hard drive to my raspberry pi. I believe it has write permissions because I can easily write to it with mkdir. I have also set this directory which is /media/pi/SAMSUNG/media as my MEDIA_ROOT. Now I have set up Apache2, WSGI and Django, everything works, I have set up all the permissions and everything, but still when django tries to access the hard drive, whether it be to read or write, I get an error [Errno 13] Permission denied: '/media/pi/SAMSUNG'. I have fixed this in the past with chown -R 777 but it does not work this time. Unfortunetly, I have no idea what I am doing when it comes to servers and file permissions, so I have no idea what code to attach. Can some please help me? I will attach all the necessary code on request. Thank you -
Django Auditlog: duplicate key value violates unique constraint "auditlog_logentry_pkey"
I'm trying to run an app simulator which hits the following API endpoint: import json import logging from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST, require_GET from django.core import exceptions from django.contrib.auth.password_validation import validate_password from lucy_web.models import Family, User logger = logging.getLogger(__name__) @require_POST def update_user_via_activation_code(request, version): username = json.loads(request.body).get('username') email = json.loads(request.body).get('email') activation_code = json.loads(request.body).get('activation_code') password = json.loads(request.body).get('password') if username is None: username = email if len(Family.objects.filter(activation_code=activation_code, employee_user__email__iexact=username)) > 0: user = Family.objects.get(activation_code=activation_code, employee_user__email__iexact=username).employee_user elif len(Family.objects.filter(activation_code=activation_code, partner_user__email__iexact=username)) > 0: user = Family.objects.get(activation_code=activation_code, partner_user__email__iexact=username).partner_user else: return JsonResponse({'success': False, 'errors': {'password': 'Activation code and email do not match'}}) try: validate_password(password, user) except exceptions.ValidationError as error: return JsonResponse({'success': False, 'errors': {'password': error.messages[0]}}) user.username = email user.email = email user.set_password(password) user.save() user.profile.using_app = True user.profile.save() if not user.family.status or user.family.status == Family.ENROLLED: user.family.status = Family.NEW user.family.save() return JsonResponse({'success': True}) However, I'm getting an error psycopg2.IntegrityError: duplicate key value violates unique constraint "auditlog_logentry_pkey" Here are the development server logs with the full stack trace: (0.029) SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_content_type" WHERE ("django_content_type"."app_label" = 'auth' AND "django_content_type"."model" = 'user'); args=('auth', 'user') (0.061) INSERT INTO "auditlog_logentry" ("content_type_id", "object_pk", "object_id", "object_repr", "action", "changes", "actor_id", "remote_addr", "timestamp", "additional_data") VALUES (4, '2018', 2018, 'Kurt Peek', … -
Wagtail: Adding an Orderable class to an Orderable class
I have a snippet that uses an Orderable class. I would like to add another Orderable class to the first Orderable. For example: models.py: @register_snippet class LocationHours(ClusterableModel): location = models.CharField( max_length=255, blank=True, help_text='Location for this set of Hours.' ) panels = [ MultiFieldPanel([ FieldPanel('location'), InlinePanel('location_hours'), ], "Hours"), ] class Hours(Orderable): snippet = ParentalKey('LocationHours', related_name='location_hours', on_delete=models.CASCADE) ... panels = [ ... InlinePanel('hours_override', label="Hours Overrides"), ] class HoursOverride(Orderable): orderable = ParentalKey('Hours', related_name='hours_override', on_delete=models.CASCADE) How would I go about doing this? -
Django 2.0.3 uploading files by models.FileField()
I am a beginner django developer. I am building my first serious application and I would like to use the mechanism of uploading files to the server. I have searched a large part of web, but I have not found an easy guide anywhere to deal with this issue in django2. Is there any experienced django ninja that could provide me with a comprehensive process to design this solution, from creating the model through the form and the apparently view? I tried to work with official documentation, but I can not help it. I will be very grateful! :D -
Automatically set the table name for a Django Model to the name of its class
Currently, most of my models look like this: class A(models.Model): # model attributes class Meta: db_table = 'A' class B(models.Model): # model attributes class Meta: db_table = 'B' Is there a way to do this automatically? I tried adding the meta class after defining the class, but because of how Django handles Meta classes for models, this doesn't work. Am I just stuck defining the Meta classes by hand? -
django - The current path ... didn't match any of these
http://127.0.0.1:8000/contextual/main/ works, but for some reason http://127.0.0.1:8000/contextual/main/create/ says the url does not exist, even if I included it. What's wrong? urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.urls import path, re_path, include urlpatterns = [ #url('admin/', admin.site.urls), #url(r'^user/', include('base.urls')), #url(r'^contextual/', include('base.urls')), #url(r'^home/', TemplateView.as_view(template_name='home.html'), name='home'), #url(r'^plots/', include('plots.urls')), # url(r'^welldata/', include('welldata.urls')), # eric's path('contextual/', include('eric_base.urls')) eric_base/urls.py from django.urls import re_path, include from eric_base import views as base_views app_name = 'eric_base' urlpatterns = [ re_path(r'^main/$', include([ re_path(r'^$', base_views.ContextualMainView.as_view(), name='main'), re_path(r'^create/$', base_views.WellCreateView.as_view(), name='create'), ])), ] views.py from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from . import models class ContextualMainView(TemplateView): template_name = 'contextual_main.html' class WellCreateView(CreateView): template_name = 'practice_add_well.html' model = models.WellInfo fields = '__all__' models.py from django.db import models # Create your models here. class WellInfo(models.Model): name = models.CharField(max_length=100) region_location = models.CharField(max_length=100) spud_date = models.CharField(max_length=100) well_bore = models.CharField(max_length=100) rig_name = models.CharField(max_length=100) status = models.CharField(max_length=100) -
Embedding a Browser in a Django App
Is it possible to embed a web browser into a django web application? I want to avoid users from being directed away from the app (ie new tabs, windows) when possible. iFrames would be perfect but because of CORS restrictions, won't work for most sites. I imagine that an embedded browser would circumvent this issue, and given that I can secure the browser from clickjacking etc, would be a fine alternative. I am open to any other ideas for showing third-party content in a web app too! Thanks in advance! -
How can I parse through a csv file within the DJANGO framework?
I am creating a scientific based website that does some calculation and plots. In order to do those calculations, I need to use some data that is in a csv file. The csv file has around 10,000 columns and 7 rows. Will I be able to do this with DJANGO? -
Getting "Content Security Policy" error in executing javascript with django?
I have inline javascript in my django webpage template that would dynamically fill a table. The html generated (after removing unnecessary parts) at the browser-end is the following: <html> <body> <article> <table> <tr> <td id="apple"></td> </tr> </table> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function (){ document.getElementById("apple").innerHTML = "AppleText"; }); </script> </article> </body> </html> I get the following error: Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src”). Source: document.addEventListener('DOMContentLo.... Initially I tried with document.onload = but got same error. How can I get rid of this error? And what does the error exactly mean in this context? UPDATE: However, if I run the above directly from an html file , then I don't get any error. Thanks in advance. -
Passwords won't get hashed and password input not working
I am currently trying to improve my knowledge in coding only by using class-based views. I am currently using Django 2.0.7 and I got a bit stuck. I was trying to extend the User model in order to create accounts. This was easily done. But I can't make the passwords to get hashed. Also, when I try to type, it will not be hidden even when using PasswordInput widget. Any advice ? #models.py class Client(User): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) phone = models.CharField(max_length=15, validators=[ RegexValidator( regex='^[0-9+]+', message='Not a valid phone number.', ), ]) address = models.CharField(max_length=255) class Meta: verbose_name = 'Client' #forms.py class ClientForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: fields = ('username', 'password', 'email', 'name', 'surname', 'phone', 'address') model = Client #views.py class HomeView(CreateView): template_name = 'home.html' model = Client form = ClientForm fields = ('username', 'password', 'email', 'name', 'surname', 'phone', 'address') success_url = reverse_lazy('home')