Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Non ASCII characters not supported in django url
I am working on a django project that has to do with some non ASCII characters(Non English Characters). The characters are rendered well on page but not well rendered in url form. if i mouse hover the url link on the page, its showing the url in appropriate form, something like this: http://www.example.com/Mehtar-Lām-مهترلام but once i clicked on the url, it changes to something like this: http://www.example.com/Mehtar-L%C4%81m-%D9%85%D9%87%D8%AA%D8%B1%D9%84%D8%A7%D9%85 i am using django 1.10, here is the some of the snippet code: Models.py class City(models.Model): name = models.CharField(max_length=200) country = models.ForeignKey('Country', on_delete=models.DO_NOTHING) # class Meta: # ordering = ['name'] def __str__(self): return u'%s %s' % (self.name, self.country.name) def _get_slug(self): return slugify(self.name, allow_unicode=True) slug = property(_get_slug) Then i build the url on template using: <a href="{% url 'display' city.slug %}">{{ city.name }}</a> and my urls.py is like this: url(r'^(?P<country_slug>[\w-]+)$',city_home, name="display"), Please, what am i missing or need to set up Thanks in advance. -
Re: Finding the live URL in Codenvy for python and django
I am trying to create a web app using Codenvy using python and the Django framework, but i cannot seem to get anything running. I have create the basic template of a webapp, and have pressed both the "run button" as well as the following in the terminal "cd /projects/hello && python manage.py runserver" Does anyone have any ideas or am i barking up the wrong tree here . Many thanks, -
Django points to the wrong version of Postgres
I downgraded Postgres.app from 9.6 to 9.5 by moving the Postgres.app desktop app. I updated the database by doing sudo /usr/libexec/locate.updatedb And it looks like it is initiating database from the right directory. /Applications/Postgres.app/Contents/Versions/9.5/bin/initdb /Applications/Postgres.app/Contents/Versions/9.5/share/doc/postgresql/html/app-initdb.html /Applications/Postgres.app/Contents/Versions/9.5/share/man/man1/initdb.1 However, when I am trying to do a migration in my Django app, it looks like the path is still point to the 9.6 version of Postgress Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/tenant_schemas/models.py", line 4, in <module> from tenant_schemas.postgresql_backend.base import _check_schema_name File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/tenant_schemas/postgresql_backend/base.py", line 14, in <module> import psycopg2 File "/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: /Applications/Postgres.app/Contents/Versions/9.6/lib/libpq.5.dylib Referenced from: /Users/me/Desktop/myapp/venv/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: image not found -
How to solve [Errno 11] Resource temporarily unavailable using uwsgi + nginx
I am using uwsgi with net.core.somaxconn = 1024, net.core.netdev_max_backlog=1000 setting, I got resource temporarily unavailable issue. How to resolve this issue ? df -h Filesystem Size Used Avail Use% Mounted on /dev/xvda1 7.8G 2.1G 5.6G 28% / devtmpfs 1.9G 12K 1.9G 1% /dev tmpfs 1.9G 16K 1.9G 1% /dev/shm -
Haanga include template with parameters
In Django you should be able to do something like this: {% include "fragments/threadComment.html" with post.comments as comment only %} But we are using Haanga witch it based on Django and i was told to follow Django documentation when i got some problems with Haanga but i cant get this part to work. Is this even supported in Haanga? I get this error: Fatal error: Uncaught Haanga_Compiler_Exception: Haanga_Compiler_Exception: Unexpected T_WITH(with) in /var/www/project/templates//pages/postThread.html:5 in /var/www/project/framework/lib/Haanga/Compiler/Parser.php:155 Stack trace: #0 /var/www/project/framework/lib/Haanga/Compiler/Parser.php(2253): Haanga_Compiler_Parser->Error('Unexpected T_WI...') #1 /var/www/project/framework/lib/Haanga/Compiler/Parser.php(2364): Haanga_Compiler_Parser->yy_syntax_error(36, 'with') #2 /var/www/project/framework/lib/Haanga/Compiler/Tokenizer.php(570): Haanga_Compiler_Parser->doParse(36, 'with') #3 /var/www/project/framework/lib/Haanga/Compiler.php(256): Haanga_Compiler_Tokenizer::init('{% extends "bas...', Object(Haanga_Compiler_Runtime), '/var/www/projec...') #4 /var/www/project/framework/lib/Haanga/Compiler.php(356): Haanga_Compiler->compile('{% extends "bas...', '/var/www/projec...', '/var/www/projec...') #5 /var/www/project/framework/lib/Haanga.php(378): Haanga_Compiler->compile_file('/var/www/projec...', false, Array) #6 /var/www in /var/www/project/framework/lib/Haanga/Compiler.php on line 399 -
Overring menu blocks in Django DTL?
I got a navbar that will have four links, {% block navbar %} <div id="navbar"> <a href="">Link 1</a> <a href="">Link 2</a> <a href="">Link 3</a> <a href="">Link 4</a> </div> {% endblock %} A class='current' will define the current active page like <a href="" class='current'>Link 4</a> My question is overriding the block navbar on each of the 4 links the best way to it in Django template language so that each link will have a corresponding class 'current'? -
Issues setting up Virtualenv and Virtualenvwrapper
I'm trying to install virtualenv and virtualenvwrapper so that I can do some django work. I'm not exactly sure where the issue is stemming from. I currently have installed Jupyter Notebook and installed a lot of python files though it (python 3+ I believe), so when I did pip install virtualevnwrapper, the location of the shell file was in C:/Users/'Andy Renz'/Anaconda3/Scripts/virtualenvwrapper.sh. I account for this in changing by .bashrc file, by including: export WORKON_HOME=$HOME/.virtualenvs source C:/Users/'Andy Renz'/Anaconda3/Scripts/virtualenvwrapper.sh When I run source ~/.bashrc in my shell, I get the following: bash: /usr/bin/python: No such file or directory virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could no import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and the PATH is set properly. I think this means python isn't where it is supposed to be. Virtualenv references python 2+ I believe which leads me to believe my python 2 is somewhere odd. I do have it, not downloaded from Jupyter. How do I account for this and proceed forward? -
Writing multiple nested objects in Django REST Framework
I followed the instructions from the documentation but can't figure out how to make it work. My goal: whenever creating a playlist, you always have to include songs. class SongSerializer(serializers.ModelSerializer): name = serializers.CharField() class Meta: model = Song fields = ['name'] class PlaylistSerializer(serializers.ModelSerializer): songs = SongSerializer(many=True) class Meta: model = Playlist fields = ('name', 'songs') def create(self, validated_data): songs_data = validated_data.pop('songs') playlist = Playlist.objects.create(**validated_data) for song_data in songs_data: Song.objects.create(playlist=playlist, **song_data) return playlist Problem: When I open the serialiser, it says: 'Lists are not currently supported in HTML input.' I tried creating a custom HTML form in a template but couldn't get it to work, any tips on this? Also, when I try to use the API Raw Data (JSON) input it says "Invalid data. Expected dictionary, but got str." My input: { "name": "test", "songs": ["song1", "song2"] } Any help would be so nice :) -
django.template.exceptions.TemplateSyntaxError: 'static' is not a registered tag library. Must be one of:
I am new to django.I have created project in django.while running it I am getting following error django.template.exceptions.TemplateSyntaxError: 'static' is not a registered tag library. Must be one of: Here is my index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href ="{% url 'polls:detail' question.id %}">{{question.question_text}}</a></li> {% endfor %} </ul> {% else %} <p> No polls are available</p> {% endif %} I followed steps from django doc. -
Remove title from TabularInline in admin
When I create a TabularInline in my Django's admin panel, it displays a title per record. How can I change this title? How can I delete this title? I include a screenshot below. The title I am referring to is here ExportLookupTableElement object. The lines without that title are the extra fields to add new ones. I want the entire table to look like this. -
@csrf_exempt not working for rest api
i am trying to exempt csrf mechanism for a view which handles rest api post request but i am still getting csrf verification error failed. I tried the solution given in this question and it did not work. //sendmoney @api_view(["POST"]) @authentication_classes([TokenAuthentication,]) @permission_classes([IsAuthenticated, ]) @csrf_exempt def send_money(request): if request.method == "POST": data = JSONParser().parse(request) success = send_money_api(request, data) if success["status"]: return Response(status=status.HTTP_202_ACCEPTED) else: return Response({"error": success["errors"]}, status=status.HTTP_400_BAD_REQUEST) //send_money_api def send_money_api(request, data): if data["amount"] and data["to"]: wallet = Wallet.objects.get(username=request.user.username) users = User.objects.all() users_names = [] for user in users: users_names.append(user) if int(data["amount"]) > int(wallet.amount): return {"status": False, "errors": "Withdraw amount greater than balance"} elif data["to"] == "ravinkohli" and data["to"] == request.user.username and data["to"] not in users_names: return {"status": False, "errors": "Invalid recipient"} else: wallet.subtract_money(data["amount"]) wallet.save() transaction = Transaction(from_name=request.user.username, wallet_id=wallet, date=datetime.datetime.now(), to=data['to'], amount=data["amount"]) transaction.save() return {"status": True} else: return {"status": False, "errors": "Missing content"} Error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, … -
URL dispatcher not working
I am creating a simple form in Django that takes inputs as username, email, password and adds them to database. Now when i click on submit button the URL dispatcher is not redirecting as well as updating database here is my code: loginForm\urls.py ( loginForm as project ): from django.conf.urls import url, include from django.contrib import admin app_name = 'authentication' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^authentication/', include('authentication.urls',namespace="authentication")), ] authentication\urls.py ( authentication as app ): from django.conf.urls import url from .import views urlpatterns = [ url(r'^$',views.SignIn, name="sign_in"), url(r'^register/$',views.Register, name="register"), ] sign_in.html : {% extends 'authentication/base.html' %} {% block body %} <div class="container"> <div class="row"> <div class="col-sm-offset-2 col-sm-8 col-md-offset-3 col-md-6 col-lg-offset-4 col-lg-4"> <fieldset> <legend> Register </legend> <from method="post" action="{% url 'authentication:register' %}" > {% csrf_token %} <div > <input name="username" type="username" placeholder="Username" class="form-control"> <input name="email" type="email" placeholder="Email" class="form-control"> <input name="password" type="password" placeholder="Password" class="form-control"> </div> <br> <button type="submit" class="btn btn-defaul"> Submit </button> </from> </fieldset> </div> </div> </div> {% endblock %} views.py: from django.shortcuts import render from .models import users def SignIn(request): return render(request,'authentication/sign_in.html') def Register(request): register = users() register.username = request.POST['username'] register.email = request.POST['email'] register.password = request.POST['password'] register.save() return render(request,'authentication/profile.html',{'username': register.username }) thanks for your kindness :) -
Django REST nested router
I'm new to Django and Django REST. Trying to implement recommended routing scheme using nested router for each app. Example: mysite.url.py: urlpatterns = [ url(r'^'+root_url+'/tinymce/', include('tinymce.urls')), url(r'^'+root_url+'/admin/', admin.site.urls), url(r'^'+root_url+'/swagger', swagger_schema_view), url(r'^'+root_url+'/', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) blog.urls.py: from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'^/blog', views.PostViewSet) router.register(r'^/users', views.UserViewSet) getting exception: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'C:\\Users\\user11\\PycharmProjects\\api_v2\\blog\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django AJAX login form validation
I'm trying to create an AJAX login form in Django, which would involve checking if the user has entered the correct username and password. Here is my code right now: urls.py urlpatterns = [ url(r'^$', views.boxes_view, name='news'), url(r'^user_login/', views.user_login, name='user_login'), ] forms.py class UserLoginForm(forms.Form): username = forms.CharField(max_length=25) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password', ] base.html <form method="post" enctype="multipart/form-data" action="{% url 'user_login' %}" class="form_login">{% csrf_token %} <div class="loginWrapper"> <div class="login"> <div class="loginBox"> {{ form_login.username|placeholder:"username"|add_class:"login_username" }} {{ form_login.password|placeholder:"password"|add_class:"login_password" }} <input type="submit" value="login"/> </div> </div> </div> </form> Here is my jQuery function. It successfully logs the entered username and password to the console. base.js $('.form_login').on('submit', function(e) { $.ajax({ type: 'POST', url: 'http://127.0.0.1:8000/user_login/', data: {'username': $('.login_username').val(), 'password': $('.login_password').val()}, success: function (data) { console.log(data) } } ) }) How do I get the data from the jQuery function to my views.py? Here is my current views which works fine to log a user in, however if the wrong credentials are entered it just submits the form anyway, which is why I want to implement AJAX to prevent submission and list errors if this happens. views.py def user_login(request): form_login = UserLoginForm(request.POST or None) if form_login.is_valid(): username = form_login.cleaned_data['username'] password … -
How to represent a date time for B.C. within python
I am creating a application about the history. But I am getting stuck when I need to create a field with django DateTimeField to represent the date time for B.C.(aka Before Christ). eg. Roman Empire is from 27 B.C. to 395 AD. How can I represent the from and to date with python datetime or django DateTimeField? I need some further date calculation on these fields, so an integer is not quite well for this, any idea? -
Setup gunicorn to run with Django
I've installed gunicorn and my django project kb when I cd into kb and run gunicorn --bind 0.0.0.0:8000 kb.wsgi:application it runs okay. I've I run nano on /etc/init/gunicorn.conf description "Gunicorn application server handling myproject" start on runlevel [2345] stop on runlevel [!2345] respawn setuid user setgid www-data chdir /home/ubuntu/kb exec gunicorn --workers 3 --bind unix:/home/ubuntu/kb/kb.sock kb.wsgi:application When I run sudo service gunicorn start I get Failed to start gunicorn.service: Unit gunicorn.service not found. -
Django - check if object exists
I'm trying to check if an object exists in my form but i'm getting an error. my views: def foo(request): titulo = "something" form = MyForm(request.POST or None) queryset = myModel.objects.all() if myModel.objects.filter(name=name).exists(): messages.error(request, 'already exists') context = { "titulo": titulo, "form": form, "queryset": queryset, } if form.is_valid(): instance = form.save() messages.success(request, 'Added') return redirect('/') return render(request, "forms7.html", context) Basically what I'm doing is adding an user, if the user exists I want a warning saying already exists Error: UnboundLocalError at /model/ local variable 'name' referenced before assignment What am I doing wrong? Note: If I add name = 'jesus' to my code and jesus exists it works but that's not how I want. I want to check if the name I'm entering exists show me the msg Could someone help me? thanks. -
How to downgrade Postgres from 9.6 to 9.5
I removed my 9.6 postgres.app and downloaded postgres.app. However, when I did locate initdb It still points to the wrong location: /Applications/Postgres.app/Contents/Versions/9.6/bin/initdb /Applications/Postgres.app/Contents/Versions/9.6/share/doc/postgresql/html/app-initdb.html /Applications/Postgres.app/Contents/Versions/9.6/share/man/man1/initdb.1 What would be the most efficient way to resolve this problem? -
I couldn't upload images using Django Rest-framework
I couldn't upload images using Django Rest-framework through POSTMAN , But I can do the same using Django Admin. When I try to debug the code, It's found that, serializer.is_valid() is always false. These are my code parts, views.py class imageuploadView(APIView): def post(self, request,format=None): serializer=ImageSerializer(data=request.data) print serializer if serializer.is_valid(): serializer.save() return Response(data={"detail":"Image Uploaded !"})#data else: return Response(data={"detail":"Not Uploaded"}) models.py class ImageUploadModel(models.Model): usr_id=models.IntegerField() upImg=models.ImageField(upload_to='media/') caption=models.CharField(max_length=50,default=None) serializer.py class ImageSerializer(serializers.ModelSerializer): upImg = serializers.ImageField(max_length=None,use_url=True) class Meta: model=ImageUploadModel fields=('usr_id','upImg','caption') settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/static/', ) MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } -
Django model has no foreign key object set
So I'm making django models of Country and Embassy, an Embassy requires two countries to be involved, one country that represents the Embassy, and another one that the Embassy is located in. So I've put two Countrys as foreign keys in Embassy Here's my models.py: from django.db import models class Country(models.Model): code = models.CharField(primary_key=True, max_length=3) #ISO Alpha-3 Country Code name = models.CharField(max_length=50, db_column="Name") def __str__(self): return self.name class Embassy(models.Model): government = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="government") location = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="location") name = models.CharField(max_length=200, db_column="Name") street_address = models.CharField(max_length=200, db_column="Address") city = models.CharField(max_length=50, db_column="City") phone_number = models.IntegerField(default=-1, db_column="Phone Number") fax_number = models.IntegerField(null=True, blank=True, db_column="Fax Number") email_address = models.CharField(max_length=200, db_column="Email") website = models.CharField(max_length=200, db_column="Link") def __str__(self): return self.name Now when I go into the shell I want to find what embassies are associated with a country: >>> from appName.models import Country, Embassy >>> c = Country(code="USA", name="United States of America") >>> c.save() >>> Country.objects.all() <QuerySet [<Country: United States of America>]> >>> c.embassy_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Country' object has no attribute 'embassy_set' When looking over the django tutorial with the Choice model having a foreign key of the Question model, the question objects have an attribute … -
Getting the user details using jwt authentication in django rest framework
hello i am trying to get the user details using jwt token authentication i am able to get using BasicAuthentication and JsonWebToken authentication. I am trying to get the details using Jwt . class PermissionView(APIView): permission_classes = [IsAuthenticated] authentication_classes = [BasicAuthentication,JSONWebTokenAuthentication] def get(self, request,format=None): data = { 'username': request.user.username, 'password':request.user.password, } return Response(data) urls: url(r'^api-token/$', obtain_jwt_token), output: 1)generating the token 2)getting the user details using Basic Authentication and JsonWebTokenauthentication I am trying to get the user details or authenicate the user details using jwt token.Help would be appreciated ? -
update password only if it is entered while updating user in Django admin
I have custom user in Django, so in user creation form in admin we have password field, and its getting saved while creation, but when I go to change existing user and I am not entering/changing password field , but it getting reflected in database. below is my code class ChangeClientEmployeeMasterForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChangeClientEmployeeMasterForm, self).__init__(*args, **kwargs) self.fields['groups'].label='Roles' if 'instance' in kwargs and hasattr(kwargs['instance'], 'client_employee_id'): self.client_employee_id = kwargs['instance'].client_employee_id def clean(self): if self.cleaned_data['client_employee_type'] =='imast': self.cleaned_data['is_superuser'] = True else : self.cleaned_data['is_superuser'] = False return self.cleaned_data def save(self, commit=True): user = super(ChangeClientEmployeeMasterForm, self).save(commit=False) password = self.cleaned_data["password"] if password: user.set_password(password) if commit: user.save(self.cleaned_data) return user -
How to refactor similar looking functions across 2 different class based views in Django 1.10?
Am using codecoverage and it complains that I have 2 functions in 2 different class based views that are too similar. Attached is the codecoverage error Below are the code that were highlighted: class PalletContentPickup(APIView): """ Picking up a pallet content to transfer to exiting pallet content """ def put(self, request, pk): count = request.data['count'] pallet_id = request.data['pallet_id'] from_pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk) to_pallet = QuickFind.get_pallet_or_404(pallet_id=pallet_id) Transfer.validate_if_can_pickup_pallet_content(from_pallet_content, to_pallet, request.user) to_pallet_content = QuickFind.get_or_create_pallet_content(pallet=to_pallet, product=from_pallet_content.product) ExitFormHelper.create_exit_form_line_item_on_pallet_content_if_no_exit_form_line(to_pallet_content, request.user) Transfer.previous_pallet_content_to_new_pallet_content(from_pallet_content, to_pallet_content, count) serializer = PalletSerializer(from_pallet_content.pallet) return Response({"data": serializer.data}, status=status.HTTP_202_ACCEPTED) class PalletContentPutback(APIView): """ Put back pallet content to an approved pallet """ def put(self, request, pk): count = request.data['count'] pallet_id = request.data['pallet_id'] from_pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk) to_pallet = QuickFind.get_pallet_or_404(pallet_id=pallet_id) Transfer.validate_if_can_putback_pallet_content(from_pallet_content, to_pallet, request.user) to_pallet_content = QuickFind.get_or_create_pallet_content(pallet=to_pallet, product=from_pallet_content.product) ExitFormHelper.create_exit_form_line_item_on_pallet_content_if_no_exit_form_line(to_pallet_content, request.user) Transfer.previous_pallet_content_to_new_pallet_content(from_pallet_content, to_pallet_content, count) serializer = PalletSerializer(from_pallet_content.pallet) return Response({"data": serializer.data}, status=status.HTTP_202_ACCEPTED) I read about strategy pattern in Python Not sure if I should apply strategy pattern here and if so, how? Because the example in the url still does not help me realise exactly how to perform strategy pattern here. -
How to create a biometric employee attendence management system in django web development
I am creating on new startup project on django web development.As i am new to the programming...And i am started my first project on web based biometric employee attendence management system ..And i created models are: Employee Attendence Working Setup Salary location leave And i am more confused how to write query on it..means one particular employee uses his fingerprint for many times in one day.And i need to save his checkin time each and every time he uses fingerprint...And based on his fingerprint i should calculate his working hours and to calculate if he takes leave and finally want to pay for his work what he did... So please can any one help how to write a query in django to create Biometric based attendece for an employee -
Django - on_delete=models.PROTECT not working properly
Hello friends I need help, I'm new in python and Django This time I'm building my app and i'm trying to use on_delete=models.PROTECT it works ok but I want to replace my template ProtectedError for any message. How can I do that? I have something like this: grupos models class grupos(models.Model): nombre_grupo = models.CharField(max_length=100) nombre_puerto = models.ForeignKey(puerto, on_delete=models.PROTECT) def __unicode__(self): return self.nombre_grupo def __str__(self): return self.nombre_grupo As you can see there's a dependecy, where if I have a puerto created it won't let me delete that puerto that's fine and that's working but I'm getting the template error and I want a msg instead of that. Here's my puerto delete views: Puerto views.py def delete(request, id): # I want the message here..... (such as messages.warning or something) note = get_object_or_404(puerto, pk=id).delete() messages.error(request, 'This puerto has been deleted.') return redirect('/puertot') for example, I want something like messages.warning(request, 'You can't delete this because it's being used by grupos') Template error: ProtectedError at /delete/59/ ("Cannot delete some instances of model 'puerto' because they are referenced through a protected foreign key: 'grupos.nombre_puerto'", ]>) I've trying to figure out how to manage this but no clue... How can I do this? Thanks...!