Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have variable Item name ,how to pass this variable to Url?
I have variable Item name ,how to pass this variable to Url ? html <!-- language: lang-html --> <form action="" method="POST" > {% csrf_token %} {{ field.errors }} <p style="font-size:30px" id="t">Chose The Item</p> {{ form.Item }} <a href="{% url 'ItemState' name=form.Item %}"> Done Form iclass ItemState1(forms.Form): Item = forms.ModelChoiceField(queryset=Product.objects.filter(state=1)) Url path('ItemState/<name>', ItemState, name='ItemState'), -
How to retrieve all values inside Django Postgres Array Field?
I used Django ArrayField with Postgres Database, I read the documentation however I cannot find a method to retreive all values saved inside the array field. After retrieved the record from database, I want to convert ArrayField type into python list type. This is their documentation -
Using an alternative model for password reset in Django
Due to the complexities of the application I'm creating, I ended up with three user models. One which is pretty much the normal User which is not used for anything other than admin and two others. I wrote my own set of auth backends to deal with it and it's working well. Now my problem is having a reset password system. Is there a way to use Django's reset password views while using a custom model? -
Cannot run python manage.py check
When I run said command I get python3 manage.py check Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "~/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "~/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "~/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "~/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "~/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "~/src/lavoro-fabio/places/models.py", line 2, in <module> from django.contrib.gis.db import models as g File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> import django.contrib.gis.db.models.functions # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/functions.py", line 4, in <module> from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> from django.contrib.gis import forms, gdal File "~/.local/lib/python3.6/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> from .fields import ( # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/forms/fields.py", line 2, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "~/.local/lib/python3.6/site-packages/django/contrib/gis/geos/__init__.py", line 5, in <module> from .collections import ( # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/geos/collections.py", line 9, in <module> from django.contrib.gis.geos.geometry import GEOSGeometry, … -
Class Attribute user input taking way
Hey, I'm doing a project and I want to know if this is a Good way to take user input from class attribute? class FileStudio(): # CLASS ATRRIBUTES def __init__(self, file_name='tod', file_type='.py', complete_file='tod.py'): # Accept Strings self.file_name = input('file name: ') self.file_type = input('file type: ') self.complete_file = self.file_name + self.file_type def act(self): return self.complete_file print(FileStudio().act()) -
Adding both Django_filter and pagination to FilterView class in django
I am using the django_filters lib to filter my list views, here is the filter form : class WorkerFilter(django_filters.FilterSet): class Meta: model = Worker fields = ['id', 'branch'] here is how the view looks : class WorkerListView(FilterView): model = Worker paginate_by = 1 filter_class = WorkerFilter template_name = 'erp_system/worker_list.html' filterset_fields = ['id', 'branch'] def get_queryset(self): new_context = Worker.objects.filter( active=True, ) return new_context And am using the form inside the HTML template this way : <form action="" method="get"> {{ filter.form.as_p}} <button class="btn btn-warning" type="submit"><span class="fa fa-search"></span> بحث </button> </form> And at the end of this HTML page I have the list and the paginator this way : {% for item in filter.qs %} {{item}}<br> {% endfor %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}"><button class="btn-success">الصفحة السابقة</button> </a> {% endif %} <span class="page-current"> صفحة رقم {{ page_obj.number }} من {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}"><button class="btn-success">الصفحة التالية</button> </a> {% endif %} </span> </div> {% endif %} The paginator part is not showing even when I used paginate_by = 1 to debug it and make sure that {% if is_paginated %} works -
Two button with two different action in the same form
I have a form that two button/input. Button1 save the page and refresh it. Button2 save save the page and go to another url. Button1 is working with type="submit" and then view.py takes the data, saves them and refresh the data. My problem is with Button2. I added it with formaction="{% url 'team_area:home' %}" and actually redirect me but the problem is that it doesn't save the data. Button1 still works properly. Is possible to have some sort of request.the_id_of_pressed_button to use in view.py? If can be helpful here are my files involved: modify_players.html <h1>AREA SQUADRA</h1> <form method="post" action=""> {% csrf_token %} <h2>Giocatori</h2> {{ player_formset.management_form }} {% for player_form in player_formset %} {% if forloop.last %} {% if not forloop.first %} <input type="submit" value="Salva" formaction="{% url 'team_area:home' %}"> {% endif %} <h5>Nuovo giocatore:</h5> {% endif %} {% for field in player_form %} {% if forloop.revcounter == 2 %} {{ field }} {% elif forloop.parentloop.last and forloop.last%} {% else %} {{ field.label_tag }} {{ field }} {% endif %} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiungi"> </form> views.py @login_required(login_url="/accounts/login/") def modify_players(request): if request.user.team is not None: PlayerFormSet = modelformset_factory(Player, form=PlayerForm, extra=1, can_delete=True,) if request.method == "POST": player_formset = … -
Why does queryset.iterator() show poor performance
# I am using postgresql # queryset run complex SQL joining 4 tables print(queryset.count()) # print 30000 # it takes 5 sec for i in queryset: print(i.arg) # it takes 10 sec for i in queryset.iterator(chunk_size=30000): print(i.arg) I simplify situation I have suffered like above. iterator() takes more time about 2 times. Of course, I understand that iterator() need more DB-side operation and more request like DECLARE, FETCH and CLOSE because it is using DB CURSOR internally(in practice I check for Django to emit these request through DB log). However, I don't think these additional operations will take that much time. It even will fetch all rows at one FETCH request since chunk_size is the same as the total number of rows. I am wondering if this situation is expected one or not. If it is expected, why it takes that much more time? -
Uncaught SyntaxError: Unexpected end of JSON input. Can't properly parse the info to JSON from the html
Getting the error when trying to open the modal with product details after products were queried with help of ajax Error itself: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at HTMLButtonElement.<anonymous> (scripts.js:54) at HTMLDocument.dispatch (jquery-3.3.1.js:5183) at HTMLDocument.elemData.handle (jquery-3.3.1.js:4991) To be clear: I have some filters, result of which is filtered in the python filter_items function then it uses JSONResponse to send it to the front-end in form of a dictionary(as_dict() function in Item model) were they are added to hidden input value. JS function takes that hidden input value and renders the results of filtering using the data from that input. Item Model which is queried with help of filter function: class Item(models.Model): ITEM_TYPES = ( ('UM', 'Umbrella'), ('SK', 'Skirt'), ('TR', 'Trousers'), ('OT', 'Other') ) BRANDS = ( ('VS', 'Versace'), ('SP', 'Supreme'), ('SI', 'Stone Island'), ('FP', 'Fred Perry'), ) title = models.CharField(max_length=256) image = models.ImageField(upload_to='img/') brand = models.CharField(max_length=256) type = models.CharField(choices=ITEM_TYPES, max_length=2) description = models.TextField(blank=True, null=True) season = models.TextField(blank=True, null=True) discount = models.FloatField(blank=True, null=True) price = models.FloatField() def __str__(self): return self.title + ' ' + self.type def as_dict(self): data = {"title": self.title, "image": self.image.url, "brand": self.brand, "type": self.type, "discount": self.discount, "price": self.price, "rus_representation": self.rus_representation, "description": self.description, "season": … -
Custom django admin actin doesn't called twice as built-in delete_selected
I try to make custom admin action with intermediate setting page. My action perfectly visible in admin interface for correct ModelAdmin. Intermediate page occurs on action. But my action doesn't called when I submit intermediate page from. I have made my action as a copy of built-in delete_selected action. action form in intermediate action html template: <form method="post">{% csrf_token %} <div> <input type="hidden" name="action" value="assign" /> <input type="hidden" name="post" value="yes" /> <input type="submit" value="Yes, I'm sure"/> <a class="button cancel-link">No, take me back</a> </div> </form> action function in admin.py: def assign(modeladmin, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) methodists = User.objects.filter(groups__name='methodologists') context = dict( ids=selected, ms= {str(x.id):x.username for x in methodists}, title="Set methodologiest", opts=Task._meta, app_label=Task._meta.app_label, media=modeladmin.media, action_checkbox_name="assign") return TemplateResponse(request, "admin/set_methologiest.html", context) -
Django - Showing two table data on a page
I have a table of lessons and exams. I list them by filtering according to the academicians. When I enter the content of the lesson, I see the data for the lesson. I want to see the exam information that belongs to the lesson on the lesson page and I cannot show it because there are different tables. Exams for each lesson: Mid-term and final exam. For example ; Mid-term exam, A, Final exam; Midterm exam for B, Final, Make-up exam. models.py def set_user_files_upload_path(instance, filename): return '/'.join([ 'users', 'user_%d' % instance.id, 'images', filename ]) class Lesson(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) lesson_name = models.CharField(verbose_name=_('Ders Adı'), max_length=150) lesson_content = models.TextField(verbose_name=_('Ders İçeriği'), blank=True) lesson_content_file = models.FileField( verbose_name=_('Ders İçeriği Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) lesson_notes = models.TextField(verbose_name=_('Ders Notu'), blank=True) lesson_notes_file = models.FileField( verbose_name=_('Ders Notu Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) def __str__(self): return '{lesson_name}'.format( lesson_name=self.lesson_name ) class Meta: verbose_name = 'Lesson' verbose_name_plural = 'Lesson' class Exam(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) exam_type = models.CharField(verbose_name=_('Sınav Türü'), max_length=50) exam_information = models.CharField( verbose_name=_('Sınav Hakkında Bilgi'), max_length=500) exam_file = models.FileField( verbose_name=_('Sınav Kağıdı Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) exam_answer_file = models.FileField( verbose_name=_('Cevap Anahtarı Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) def __str__(self): return '{lesson} - {exam_type}'.format( lesson=self.lesson.lesson_name, exam_type=self.exam_type ) class Meta: verbose_name = … -
localStorage.getItem return string, how to get an array and loop through it, also how to compare against existing data if the data id still there?
I have a page lists ads. each ad has a favorite icon. user can click on icon for every single ad to add it to the favorite list. The favorite list is stored on local storage(using cookies). I have made everything. the code works fine ( store selected data). I wrote a code to pull stored favorite ads once the page is loaded. I want to populate the favorite icons with previously favorited ads(data obtained from local storage). The icons has class (fa-star-o) while favorite icons should have class(fa-star). Hence, I need the following Two tasks: 1- I want to find the ads IDs stored on the local storage. Then loop through them and change the icons class based on them. 2- I want to compare existing IDs with current IDs come from the data base because every ads expires after 45 days and will be removed from the data base. How can I do that? The existing problem is the data came from local storage return as string. I did made the following code to make it an array: var stored_fav = JSON.parse("["+localStorage.getItem('SL_favourites')+"]"); The result is an array. However,when I loop through this array, I expect to have all … -
Django Infinite scroll using Django Paginate repeating the queryset
Intro: I am using the the below link to add infinite scroll to my project https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html below is the github code for that link https://github.com/sibtc/simple-infinite-scroll The link shows how to add infinite scroll to both function based views and class based views. I have added this to my function based view and it works perfect. The problem: I have 8 posts in my post-list which is a class-based view. After I add paginate_by = 3 I can only see 3 posts of the 8 posts. Everytime I scroll down these 3 posts keep repeating in an infinite loop My Views: class Postlist(SelectRelatedMixin, ListView): model = Post select_related = ('user', 'group') paginate_by = 3 context_object_name = 'post_list' template_name = 'posts/post_list.html' My Base.html: (I have the below files in JS folder they worked for my FBV) <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> {% block javascript %}{% endblock %} My post_list.html: <div class="col-md-8"> <div class="infinite-container"> {% for post in post_list %} <div class="infinite-item"> {% include "posts/_post.html" %} <!---This code is good----> </div> {% empty %} some code {% endfor %} </div> <div class="loading" style="display: none;"> Loading... </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ … -
Cannot access python shell from virtualenv and Django
I'm on Windows 10. I tried to install channels to use websockets with Django but it doesn't work. I got the following error : Failed building wheel for Twisted I have still not succeeded to install channels. But now I have a new problem, I can no anymore access Python shell from my virtual environment that I use for Django. (myproject) D:\Django\mysite>py manage.py shell Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\kevin\Envs\myproject\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'channels' I have no idea to solve my problem ... Someone could bring me help ? -
Python- Google NLP Api returns ssl.SSLEOFError: EOF occurred in violation of protocol
I'm working on a project using Python(3.6) in which I need to process too many files from a directory by using Google cloud natural language processing API, but after processing ~100 files it returns an error as: ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:852) [29/Dec/2018 13:27:33] "POST / HTTP/1.1" 500 17751 Here's from views.py: def nlp_text_manager(text_path, name): text = text_path # encoding = predict_encoding(text_path) # print('encoding is: {}'.format(encoding)) txt = Path(text_path).read_text(encoding='utf8') service = discovery.build('language', 'v1beta2', credentials=credentials) service_request = service.documents().analyzeSentiment( body={ 'document': { 'type': 'PLAIN_TEXT', 'content': txt } } ) response = service_request.execute() return response -
is there any elegant way to get data from 3 options?
I need to get title from data or instance or None actually there may not be any instance then None something like this title = data.get('title', None) but also try to get from instance if possible title = data.get('title', instance.title, None) -
Extract value from cookie
With _ga = request.COOKIES.get('_ga') I e.g. GA1.1.1432317817.1125843050. I now have to define everything behind GA1.1.in a new variable. However, GA1.1. could also be GA1.2. etc. The dots are consistent. How would you extract it? -
Does Django's csrf_exempt decorator remove all POST data?
I have a Django view which returns a list of objects, or allows you to create one if you POST... @csrf_exempt def quantities(request): if request.method == "POST": kwargs = {**request.POST} print(request.POST) quantity = Quantity.objects.create(**kwargs) return JsonResponse({"quantity": f"/quantities/{quantity.id}/"}) return JsonResponse([], safe=False) If it gets a GET request it returns a list of quantities (code not shown), which works fine, and if it gets a POST request it uses POST data to create a new quantity. (I'm aware DRF does all this for you, but for my first API I wanted to try doing it manually - you just understand it better that way.) Anyway in my test, I use requests to check this works... response = requests.post( self.live_server_url + f"/quantities/", data={ "name": "Height", "units": "m", "description": "Human Height" } ) This doesn't work - it doesn't pass any data. That print statement in the view above just prints <QueryDict: {}>. For some reason the POST data that I put in the request has gone from the request by the time it passes through all the middleware and gets to the view. The only thing I can think of is that the @csrf_exempt decorator is removing POST data, though I can't imagine … -
Error while using ckeditor with django version 2.x
Before marking this question duplicate or anything please be informed I researched stack overflow and ckeditor documentation and configured accordingly. first i install ckeditor using pip install django-ckeditor then i configured my settings.py as below # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Static files (CSS, JavaScript, Images) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor" # CKEditor settings CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' # This ensures you have all toolbar icons CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } Then i configured my urls.py (project's url) as below url(r'^ckeditor/', include('ckeditor_uploader.urls')) Then I ran command collect static ckeditor statics are collected in right location defined in settings which is /static/ckeditor/ckeditor After that I imported and used ckeditor richtextfield in my model from django.db import models from ckeditor.fields import RichTextField class Post(models.Model): post = models.RichTextField() While makemigrations i am getting the following error AttributeError: module 'django.db.models' has no attribute 'RichTextField' -
Could not connect to postgres server in a docker from a dockerized app
I would like to run a dockerized Django app with a dockerized postgres. I run the dockerized Django app by using: docker run --rm --env-file /path/to/variables -d -p 8000:8000 django_app:test I run a dockerized postgres by using: docker run --rm -d --env-file /path/to/secrets/variables -p 5432:5432 \ -v "$PWD/my-postgres.conf":/etc/postgresql/postgresql.conf \ --mount src=/path/to/db/data,dst=/var/lib/postgresql/data,type=bind \ postgres:alpine -c 'config_file=/etc/postgresql/postgresql.conf' my postgres config is the default config that is suggested in the postgres docker container documentation. It is essentially a config file that contains listen_addresses = '*' I use the same environment variables for both containers: DJANGO_SETTINGS_MODULE=settings.module PROJECT_KEY=xxyyzzabcdefg DB_ENGINE=django.db.backends.postgresql POSTGRES_DB=db_name POSTGRES_USER=db_user POSTGRES_PASSWORD=verydifficultpassword POSTGRES_HOST=localhost # I've also tried to use 0.0.0.0 POSTGRES_PORT=5432 My Django settings module for the database is: DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE'), 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PORT': os.environ.get('POSTGRES_PORT') } } However, I keep on getting: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? The Dockerfiles for my django app looks like: FROM python:alpine3.7 COPY --from=installer /app /app # required for postgres COPY --from=installer /usr/lib /usr/lib COPY --from=installer /usr/local/bin /usr/local/bin COPY --from=installer /usr/local/lib /usr/local/lib ARG SETTINGS_MODULE WORKDIR /app ENTRYPOINT python manage.py migrate &&\ python … -
Example of how to Subclass Column() in Django-tables2
Can anyone point me to an example of how to subclass the base Column() in django-tables2 please. By default the django-tables2 base Column() attrs supports 'th', 'td', 'cell' and 'a' as detailed in the documentation, which also states that this can be extended by subclasses to allow arbitrary HTML attributes to be added to the output. What I want to try and do, which may be either ambitious or flat out stupid and wrong, is to add a 'ul' attribute (and subsequently 'li' attributes) so that I can render a dropdown menu in a cell. My thinking is to have an options button on each row of my table that provides the user with the various options of 'delete', 'copy', 'archive' etc via a css or js dropdown menu. -
Django max_upload_size get's ignored
i have this code but for some reasone the file size gets ignored, even if i set this directly to ('max_upload_size', 5242880) at formatChecker.py the vaule seems to get ignored after the upload has happend. formatChecker.py from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ class ContentTypeRestrictedFileField(FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types', []) self.max_upload_size = kwargs.pop('max_upload_size', []) super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file._size > self.max_upload_size: raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % ( filesizeformat(self.max_upload_size), filesizeformat(file._size))) else: raise forms.ValidationError(_('Filetype not supported.')) except AttributeError: pass return data models.py ... class Post(models.Model): postattachment = ContentTypeRestrictedFileField( blank=True, null=True, upload_to=get_file_path_user_uploads, max_upload_size=5242880, content_types=['application/pdf', 'application/zip', 'application/x-rar-compressed', 'application/x-tar', 'image/gif', 'image/jpeg', 'image/png', 'image/svg+xml', ] ) ... Any idea why that problem occurs? Did i forgot something here? Thanks in advance -
Why do we have to include staff and admin fields in custom user django model?
Let's say I am building a social networking website that has nothing do with admin and superuser. But I still have to include these fields while making custom user model. This is going to be a simple model that has user's profile information not that user is admin or superuser. Can anyone explain why do we always need these fields to be there. Can we get rid of them and still create a Custom user model or do we always need them. -
Don't upload and load and show Picture profile in Django
Hellow i use Django freamwork Python. in model i user AbstractBaseUser. i use python3 in my website user can choice picture for that profile. but don't load and upload picture in my model: Model: class CustomUser(AbstractBaseUser , PermissionsMixin): username = models.CharField(max_length = 200 , unique = True) email = models.EmailField() age = models.IntegerField(null=True , blank=True) number = models.IntegerField(default=1) country = models.CharField(max_length = 200) city = models.CharField(max_length = 200) image = models.ImageField(upload_to = 'ImageProfile' , default='ImageProfile/none.jpg') privilege = models.IntegerField(default= 0) is_staff = models.BooleanField(default = False) REQUIRED_FIELDS = ['email'] USERNAME_FIELD = 'username' objects = CustomUserManager() def get_short_name(self): return self.username def natural_key(self): return self.username def __str__(self): return self.username Form: from django import forms from django.contrib.auth import get_user_model class Register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email' , 'age' , 'image') def clean_username(self): User = get_user_model() username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save … -
How to add link to npm package to a django template using the script tag when path is always converted to a url
I am trying to add a link to a folder in the npm_modules folder located in the root of my Django project to one of my templates. However, when attempting to do so, the path typed in is simply appended to the current url and is treated as a link. Since my folder is not there, it is not loaded and my javascript crashes. Since it is best practice to keep the npm_modules folder in root, how do I go about referencing folders within it inside my templates? <script src="\node_modules\angular-file-upload\dist\angular-file- upload.min.js" type="text/javascript"></script>