Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fetch file of any format from postgre sql and show in template using django
enter image description here class manuals(models.Model): topic = models.CharField(max_length=100) semester = models.CharField(max_length=100) course = models.CharField(max_length=100) format = models.CharField(max_length=100) word = models.FileField(max_length=700,upload_to='media') Please guide me that how i can fetch my word file from this table and show in my template -
Django : Why doesn't django translate the words
This is my models. I have used gettext_lazy because it is models.py file from django.utils.translation import gettext_lazy as _ class User(AbstractUser): email = models.EmailField(_('email address'),unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("username","first_name","last_name") This is my setting.py file.I have added only LANGUAGE_CODE = 'fr' LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) # Translation local path LOCALE_PATHS = ( os.path.join(os.path.dirname(BASE_DIR), 'locale'), ) This is done after the following process python manage.py makemessages -l 'fr' Then a mo file is created and I add my translation there but got no translation.Then after writing the code below a po file is created and contains all the translation in pdf file python manage.py compilemessages -
ImportError: cannot import name 'admin' from 'django.contrib
What is the problem that i can't solve?I have everything done in settings.py, i checked if admin is installed.This problem has only appeared today,i didn't have this problem before.Can somebody help please? Traceback (most recent call last): File "C:\Software Files\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Software Files\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Software Files\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\apps\config.py", line 136, in create import_module(entry) File "C:\Software Files\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.admin' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Software Files\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Software Files\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line … -
request.data not always a queryDict
Using a PATCH request on a RetrieveUpdateDestroyAPIView I receive the following in RetrieveUpdateDestroyAPIView.update when i run print(request.data): {'myVar': ''} when running automated tests using django rest framework's APIClient I get this: <QueryDict: {'myVar': ['']}> Why is this different? What can i do to ensure consistency between my environments of test and dev? -
Django Many=True doesn't work with to_representation
I have following situation. I need a PATCH for my device model to change the supplier. When a user set's parameter device on "ALL", all the devices need to be changed. Everything works but my serialiser doesn't return my supplier as validated data when the user wants ALL the devices to be changed because it's a many=true field. This is my patch: def patch(self, request, site_pk): """ PATCH the device's supplier info of the site. """ all_device_token = False if request.data.get("device") == "ALL": all_device_token = True arguments = {} else: device_pk = request.data.get("device") arguments = {"id": device_pk} devices = Device.objects.filter(site_id=site_pk, **arguments).all() if not devices.exists(): raise PermissionDenied("The device does not belong to the site.") if all_device_token: serializer_class = self.get_serializer_class() serializer = serializer_class( devices, many=True, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) new_supplier = get_object_or_404(Supplier, pk=request.data.get("supplier")) for device in devices: device.supplier_id = new_supplier.pk device.save() else: device = devices.first() serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True,) serializer.is_valid(raise_exception=True) if "supplier" in self.request.data: new_supplier = serializer.validated_data["supplier"] device.supplier_id = new_supplier.pk device.save() return Response(serializer.data, status=status.HTTP_200_OK) Serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): site = serializers.SerializerMethodField() owner = serializers.SerializerMethodField() country = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "site", "owner", "country", "disk_space", "supplier", ] def to_representation(self, device): data = super().to_representation(device) if not device.supplier: … -
How to Store a Specific blank fields of user who is already Exist in the models
Views.py This my code as you can see in views.py file i am deriving the fields using request object I could have used form.save() but i am getting an error. I want to store this field data to that user model User is already Exist i had Used UserCreationForm from django.shortcuts import render from django.views.generic import TemplateView,CreateView from auctions.models import User from auctions import forms from django.urls import reverse from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.contrib.auth import settings from django.contrib import messages # Create your views here. # class HomePage(TemplateView): template_name = 'index.html' form_class = forms.ProfileSetupForm # success_url = reverse_lazy('auctions:profile_update') # template_name = 'index.html' users =User.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = self.users context['form']=forms.ProfileSetupForm() return context def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): address= request.POST['address'] mobile = request.POST['mobile'] city =request.POST['city'] state = request.POST['state'] birth_date =request.POST['birth_date'] image=request.FILES['image'] # file= request.FILES['image'] user_name=request.POST['user_name'] pincode = request.POST['pincode'] print("abc",pincode,user_name,image) return HttpResponseRedirect('') class ThanksPage(TemplateView): template_name = 'thanks.html' forms.py Here in forms.py file two fields first_name and last_name comes from auth.models.User i assume class ProfileSetupForm(forms.ModelForm): # def save(self, commit=True): # user= models.User() class Meta(): fields=('image','first_name','last_name','address','mobile','birth_date','city','state','pincode') model=models.User # widgets={ # # } models.py Here auth.models.User are inherited so few fields … -
How to change timezone celery in models.py of django
i create a periodic tasks to to something in models.py in django , but when i run it run on UTC timezone , how can i change timezone class TimeSend(models.Model): user = models.ForeignKey(UserMail,on_delete=models.CASCADE,null=True) hour = models.CharField(max_length=10,blank=True,null=True) minute = models.CharField(max_length=10,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return self.user.user_mail def set_periodic_task(self,task_name): schedule = self.get_or_create_crontab() PeriodicTask.objects.create( crontab=schedule, name=f'{self.user.user_mail}-{self.user.id}', task=task_name, kwargs=json.dumps({ 'recepient': self.user.user_mail, }) ) def get_or_create_crontab(self): schedule, created = CrontabSchedule.objects.get_or_create( minute=self.minute, hour=self.hour, day_of_week='*', day_of_month='*', ) return schedule in settings.py , i already change the timezone TIME_ZONE = 'Asia/Bangkok' USE_I18N = True USE_L10N = True USE_TZ = True CELERY_TIMEZONE = 'Asia/Bangkok' CELERY_ENABLE_UTC = False -
JS TypeError when not waiting for the document to be ready [duplicate]
I am using Django and running a basic JS command for testing and manage to make it work if I wrap it such that the command start only after the whole document is ready or if I wrap the command between <script> tag inside the html directly, but not if I use a JS block tag and call the JS command. Why ? In more detail, say I have an html template and inside that template I have the js tag: {% block js %} <script src="{% static 'app/js/basic.js' %}"></script> {% endblock %} inside basic.js, this works: document.addEventListener('DOMContentLoaded', function(){ document.getElementById('js-table').style.height = "50px"; }); but this doesn't: document.getElementById('js-table').style.height = "50px"; and returns TypeError: document.getElementById(...) is null if I include a console.log, it prints correctly so the call to basic.js file works if I add the script below directly in the html it works: <script> document.getElementById('js-table').style.height = "50px"; </script> -
Undefined variable error during splitting views.py into modules - Django
My codes in views.py becomes larger day by day, and now I want to split it into modules. But I have trouble with variables. Problem is in that I don't where should I declare variables, or import built-in modules: in my custom module, or views.py. Here is my codes: views.py: @login_required(login_url='sign_in') def result(request): find_by_fives() context = { 'last_uploaded': last_uploaded, 'words_count': words_count, 'characters_count': characters_count } return render(request, 'result.html', context) find_by_fives.py(is my custom module): import glob from .models import OriginalDocument from django.shortcuts import render def find_by_fives(): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) path = 'static/other_documents/doc*.txt' files = glob.glob(path) Error: NameError: name 'last_uploaded' is not defined Note: This is not my entire view, all I want to know is just where should I declare context, variables, and imports. -
Best way to access reverse relation's attributes
I have these three models : MenuItem, Subs and Pizzas Both Subs and Pizzas have a foreign relation on MenuItem, for example : menuItem = models.ForeignKey('MenuItem', related_name='pizza', on_delete=models.CASCADE) Moreover, both Subs and Pizzas have a @property price() property. I would like to access this price property from the MenuItem, in order to be able to compute the price of an order. What would be the best way to implement this ? I have thought about defining a price() property in MenuItem, but then how do I access the reverse relation in order to retrieve the price, considering there may be multiple reverse relations ? Do I need to check every possible reverse relations, to find one that is not Null, and then access the price ? Thank you -
Authntication finally failed error on AWS ElasticSearch Service
I'm trying to upgrade a Django application from using AWS ElasticSearch 2.3 to 7.4 (and upgrade the Django packages at the same time). I have it running locally, but when I attempt to run with AWS ElasticSearch7.4 I get the following Traceback Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/henry/Documents/Sites/Development/autumna2/autumna/src/search/views.py", line 169, in name_suggestions field='name_suggestion', File "/home/henry/Documents/Sites/Development/autumna2/autumna/src/search/views.py", line 129, in search_suggestions data = sqs.execute(ignore_cache=True).to_dict()['hits']['hits'] File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch_dsl/search.py", line 698, in execute **self._params File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch/client/utils.py", line 92, in _wrapped return func(*args, params=params, headers=headers, **kwargs) File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch/client/__init__.py", line 1627, in search body=body, File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch/transport.py", line 362, in perform_request timeout=timeout, File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 248, in perform_request self._raise_error(response.status, raw_data) File "/home/henry/Documents/Sites/Development/autumna2/env/lib/python3.6/site-packages/elasticsearch/connection/base.py", line 244, in _raise_error status_code, error_message, additional_info elasticsearch.exceptions.AuthenticationException: AuthenticationException(401, 'Authentication finally failed') I am using django-elasticsearch-dsl so I've simply declared the host within settings.py (this is a straight replacement of what I had before) with ELASTICSEARCH_DSL = { 'default': { 'hosts': 'https://search-elastic7-zoqohjbiedz2ozmthfi4a3ccm4.eu-west-2.es.amazonaws.com', # I've changed this string }, } I'm using IAM authentication and I've given the IAM account full access to all my ElasticSearch … -
how do i get specific field in a form?
So what I'm trying to do is, I get long text from a user via the modelform I've created. Then in my models, I want to save the first sentence of the text. In order to do this, I believe I have to get the data(long text) from the form, and use a function to leave nothing but the first sentence. But I have as a beginner in Django, I have no idea on how to get an individual field from a form. So this is my codes: models.py class InputArticle(models.Model): objects = models.Manager() authuser = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'dansang', null=True, default=None) title = models.CharField(max_length=100) contents = models.TextField(max_length=100000) first_sentence = models.CharField(max_length=100) def __str__(self): return self.title forms.py class InputArticleForm(forms.ModelForm): class Meta: model=InputArticle fields=['title', 'contents'] I want to later display the title, contents, and first sentence in a separate page. I very much appreciate your help :) -
managed=False ignored and default_permissions=() bugged?
Django : 2.2.9 Python : 3.7 I try to create a dummy model to store my custom permissions. I don't want Django to create a table in my database nor create default permissions. My model look like this : class Permissions(models.Model): class Meta: managed = False, default_permissions = (), permissions = ( ("approbations_write", "Modifier/Emettre les approbations"), ("config_read_saufmdp", "Lecture configuration applicative avec mot de passe masqués"), ("config_write", "Modification configuratin applicative"), ("config_deploy_read", "Lecture configuration interne DEPLOY"), ("config_deploy_write", "Modification configuration interne DEPLOY"), ("ssh_write", "Effectuer un échange de clé SSH"), ("historique_read_normal", "Lecture de l'histrique sans conf DEPLOY interne"), ("historique_read_full", "Lecture de l'histrique sans restrictions"), ("releases_write", "Purge des releases potentiellement bloquées"), ) I use makemigrations and my options are in the migration file : migrations.CreateModel( name='Permissions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'permissions': (('approbations_write', 'Modifier/Emettre les approbations'), ('config_read_saufmdp', 'Lecture configuration applicative avec mot de passe masqués'), ('config_write', 'Modification configuratin applicative'), ('config_deploy_read', 'Lecture configuration interne DEPLOY'), ('config_deploy_write', 'Modification configuration interne DEPLOY'), ('ssh_write', 'Effectuer un échange de clé SSH'), ('historique_read_normal', "Lecture de l'histrique sans conf DEPLOY interne"), ('historique_read_full', "Lecture de l'histrique sans restrictions"), ('releases_write', 'Purge des releases potentiellement bloquées')), 'managed': (False,), 'default_permissions': ((),), }, ), Still when I do the migrate, Django create the table … -
xhtml2pdf how manage the class attribute?
In my django project i have to create a pdf file from my html. For this purpose i use xhtml2pdf and in my html section i write: <style type="text/css"> body {margin:0;padding:0;background-color:#FAFAFA;font:8pt "Tahoma";} * {box-sizing:border-box;-moz-box-sizing:border-box;} th, td {border:1px solid black;border-collapse:collapse;} @page { size: a4 portrait; margin: 1cm auto; padding: 1cm; margin: 1cm auto; border: 1px #D3D3D3 solid; border-radius: 5px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); } table { -pdf-keep-in-frame-mode: shrink; border:1px solid black; border-collapse:collapse; } p {margin:0;padding:0;line-height:1.4em} .column-50-left {width:49.5%;display:inline-block;vertical-align:top;padding-right:15px} .column-50-right {width:49.5%;display:inline-block;vertical-align:top;padding-left:15px} .invoice {font-size:6pt} .invoice td {height:50px;vertical-align:top;padding:5px;} .destinatario td {height:120px;vertical-align:top;padding:5px;font-size:6pt} .description th {height: 30px} .description td {height: 50px} .top-10 {margin-top:10px} .top-15 {margin-top:15px} .top-20 {margin-top:20px} .padding-top-4 {padding-top:4px} .padding-bottom-15 {padding-bottom:15px} .padding-bottom-30 {padding-bottom:30px} .border-top {border-top:1px solid #000000} </style> but when i use my attributes on elements for apply the styles nothing appen for example: <table style="width:80%" class="invoice top-10"> or <div class="border-top top-10 invoice padding-top-4 padding-bottom-15"><p>PORTO / <em>Freight</em></p></div> How can i apply my class style to my pdf output in xhtml2pdf? So many thanks in advance -
Django: show selected item detail after selected jinja templates
I use Django and his templates (jinja). I have list view and detail view. I would like, that after selecting the item in list view, I populate the detail view with it's content. Inside content item, there is all necessary data. Is there more elegant way to use power of jinja templates to do this? -
How to upgrade Django Q and Django without clearing the queue?
When deploying the project after upgrading Django and Django-Q. I got the following log. Is there a way to avoid that error but still keep the tasks running in the queue to avoid downtime? 08:59:03 [Q] INFO Process-1:440 pushing tasks at 12192 Process Process-1:440: Traceback (most recent call last): File “/usr/lib/python3.6/multiprocessing/process.py”, line 258, in _bootstrap self.run() File “/usr/lib/python3.6/multiprocessing/process.py”, line 93, in run self._target(*self._args, **self._kwargs) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/cluster.py”, line 340, in pusher task = SignedPackage.loads(task[1]) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/signing.py”, line 31, in loads serializer=PickleSerializer) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/core_signing.py”, line 36, in loads return serializer().loads(data) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/signing.py”, line 44, in loads return pickle.loads(data) AttributeError: Can’t get attribute ‘simple_class_factory’ on <module ‘django.db.models.base’ from ‘/home/ubuntu/py34env/lib/python3.6/site-packages/django/db/models/base.py’> -
ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later I met with this problem at the django project, mismatching version for the sqlite3 and the django. this occurs at the centos7 env, and I also want a convenient solution that works in the container env. -
Including ffmpeg in Django project
I am making a very simple Django app (it's a test for non-Django course) and I need to analyse a mp3 file in there, so I try to turn it into wav with this: sound = AudioSegment.from_mp3('upload/' + filename) sound.export('upload/wavfile', format="wav") rate, data = wav.read('upload/wavfile') I have installed ffmpeg by pip install ffmpeg in venv terminal, since I want to my code to run not only on my machine. The ffmpeg and ffprobe folders have appeared in /venv/lib/python3.7/site-packages/ however when I run my server I get the warning: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning) and when I load file in web page it throws [Errno 2] No such file or directory: 'ffprobe': 'ffprobe' at the first line of the code above. I would really appreciate any help with how I can use ffmpeg in my app or other ways to handle my mp3 file. -
Overriding Django Admin get_queryset with raw() results in DatabaseError
To speed up my admin page, I've decided to override my get_queryset() with a raw query however it results in: Database error: Something’s wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user. Is there some step I'm missing?. I've already confirmed that the query works in PSQL so I don't see what's going wrong. I've tried cutting it down to just the following but it still errors out. def get_queryset(self, request): return MyObject.objects.raw('SELECT * FROM myapp_myobject') -
Python Django - How to Pass HTTPS URL as function parameter in manage.py shell
I'm trying to call a function insert_db in the python shell. insert_db requires an https url to call some other functions. In Terminal in my Django python project folder, I type './manage.py shell' to get the python shell for Django going. After that: from send_values.api.send_to_db import insert_db insert_db('https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json') I'm getting the following error: requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h? send_to_db.py code: # python send_to_db.py 'https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json' from ..models import Correlations from .lambda_async_s3_uri import filter_complete import sys def insert_db(args): print(args) table_values = filter_complete(args) for value_set in table_values: new_value_set = Correlations.objects.create(value_set) # new_value_set = Correlations.objects.create(experimentName=item[3], colLabel=item[5], rowLabel=item[4], rowNum=item[0], colNum=item[1], cor=item[2]) new_value_set.save() def main(args): insert_db(args) if __name__ == '__main__': main(sys.argv[1:]) Any help is appreciated. Please let me know if you need more information. Notes: 1) I know the insert_db function works like it is supposed to (taking the url, downloading some files, parsing through them for some data, and making some calculations from that data). Before making this Django project, in a pure Python project, I used to call it like this: python send_to_db.py 'https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json' At that earlier point, instead of trying to add it to the Django database, I was just printing the values insert_db would calculate (which … -
django: api call view: on redirect the request method does not change to GET
I have viewA() and viewB() I am sending a POST request toviewB()` using curl curl --location --request POST 'http://127.0.0.1:8000/viewB' \ --header 'Content-Type: application/json' \ --data-raw '{ "item" : "new" }' inside viewB() i have a redirect(..to viewA) after redirected to viewA() when i debug inside viewA() i see that the request.method as POST instead of GET Why redirect() does not change request.method to GET -
Google Docs gives No Preview available in iframe Django
I have implemented previewing documents in iframe using google docs. But when executed it gives no preview available. Can someone help with it? Do I have to enable anything in settings.py in Django? -
Rediect to view or URL from Model in Dajngo
When user tries with brute-force attack with more than 10 unsuccessful attempts (in login page), then I am locking user. So part of this as shown in below code, I am moving user from login view to '/login_lock/' view as shown in urls. But not sure for some reasons I am unable to move to /login_lock/ and re-iterates login page/view with invalid login credentials Validation Error. Could you please help me how can I move to login_lock view with a call from user_login_failed_callback (this call in models.py). @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs): username = credentials['username'] user = User.objects.get(username=username) profile = user.get_profile() if profile.failed_login_count <= 9: profile.failed_login_count = profile.failed_login_count+1 profile.last_login_attempt_date_time = timezone.now() profile.save() else: return HttpResponseRedirect('/login_lock/') url(r'^login/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login.html'}), url(r'^login_lock/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login_lock.html'}), -
django template custom filter
I'm fairly new to django and I believe this is django template related question. I've got a project template where there is a certain value, namely {{ tenant_name }} which tells the tenant name. I've used for loop to find out all tenant names which works fine. How ever, all of the tenants have units under them and when I try to display units per tenant with for loop it loops all units to all tenants which is not what I want to do. note: self.tenant can't be used in this case as the user doesn't have a tenant yet. I've tried to solve this using custom filter, by registering it and loading it to the template and then filtering like so: {{ tenant_name|filter_units }}, however this doesn't seem to work for some reason. My question is this: is it possible to extract tenant_name from the template to the filter, use that value in the filter to search for units and return it back to the template? If so, could you possibly show me how? If it is not possible, is there a better way to accomplish this? Thanks in advance. -
Django: Error in creating custom fields in Django
I tried this on my model: class NameField(models.CharField): def __init__(self, *args, **kwargs): super(NameField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return str(value).lower() class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.NameField(validators=[name_regex], max_length=100) postalcode = models.IntegerField(unique=True) class Meta: unique_together = ["state", "name"] Now I am getting error as: AttributeError: module 'django.db.models' has no attribute 'NameField' How to resolve this error?