Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: How to make field in serializer required only for object creation?
I'm using Django Rest Framework and have a following serializer (minimal example): class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id', 'brand', 'color') extra_kwargs = { 'brand': {'required': True}, } So using POST it works as expected and prevents car creation without a brand in request params. But then I want to update some Car entity in DB and modify only a color field. Using PUT (or PATCH) like this: http PUT :8000/cars/123/ color="red" There are some errors: { "brand": [ "This field is required." ] } How can I make the brand field required only for object creation but not for modifying? -
How do I push my Bitbucket repo to my DigitalOcean server?
I've created a DigitalOcean server (droplet) for my Django site, running Ubuntu 16.04 with Nginx & Gunicorn. I've got my Django project in a Bitbucket repo - how do I push this to my DigitalOcean server? I've tried to search and there are many different/confusing answers and they all seem more complicated that it should be. Help appreciated. -
Django Integrity Error Not null
i am learning django and trying to practice by making my own website that will quiz me with questions that i submit in to it. I get this error and i dont know why. IntegrityError at /questions/new/ NOT NULL constraint failed: questions_question.date_created This is the relevent traceback i believe enter image description here here is my relevant code: questions/Views.py from django.shortcuts import render from django.views import generic from django.core.urlresolvers import reverse_lazy from django.contrib import messages from . import models from . import forms # Create your views here. class QuestionList(generic.ListView): model = models.Question class QuestionDetail(generic.DetailView): model = models.Question def get_queryset(self): queryset = super().get_queryset() class CreateQuestion(generic.CreateView): model = models.Question # form = QuestionForm fields = ('question', 'answer') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeleteQuestion(generic.DeleteView): model = models.Question success_url = reverse_lazy('questions:all') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Question Deleted") return super().delete(*args, **kwargs) Here is my models.py from django.db import models from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse User = get_user_model() import misaka # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=225) intro_text = models.TextField(null=True) date_created = models.DateTimeField() date_updated = models.DateTimeField(auto_now=True, null=True) class Question(models.Model): user = models.ForeignKey(User, related_name="question", … -
Why the `/admin/` only have few models?
I use the admin account login to the /admin/: Why there are only these field I can edit? I have write tons models in my project. why do not show up? -
'Request' object is not iterable
I am trying to do simple crud demo project API's for mobile using django rest framework and getting below error Project Name : crud_demo App Name : crud_operations crud_demo/urls.py from django.conf.urls import include, url from django.urls import path urlpatterns= [ path('models/', views.model_list), path('models/<int:pk>/', views.model_detail), ] crud_operations/models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) crud_operations/serializers.py from crud_operations.models import Member from rest_framework import serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('firstname', 'lastname') crud_operations/views.py from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Member from crud_operations.serializers import MemberSerializer @api_view(['GET', 'POST']) def model_list(request): if request == 'GET': member = Member.objects.all() serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'POST': serializer = MemberSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'key': request}, status=status.HTTP_200_OK) @api_view(['GET', 'PUT', 'DELETE']) def model_detail(request, pk): try: member = Member.objects.get(pk=pk) except Member.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request == 'GET': serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'PUT': serializer = MemberSerializer(member, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': member.delete() return Response(status=status.HTTP_204_NO_CONTENT) return Response({'key': 'value'}, status=status.HTTP_200_OK) -
After login the `rest-auth`, how to return more information?
I use django-rest-auth in my Django project. After login the rest-auth/login/, how to return more information? In the rest-auth/login/, when I login the user, it returns a key. I want to also return the user's information, how can I get this? -
django migrations in postgresql fails (Even default migrations but works in sqlite and mysql)
I created a new django project and added the following database settings in setings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', 'OPTIONS':{'options': '-c search_path=resttest'} } } I just ran "python manage.py migrate" But it this error django.db.utils.ProgrammingError: constraint "django_admin_log_user_id_c564eba6_fk" does not exist When is try changing the Database setting with default sqlite or to MySQL it works fine. I even tried using 'ENGINE': 'django.db.backends.postgresql' as shown in the documentation. Can someone help me out in guessing what the problem is? -
Dynamically add properties to Django model
Currently I have the following Django model class TestUser(models.Model): name = models.CharField(max_length=250) email = models.CharField(max_length=250) ... class Meta: db_table = 'temp_user' and I've the following method. def print_name(self): return self.name I want to add this method as a property to TempUser model. I know this can be done by putting the method inside TempUser class and user @property. But I want to do it dynamically. I tried this from python shell. In [10]: TempUser.print_name = property(print_name) In [11]: TempUser.print_name Out[11]: <property at 0x7efc374e7c58> In [12]: user = TempUser.objects.get(pk=1) In [13]: user.print_name Out[13]: u'Test User' But once I exit the shell, I loose the property. Is there any way to add the property permanently. -
django S3 - trim imagefield filename but not the url path
this is a followup to my question here: ImageField / FileField Django form Currently unable to trim the path to filename In my Django app, there is an imagefield uploaded to S3 After trim the imagefile path name, the image is not accessible because the url is trimmed. How can i trim the display but dont trim the path ? I manage to trim the display showing the filename like this class CustomClearableFileInput(ClearableFileInput): def get_context(self, name, value, attrs): logging.debug("%s",name) logging.debug("%s",value) value.name = path.basename(value.name) context = super().get_context(name, value, attrs) return context class CompanySettingEdit(forms.ModelForm): company_logo = forms.ImageField(widget=CustomClearableFileInput) this is the output: https://imgur.com/a/M42Mz <-- display correct https://bucketname.s3.amazonaws.com/media/certiport_logo.png <-- invalid url If I dont trim it: class CustomClearableFileInput(ClearableFileInput): def get_context(self, name, value, attrs): logging.debug("%s",name) logging.debug("%s",value) # value.name = path.basename(value.name) <-- remove this context = super().get_context(name, value, attrs) return context class CompanySettingEdit(forms.ModelForm): company_logo = forms.ImageField(widget=CustomClearableFileInput) this is the output: https://imgur.com/a/rGi8f <-- display incorrect https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png <--valid url my goal is to: display: certiport_logo.png url: https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png How can I achieve this ? -
django.core.exceptions.ImproperlyConfigured. The included URLconf does not appear to have any patterns in it
I am trying to do simple crud demo project API's for mobile using django rest framework and getting below error django.core.exceptions.ImproperlyConfigured: The included URLconf '' 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. Project Name : crud_demo App Name : crud_operations crud_demo/urls.py from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns= [ url(r'^admin/', admin.site.urls), url(r'^crud_operations/', include('crud_operations.urls')), ] crud_operations/models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) crud_operations/serializers.py from crud_operations.models import Member from rest_framework import serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('firstname', 'lastname') crud_operations/urls.py from crud_operations import views urlpatterns = [ url(r'^models/$', include(views.model_list)), url(r'^models/(?P<pk>[0-9]+)$', include(views.model_detail)), ] crud_operations/views.py from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Member from crud_operations.serializers import MemberSerializer @api_view(['GET', 'POST']) def model_list(request): if request == 'GET': member = Member.objects.all() serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'POST': serializer = MemberSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'key': request}, status=status.HTTP_200_OK) @api_view(['GET', 'PUT', 'DELETE']) def model_detail(request, pk): try: member … -
How to avoid ValueError save() prohibited to prevent data loss due to unsaved related object?
I have (2) models - Recipes and RecipeIngredient, related by foreign key. The user creates a recipe (core information) and saves it, then can later CRUD associated elements (like ingredients, procedures, etc.) The Formview/modelformset is called by passing the pk of the recipe all the forms will use as a FK. After posting the view assigns the FK's pk to the appropriate field in each form. Unfortunately, I get the "save() prohibited" error, and after reading through many SO questions/comments about this error occurring, I don't see a clear answer on how to avoid/correct this. To me this seems like a central method of relating objects to each other, and there should be a way to accomplish this. If I don't assign the FK manually, it won't save without the mandatory relationship being specified. If I DO assign it, I get this save() error. The error always occurs Django attempts to save the first form of the loop. The error: save() prohibited to prevent data loss due to unsaved related object 'parent_recipe' The models: class RecipeBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) creation_date = models.DateField("Record creation date",auto_now_add=True) creation_user = models.CharField("Record creation user",max_length=150) lastupdated_date = models.DateField(auto_now=True) lastupdated_user = models.CharField(max_length=150) category = … -
Django rest serializer don't work with many to many relationship
I'm trying to create an personal project based on a simple kanban, the model task have a relationship with model board. When I try renderize it, I get the items: title and slug, but, the relationship with model board is missing, can someone help me with this error please, what I doing wrong? OBS: I know, here in stackoverflow have many posts with the same subject, but unfortunately I did not find the solution :/ here is my model code: class Board(models.Model): BACKLOG = 'Backlog' PROCESS = 'In progress' QA = 'QA' COMPLETE = 'Complete' _status = ((BACKLOG, 'Backlog'), (PROCESS, 'In progress'), (QA, 'QA'), (COMPLETE, 'Complete')) LOW = 'Low' NORMAL = 'Normal' HIGH = 'High' _priority = ((LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High')) status = models.CharField(_('Status'), max_length=20, choices=_status, default=BACKLOG, help_text='Selecione o status da task') priority = models.CharField(_('Priority'), max_length=20, choices=_priority, default=NORMAL, help_text='Selecione a prioridade da task') description = models.TextField() class Meta: verbose_name = 'Board' verbose_name_plural = 'Boards' ordering = ['priority',] def __str__(self): return "{} - {}".format(self.description, self.priority) class Task(models.Model): title = models.CharField(_('Tittle'), max_length=100, help_text='Titulo da task') slug = models.SlugField(db_index=True) board = models.ManyToManyField(Board) class Meta: verbose_name = 'Task' verbose_name_plural = 'Tasks' ordering = ['title',] def __str__(self): return "{}".format(self.title) in my serializers file … -
Is the default Permissions have API?
Is the default Permissions have API for edit? This is my urls conf(sorry about the ): I want to edit the permissions, such as its name, or others information. But you see there is no url conf for it. how can I edit it? I mean in my custom interface to edit it, there need the permissions' API. -
How to set a variable in if statement and return in function?
I want to set a variable: correct_captcha, in if statement and return it from the function to HTML, the views is as below: def list(request): correct_captcha = None if request.method == 'POST': file = request.FILES.get('file', False) ca_mode = request.POST.get('mode', 'word').lower() assert ca_mode in ['number', 'word', 'four_number'] captcha = request.POST.get('captcha') ca = Captcha(request) if ca.validate(captcha): if 'file' in request.FILES: fs = FileSystemStorage() fs.save('(' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ')' + file.name, file) filesname= str('(' + datetime.now().strftime('%Y-%m-%d-%H- %M-%S') + ')' + file.name) else: filesname = '' add_obj = enquiry(file=filesname) add_obj.save() correct_captcha = 0 return correct_captcha else: correct_captcha = 1 return correct_captcha return render(request, 'list.html', {'correct_captcha':correct_captcha}) But it did not work, how can I do to return this variable in function? -
Can't access Graphite web (error 500)
After updating the Whisper package (from 0.9.12 to 1.1.1) using pip, I'm not able to access my Graphite instance anymore (even after downgrading...) The logs say the target script can't be loaded as a Python module. Here are some informations about the system. Python version: 2.7 Carbon, Graphite web, Whisper versions: 0.9.12 I tried changing the rights of /usr/share/graphite-web/graphite.wsgi and /opt/graphite/conf/graphite.wsgi but it didn't solve the problem. My error log: [Thu Jan 18 14:53:17.260272 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] mod_wsgi (pid=16527): Target WSGI script '/usr/share/graphite-web/graphite.wsgi' cannot be loaded as Python module. [Thu Jan 18 14:53:17.260431 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] mod_wsgi (pid=16527): Exception occurred processing WSGI script '/usr/share/graphite-web/graphite.wsgi'. [Thu Jan 18 14:53:17.260470 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] Traceback (most recent call last): [Thu Jan 18 14:53:17.260507 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/share/graphite-web/graphite.wsgi", line 16, in <module> [Thu Jan 18 14:53:17.260552 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] application = get_wsgi_application() [Thu Jan 18 14:53:17.260564 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Jan 18 14:53:17.260586 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] django.setup(set_prefix=False) [Thu Jan 18 14:53:17.260597 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup [Thu Jan 18 … -
How do I customize the Group in Django?
I write a Django project, and I use the default Groups and Permissions. When I list or retrieve the Group, the data is bellow: { "id": 2, "name": "group02", "permissions": [ 22, 23, 24 ] } I can not see the permissions name and the users belong to the Group instance. How can I optimize this to satisfy my requirement? -
How do i change the default primary key in django?
I'm new to learning django. I'm using PostgreSQL as my database. I created an app called gplus and a model I created looks something like this class Account(AbstractBaseUser): email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_of_birth = models.DateTimeField() I applied the migrations and then wanted to change the primary key field from default 'id' to 'username'. So, in the psql command line I ran the following commands ALTER TABLE gplus_account DROP CONSTRAINT gplus_account_pkey; ALTER TABLE gplus_account ADD PRIMARY KEY (username); ALTER TABLE gplus_account DROP COLUMN id; Then in the models.py, I edited the username field as username = models.CharField(max_length=50, primary_key=true) Now, when I try to apply the migrations, I get the error django.db.utils.ProgrammingError: column "id" of relation "gplus_account" does not exist It seems Django needs to know there is no 'id' field in the table anymore. How can I do that? Thanks -
Connecting to AWS Postgres Instance For Django Backend
I've created a PostgreSQL database on AWS, which I want to use for a Django project. I've modified settings.py so that it has DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': <db name>, 'USER': <user>, 'PASSWORD': <password>, 'HOST': 'projectdevelopment.foobar.us-east-1.rds.amazonaws.com', 'PORT': '5432', } } Which I would have thought seemed pretty straightforward. Except that when I try to make a migration I get this error: django.db.utils.OperationalError: could not translate host name "projectdevelopment.foobar.us-east-1.rds.amazonaws.com" to address: nodename nor servname provided, or not known The value projectdevelopment.foobar.us-east-1.rds.amazonaws.com has been copied directly from the value under endpoint in the RDS console. Am I missing a setting, or misconfigured? Or both? -
How can I save a UserProfile image (avatar)'s path in the database?
I am having trouble figuring out how I can store a user's uploaded image (their avatar) when they update their profile. The default image I have in the model works, but the update does not give a validationerror, but essentially nothing happens when i submit - the default image remains the same. Here is my code, any understanding of what I'm doing wrong is greatly appreciated. user_profile/views.py def update_user_profile(request, username): args = {} if request.method == 'POST': form = UpdateUserProfile(request.POST, request.FILES, instance=request.user) if request.user.username == username: if form.is_valid(): form.save() return HttpResponseRedirect(reverse('user-profile', kwargs={'username': form.instance.username})) else: raise Http404() elif request.method == 'GET': if not request.user.username == username: raise Http404() else: form = UpdateUserProfile(instance=request.user) else: form = UpdateUserProfile(instance=request.user) args['form'] = form return render(request, 'storytime/update_user_profile.html', args) user_profile/forms.py class UpdateUserProfile(forms.ModelForm): class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: width, height = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if width > max_width or height > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): … -
wrap all django apps in a apps folder
I am trying to wrap all the local apps into apps folder. The project structure I am wanting is apps app1 app2 static templates db.sqlite3 manage.py For this I tried using django-oscar way Here is my settings configuration import os import project_name PROJECT_DIR = os.path.join(os.path.dirname(__file__)) location = lambda x: os.path.join(PROJECT_DIR, x) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ]+project_name.get_core_apps() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': location('db.sqlite3'), } } project/init.py import os def get_short_version(): return '%s.%s' % (VERSION[0], VERSION[1]) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) # Append 3rd digit if > 0 if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) elif VERSION[3] != 'final': version = '%s %s' % (version, VERSION[3]) if len(VERSION) == 5: version = '%s %s' % (version, VERSION[4]) return version PROJECT_MAIN_TEMPLATE_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'templates') PROJECT_CORE_APPS = [ 'project_name', 'project_name.apps.checkout', 'project_name.apps.address', 'haystack', 'treebeard', 'versatileimagefield', ] def get_core_apps(overrides=None): if not overrides: return PROJECT_CORE_APPS from django.utils import six if isinstance(overrides, six.string_types): raise ValueError( "get_core_apps expects a list or tuple of apps " "to override") def get_app_label(app_label, overrides): pattern = app_label.replace('project_name.apps.', '') return app_label apps = [] for app_label in PROJECT_CORE_APPS: apps.append(get_app_label(app_label, overrides)) return apps I get ModuleNotFoundError: No module named 'project_name.apps' error … -
Create parent record with child many by django form
In my django project I have code as below: forms.py class addOrderForm(ModelForm): class Meta: model = Orders fields = [ 'shipvia', 'customer', 'employee', 'orderdate', 'freight', 'shipname', 'shipaddress', 'shipcity', 'shipregion', 'shippostalcode', 'shipcountry' ] views.py def addOrder(request): OrderDetailsFormSet = inlineformset_factory(Orders, OrderDetails, fields=('product', 'unitprice', 'quantity' , 'discount'), extra=3) order=Orders() if request.method == 'POST': f = addOrderForm(request.POST, instance=order) fs = OrderDetailsFormSet(request.POST,instance=order) if fs.is_valid() and f.is_valid(): f.save() fs.save() return HttpResponse('success') else: f = addOrderForm(instance=order) fs = OrderDetailsFormSet(instance=order) return render(request, 'orders/addOrder.html', context = {'fs': fs,'f':f,'order':order}) orders/addOrder.html {% block body %} <form action="/orders/addOrder/" method="post"> {% csrf_token %} <div class="row"> {{ fs.management_form }} <table> {% for form in fs.forms %} {% for field in form %} <tr><th>{{field.label_tag}}</th><td>{{field}}{{field.errors}}</td></tr> {% endfor %} {% endfor %} </table> </div> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker({ inline: true, sideBySide: true, format: 'YYYY-MM-DD', }); }); </script> {% endblock %} There are two tables in the database ORDERS table: orderid | smallint | not null default nextval('orders_orderid_seq'::regclass) customerid | bpchar | employeeid | smallint | orderdate | date | requireddate | date | shippeddate | date | shipvia | smallint | freight | real | shipname | character varying(40) | shipaddress | character varying(60) | shipcity | character varying(15) | … -
Edit view on Django not displaying object into page
I got a form page to edit my objects from database, but when I access them with the edit button it goes to the url http://localhost:8000/acoes/edit/1, but I cannot see the object details in the form field. It is just empty as if I was going to create a new object (and it creates if I try) Any suggestion? Every post and question that I found online states that the code would work being just like this, but it isnt. on the template acoes_form.html <form method="post"> <div class="form-group"> {% csrf_token %} {{form.as_p}} </div> <input type="submit" value="Gravar dados" class="btn btn-success" /> </form> on views.py @login_required(login_url="/login") def acoes_edit(request, pk, template_name='acoes/acoes_form.html'): if request.user.is_superuser: acoes= get_object_or_404(Acoes, pk=pk) else: acoes= get_object_or_404(Acoes, pk=pk, user=request.user) form = AcoesForm(request.POST or None, instance=acoes) if form.is_valid(): form.save() return redirect('acoes_list') return render(request, template_name, {'form':AcoesForm}) on forms.py class AcoesForm(ModelForm): #bunch of fields definitions #... # class Meta: model = Acoes fields = ['id_pedido','bl_msg','tb_msg','bl_shell','tb_shell','obs','ativo'] -
How to hide my website to the public so only I can see it?
Creating a Django website with Digital Ocean (Nginx, Guncorn) - and would like to know how to show a blank page until I've finished development. So when someone other than myself visits my website, I want them to see a page saying "Site under construction" or something. Advice appreciated. -
How to resolve FOREIGN KEY constraint failed
I am following a tutorial on a basic concept. How to customize a user in django. I want to use the built in auth user. I found this tutorial which seems to work until a point. I get through the whole tutorial with everything working. however when I run my project, log in and open the user in the admin area I click "Save and continue editing" This gives me the error The code I have in my project is EXACTLY the same as in the tutorial. I have tried removing my cache and migrations and starting again, even creating a new environment and reinstalling django. Nothing seems to work. Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/user/1/change/ Django Version: 2.0.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit 239. return self.connection.commit() The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File … -
Django: Change formset error message(s)
Hello fellow programmers, I would like to change the min_num error message of a formset. My code creates a formset using an inlineformset_factory: formset_clazz = inlineformset_factory(MyParentModel, MyModel, MyModelForm, can_delete=True, min_num=1, validate_min=True) formset = formset_clazz(data=request.POST) print(formset._non_form_errors) if formset.is_valid(): print("yay!") else: print("nay!") return render(request, "mytemplate.html", {'formset':formset}) In the template I render the non_form_errors: {% if formset.non_form_errors %} <ul> {% for error in form.non_form_errors %} <li> {{ error }} </li> {% endfor %} </ul> {% endif %} The min_num validation works as intended and shows the error message Please submit 1 or more forms., when a user removes all forms and submits the formset. My question is: How do I change the error message? From [0] I learned, that it is stored in formset._non_form_errors, but without a way to override the too_few_forms [1] (ctrl-F validate_min) code's message. The BaseFormSet class itself uses ngettext to translate the message, but I do not really want to setup internationalization just for this (or is that easy and straight-forward?). Is there a more convenient way to achieve my goal? [0] Django: Displaying formset errors correctly [1] https://docs.djangoproject.com/en/2.0/_modules/django/forms/formsets/#BaseFormSet