Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Tables2 LinkColumn and Column(linkify=True) returning famous Reverse error
I have been stuck on a problem that I had address previously (link goes to wrong item) but fixed it with some assistance by a helpful mechanical turk. Then I changed the model such that one of the fields went from ForiegnKey to ManyToMany, and broke something in the process. I am using django 2.1, python 3.6, and the latest django-tables2 version. Here is a bit of code. models.py class PI(models.Model): l_name = models.CharField('Last', blank=False, max_length=100, default='') f_name = models.CharField('First', blank=False, max_length=100, default='') ... def get_absolute_url(self): return reverse('pi-detail', args=[str(self.id)]) class Sample(models.Model): sample_name = models.CharField('Sample', max_length=16) pi = models.ForeignKey(PI, verbose_name='PI', on_delete=models.SET_NULL, null=True) ... def get_absolute_url(self): return reverse('sample-detail', args=[str(self.id)]) class Publication(models.Model): titlep = models.CharField('Title', max_length=200, blank=False, default='') sample = models.ForeignKey(Sample, on_delete=models.SET_NULL, null=True, blank=True, default='') pi = models.ManyToManyField(PI, verbose_name='PI') pdf = models.CharField('PDF', default='', max_length=500, blank=True) def get_absolute_url(self): return reverse('publication-detail', args=[str(self.id)]) def filename(self): return self.pdf def __str__(self): return '%s, (%s)' % (self.titlep, ' '.join(p.l_name for p in self.pi.all())) tables.py class PublicationTable(tables.Table): titlep = tables.LinkColumn('publication-detail', args=[A('pk')]) pi = tables.TemplateColumn(empty_values=(), orderable=False, template_code='''{% for pi in record.pi.all %} <a href="{% url "pi-detail" pi.pk %}">{{pi}}</a>, {%endfor%} ''') sample = tables.LinkColumn('sample-detail', args=[A('sample_id')]) pdf = tables.TemplateColumn(template_code='''{% load static %}<a href="{% static 'pdf/'|add:value %}" target="_blank">{{record.pdf}}</a>''') When I look at the rendered … -
Why this 2 form dosn't work with ajax in Django?
I am developing an application on django, and faced with strange problems with Ajax. On my website 4 forms should be processed using Ajax. And two of them work great. But 2 others not heard about Ajax at all. Consider working and non-working forms. views.py view working form def login_user(request): form = LoginForm(request.POST) context = { 'form': form, } if request.method == 'POST' and form.is_valid(): username = form.cleaned_data['user_login'] password = form.cleaned_data['user_password'] user = authenticate(username=username, password=password) response_data = {} if user and user.is_active: login(request, user) response_data['result'] = 'Ok' else: response_data['result'] = 'Bad' return HttpResponse(json.dumps(response_data)) else: return redirect('index') view non-working form def add_new_station(request, add_station_slug): form = AddStationForm(request.POST) myuser = get_object_or_404(User, id=request.user.id) print(request.user) if request.method == 'POST' and form.is_valid(): response_data = {} UserStation.objects.create( station=Station.objects.get(slug=add_station_slug), impressions=form.cleaned_data['impressions'], list=UserStationsList.objects.get(user=myuser) response_data['result'] = 'Ok' ) return HttpResponse(json.dumps(response_data)) else: return redirect('index') urls.py urlpatterns = [ path('', index, name='index'), path("add-in-list/<str:add_station_slug>/", add_new_station, name='new_station'), path('login/', login_user, name='login_action'), ... ] html html working form <form id="login_form" action="{% url 'login_action' %}" method="post"> {% csrf_token %} {{ formlogin }} <div class="text-center"> <button type="submit" class="btn btn-dark mt-2">Entry</button> </div> </form> html non-working form <form id="add_station_form" action="{% url 'new_station' choice_station.slug %}" method="post"> {% csrf_token %} {{ formaddstaion }} <div class="text-center"> <button type="submit" class="btn btn-outline-success mt-2">I visited this station</button> … -
Handle if wrong subdomain name in url using Django-hosts module
I am developing website in Django. I have redirected request as per subdomain request using Django-hosts library. But what if request come for wrong or not specified subdomain? How to handle that? -
Django: Problem with regexp and named parameters
I write my first routings and I have a problem with named parameters and regexp. I want my routing to transfer two named parameters a and b to the function sum_get_function, when I trying to access page, like mywebsite.com/routing/sum_get/function/?a=5&b=2 url(r"routing/sum_get_function/(?P)&() Actual result: I get 404 error all the time -
Apply custom paginator to all admin.ModelAdmin
I have a few different admin.ModelAdmin that I have applied a custom paginator to. The paginator seems to work on some of them but not all and I am not certain why. from django.core.paginator import Paginator from django.db import connection, models class MyPaginator(Paginator): def _get_count(self): if not hasattr(self, '_count'): if not self.object_list.query.where: table_name = self.object_list.query.model._meta.db_table cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname='{0}';".format(table_name)) self._count = int(cursor.fetchone()[0]) else: self._count = 500 return self._count @property def count(self): return self._get_count() -
Django dropdown [onChange] box with selected values but can't get the selected value
I have a dropdown selection of titles that upon selection of specific title, an action (should) run. What I have: form.py class CronForm(forms.Form): title = forms.ModelChoiceField(queryset=GlobalFID.objects.all().order_by('-title_date'), widget=forms.Select(attrs={"onChange":'change_title()'})) view.py [title_change_view ] my_form = CronForm() #initial=data return render(request, 'research/title_result.html',{"my_form":my_form}) html <form method="post" > {% csrf_token %} {{ my_form }} </form> and on the js side: function change_title() { var murl= "{% url 'title_change_view' %}"; window.location = murl; } my goal is to have the SELECTED title from {{my_form}} in the view title_change_view. While the redirection works, I can't get the selected value. Strategies I considered/tried: In the title_change_view I added if request.method == 'POST': but it's not a post (so it overlook it) so I can't read the form. var murl= "{% url 'title_change_view' %}"; to add additional parameter ?title=[SELCTED_VALUE] but couldn't figure out how to add the SELECTED title into murl or into the change_title() fuction. any idea? -
INSPECTDB and INSPECTDB_REFACTOR generate empty models
I have django project and one app. I haven't models, and I want to generate them from exist postgres database. I tried python manage.py inspectdb_refactor --database=default --app=igt and python manage.py inspectdb --database=default but for the first event django generates paths with only __inti__.py, and for the second event (inspectdb) django generates empty models.py. What is wrong? Connection is ok (so DATABASE configs is ok), apps was defined on setting.. what the problem? My setting.py: """ Django settings for lesoved project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os, sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '--------------------------------------------------' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition MYOWN_APPS = [ 'igt' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'polymorphic', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'dynamic_raw_id', 'rest_framework', 'rest_framework_gis', 'django_filters', 'inspectdb_refactor', ] + MYOWN_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
TypeError: Object of type date is not JSON serializable
I am trying to query database on the basis of multiple parameters, basically I fetch all the records from a table and then filter them out according to the parameters passed. Although the search portion works fine but when the resultant query set is returned, I get the following error: TypeError: Object of type date is not JSON serializable I am not sure why that happens since I'm not trying to serialize anything. My code looks something like: view class SearchView(LoginRequiredMixin, generic.ListView): login_url = '/login/' template_name = 'scand/search_result.html' context_object_name = 'images' def get_queryset(self): form = SearchForm(self.request.GET) query_dict = {} if form.is_valid(): query_dict = form.cleaned_data self.request.session['query_dict'] = query_dict queryset = ImageTag.objects.search(query_dict) print(queryset) return queryset model manager class ImageTagManager(models.Manager): def ordered_images(self): queryset = self.model.objects.order_by('id').all() return queryset def search(self, query_dict): if isinstance(query_dict, list): queryset = ImageTag.objects.filter(id__in=query_dict) if queryset is not None: return queryset else: return False # Initially getting all objects queryset_initial = ImageTag.objects.all() # copying queryset_initial to filter queryset = queryset_initial queryset = queryset.filter(company__iexact=query_dict['company']) if query_dict.get('company') not in ( None, '') else queryset queryset = queryset.filter(accoff__iexact=query_dict['accoff']) if query_dict.get('accoff') not in ( None, '') else queryset queryset = queryset.filter(section__iexact=query_dict['section']) if query_dict.get('section') not in ( None, '') else queryset queryset = queryset.filter(docref__iexact=query_dict['docref']) if query_dict.get('docref') … -
UnicodeDecodeError using Django smart_str with European letters
I am getting the error UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 138: ordinal not in range(128) when I try to do from django.utils.encoding import smart_str smart_str('ø') but the documentation says that the default encoding for this function is utf-8 which I thought should include 'ø'. What am I missing here? -
How to deal with time zone changes in Django?
I have a Django app with PostgreSQL as database that logs actions of users from different regions. Recently, one of the regions (Volgograd, Russia) had its timezone permanently changed from UTC+3h to UTC+4h on October 28, 2018. In January 2019, pytz had updated in pypi, and I updated pytz dependency so the region received correct time zone setting. The problem is events that happened before the October 28, 2018 are kind of "not synchronised" with the current time zone now. If I understand it correctly, after pytz update Django now believes that the time zone is and always was UTC+4h, so events before the October 28, 2018 are shifted one hour forward. For example, it shows 2pm local time instead of 1pm. The main requirement is users should be able to see correct time in their local timezone. For example, if the user performed the action at 1pm every day before and after October 28, 2018, she should see 1pm for all events. Even though events that happened before October 28 now have different UTC time than events that happened after that date. Currently events datetimes are displayed using model method: class Event(models.Model): date_created = models.DateTimeField(auto_now_add=True, blank=False, null=False) organization = … -
When sending emails from Django. Why in gmail the emails appear in *received* and in hotmail it appears in unwanted emails?
When the client registers in the system, the system sends an email with an activation link. cfg email: "EMAIL": { "EMAIL_USE_TLS": true, "EMAIL_HOST": "mail.blgroup.pe", "EMAIL_PORT": 587, "EMAIL_BACKEND": "django.core.mail.backends.smtp.EmailBackend", "EMAIL_HOST_USER": "baplie3d@blgroup.pe", "EMAIL_HOST_PASSWORD": "******", "DEFAULT_FROM_EMAIL": "baplie3d@blgroup.pe", "CONTACT_EMAIL": "demo@demo.com" } This is the template of html that sends to the mail. {% load static %} {% load i18n %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>{% trans 'Bienvenido a la plataforma baplie3d' %}</title> <meta name="viewport" content="width=device-width" /> <style type="text/css"> @media only screen and (max-width: 550px), screen and (max-device-width: 550px) { body[yahoo] .buttonwrapper { background-color: transparent !important; } body[yahoo] .button { padding: 0 !important; } body[yahoo] .button a { background-color: #4ca5a9; padding: 15px 25px !important; } } @media only screen and (min-device-width: 601px) { .content { width: 600px !important; } .col387 { width: 387px !important; } } </style> </head> <body bgcolor="#fff" style="margin: 0; padding: 0;" yahoo="fix"> <!--[if (gte mso 9)|(IE)]> <table width="600" align="center" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <![endif]--> <table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse; width: 100%; max-width: 600px;" class="content"> <tr> <td style="padding: 15px 10px 15px 10px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="center" style="color: #aaaaaa; font-family: Arial, sans-serif; font-size: 12px;"> Email … -
why is the prompt of my virtual environment different from its name?
I'm building a Django Project, and I first created a virtual environment. Before I work on it, I go to the /bin/ of my virtualenv, then I go source activate Usually, it then says: (myVirtualEnv) because that's how I named it. And I can do Python manage.py runserver, and all these sort of things. But since yesterday, after mysource activate, it says : (base) ... and the other doesn't work ! I don't understand what happened. Any help ? -
Filter by intermediary model field in Many-to-Many relationship
I want to create a friendship relationship between organisations. I added a connected_organisations field in my Organisation model: class Organisation(models.Model): ... connected_organisations = models.ManyToManyField('self', related_name='organisations_connected', through='Connection', through_fields=('requester', 'requestee'), symmetrical=False, blank=True) Then I created Connection as the intermediary model: class Connection(models.Model): requester = models.ForeignKey(Organisation, related_name='requester', null=True, on_delete=models.CASCADE) requestee = models.ForeignKey(Organisation, related_name='requestee', null=True, on_delete=models.CASCADE) is_connected = models.BooleanField(default=False) The is_connected field indicates whether the friendship request is approved by the requestee or if the request is still pending. I create a connection between org1 and org2 with: Connection.objects.create(requester=org1, requestee=org2) I know I can do: org1.connected_organisations.all() and this will return org2, but I cannot find how I can filter them by the is_connected field. I tried something like: Organisation.objects.filter(connected_organisations__requestee=org0, connected_organisations__is_connected=True) but I am getting: django.core.exceptions.FieldError: Related Field got invalid lookup: is_connected -
(keyError: 'CELERY_BROKER_URL')
File "C:\Users\User\path\lib\site-packages\environ\environ.py", line 277, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the CELERY_BROKER_URL environment variable I'm getting this error when I execute the "python manage.py" command. Already installed cookiecutter with its requirements but I don't know where to go from there. Any suggestions? -
Error running WSGI application Pythonanywhere Wagtail application
I am running into this problem on pythonanywhere where my webpage won't render. I suspect it is something with the DJANGO_SETTINGS_MODULE but I can't seem to get it to work. Also tried to use 'Wagtail-Onepage-Portfolio.settings' but did not work either. import os import sys path = '/home/webconexus/portfolio/portfolio/Wagtail-Onepage-Portfolio' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'portfolio.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() This is the /var/www/www_rafrasenberg_nl_wsgi.py Error running WSGI application 2019-02-06 14:58:00,884: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. 2019-02-06 14:58:00,884: File "/var/www/www_rafrasenberg_nl_wsgi.py", line 12, in 2019-02-06 14:58:00,884: application = get_wsgi_application() 2019-02-06 14:58:00,884: 2019-02-06 14:58:00,884: File "/home/webconexus/portfolio/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-02-06 14:58:00,884: django.setup(set_prefix=False) 2019-02-06 14:58:00,884: 2019-02-06 14:58:00,885: File "/home/webconexus/portfolio/lib/python3.7/site-packages/django/init.py", line 19, in setup 2019-02-06 14:58:00,885: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-02-06 14:58:00,885: 2019-02-06 14:58:00,885: File "/home/webconexus/portfolio/lib/python3.7/site-packages/django/conf/init.py", line 57, in getattr 2019-02-06 14:58:00,885: self._setup(name) 2019-02-06 14:58:00,885: 2019-02-06 14:58:00,885: File "/home/webconexus/portfolio/lib/python3.7/site-packages/django/conf/init.py", line 44, in _setup 2019-02-06 14:58:00,885: self._wrapped = Settings(settings_module) 2019-02-06 14:58:00,885: 2019-02-06 14:58:00,886: File "/home/webconexus/portfolio/lib/python3.7/site-packages/django/conf/init.py", line 126, in init 2019-02-06 14:58:00,886: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") 2019-02-06 14:58:00,886: *************************************************** 2019-02-06 14:58:00,886: If you're seeing an import error and don't know why, 2019-02-06 14:58:00,886: we have a dedicated help page to help you debug: 2019-02-06 14:58:00,886: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2019-02-06 14:58:00,886: … -
Wagtail single-page site
I made a single-page site in static HTML with shiny screen-height divs, and a smooth scrolling function from a navbar. The website is expected to have a mixture of simple body text, a few images, and a card-deck. It all worked nicely and I was happy. While I have used wagtail for very simple websites in the past, I cannot work out a way of making a single page site where the home page goes at the top followed by all the child pages in order. Is this possible with Wagtail's page models? -
updating password but unable to login from updated password in django
updating user password first fetching username from URL & updating password. not sure is this code working or not because i am unable to login from the old password again & even with the updated password too. views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.contrib import auth def change_password2(request, user_username): var_username = get_object_or_404(User, username=user_username) #getting username from url u = User.objects.get(username__exact=var_username) password = request.POST.get('password_update', False) u.set_password(password) b = u.save() update_session_auth_hash(request, b) messages.success(request, 'Your password was successfully updated!') # return redirect('change_password') return render(request, 'accounts/change_password2.html') change_password2.html: <form method="POST" action="/account/password2/"> {% csrf_token %} <input type="password" name="password_update"> <input type="submit" name=""> </form> Tried in incognito but not sure its because of cache. -
Fetching all objects hierarchically nested by ForeignKey in one query
I'm modeling a folders structure in my application. Every element (folder or file) has its own id and id of its parent: class Folder(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4) parent_folder = models.ForeignKey( 'folders.Folder', on_delete=models.CASCADE, null=True, ) I want to fetch all nested children of a folder. Obviously it can be done by recursively querying "find all objects with this parent_id", calling this recursively on all the found objects. But I'm wondering if there is a possibility in Django to do this in one query, so that I don't have to connect to the database X times but only once. What is the best approach here? -
Django: why ajax is not getting called even when alert onclick does
I've a form that processes my customers orders. However, I need to send the information submitted to other View, in this case that would be cart:cart_charge. In this view I do some processing, create the orders and save them in DB. However, my AJAX is not working. I only get it to alert the message, but apparently is not arriving to $.post part. <script> $('#depositButton').on('click', function (e) { alert('DepositButton Clicked'); $.post("{% url 'cart:cart_charge' %}", { amount: {{ total }}, currency_code: 'PEN', email: 'om@gmail.com', source_id: 10, last_four: 1111, shipping_address: shipping_address, }, ).done(function () { window.location.href = "{% url 'order:thanks' %}"; }) }); </script> -
Pre-fill django form fields "on-the-fly"
I would like to get your help because I don't overcome to pre-fill a django form field each time a dropdown value is selected in the previous field. I'm using Django 1.11.18 The context : I have a django form with some fields which let to make a research over the database. I'm focusing on 2 fields which are bounded together. My Model : class MemberState(models.Model): name = models.CharField(max_length=256, verbose_name=_('Name')) code = models.CharField(max_length=256, verbose_name=_('Code')) class RBI(models.Model): short_name = models.CharField(max_length=256, verbose_name=_('Short name'), unique=True) member_state = models.ForeignKey(MemberState, verbose_name=_('Member State')) ... My Form : class FinalProductSearchForm(forms.Form): releasing_body = ShortNameModelChoiceField(queryset=RBI.objects.filter(active=True).order_by('short_name'), required=False, widget=forms.Select(), empty_label=_('Select'), label=_('Releasing Body/Institution')) member_state = forms.ModelChoiceField(queryset=MemberState.objects.filter(active=True).order_by('name'), required=False, widget=forms.Select(), empty_label=_('Select'), label=_('Member state')) ... I would like to select a releasing_body in my form and prefill the member_state field associated. Each time I select a new value in the dropdown releasing_body field I would load the associated member_state. I tried some things : # Doesn't work because none releasing_body is loaded at the beginning def __init__(self, data=None, *args, **kwargs): super(FinalProductSearchForm, self).__init__(data, *args, **kwargs) releasing_body = self.fields['releasing_body'] self.initial['member_state'] = ReleaseBodyInstitution.objects.get(short_name=releasing_body).member_state I assume I need to use JS/AJAX ? Thank you -
Return ManyToManyField IDs when querying model in Django 2.1?
I have two very simple models: class Person(models.Model): full_name = models.CharField(max_length=120) class Event(models.Model): event_date = models.DateField() short_description = models.CharField(max_length=250) people_involved = models.ManyToManyField( Person, blank=True, related_name="people_involved" ) I want to return all events, including the people_involved. In views.py, I have the following: def alljson(request): events = Event.objects.values() return JsonResponse(list(events), safe=False) This returns: [ { "id": 9, "event_date": "2019-01-01", "short_description": "New Year's Party", }, ... ] How do I include the people_involved ManyToManyField in this response? -
Django: avoid race condition for field which value based on aggregation
There is example model: class MyModel(models.Model): name = models.CharField() version = models.IntegerField() I need to set version field value based on max version of instances with same name. To do this I override save method: def save(self, *args, **kwargs): max_version = MyModel.objects \ .filter(name=self.name) \ .aggregate(max_version=Max('version'))['max_version'] or 0 self.version = max_version + 1 super(MyModel, self).save(*args, **kwargs) How to avoid race condition here? -
How to create a user with AbstractBaseUser or AbstractUser. (Login Error)
I am trying to use my Person class as user in models.py. However I tried using AbstractUser and AbstractBaseUser. Both of them give me errors in the part where I try to log in, I tried several ways until I realized that I need help from someone with more experience and knowledge than I do. My models.py: from django.contrib.auth.models import AbstractUser from django.db import models class Pessoa(AbstractUser): id_pessoa = models.AutoField(primary_key=True) cnpj = models.CharField(max_length=14, unique=True) nome = models.CharField(max_length=70) email = models.CharField(max_length=100, blank=True, null=True) senha = models.CharField(max_length=40, null=False) ativo = models.BooleanField(blank=True, null=True) datacadastro = models.DateField(blank=True, null=True) cidade = models.CharField(max_length=50, blank=True, null=True) uf = models.CharField(max_length=2, blank=True, null=True) USERNAME_FIELD = 'cnpj' class Meta: managed = False db_table = 'pessoa' Detail: I am unable to remove or add fields in any template I am using, because I have used inespectdb to create the models based on the database i am using (the same one that is already full of data). Any change, with the exception of basic changes, is out of the cogitation. Below my views.py with def that validates the login and redirects to the dashboard. def dash_login(request): form = LoginForm(request.POST, None) if request.method == 'POST': #if form.is_valid(): username = form.data['cnpj'] password = form.data['senha'] … -
Django Admin not showing any model, even not Core (User/Groups)
Working on my first serious django project (which goes very well), I am facing a stupid problem with the admin site, that I can not find answers anywhere. My admin site does not show any models anymore (it did before), even not Users and Groups. empty admin I took out my own modules etc. from settings and urls, so they look like this now: """ Django settings for prototype_notar project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'g7+p!^igj=(fo%=&w0*rz$+@(@9@3)*wd!fi0om60+#8r@1)-t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'data_manager', # 'crispy_forms', ] 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', ] ROOT_URLCONF = 'prototype_notar.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': … -
Django Inlineformset Factory validation is not working
I have two forms one is supplier detail and one is contact for suppliers so I am using inlineformset_factory to combine both form and able to add contacts when I add supplier and that function is working good. The only problem is it show form validation error for the supplier form but not for the contacts (inlineformset). Forms.py class SupplierForm(forms.ModelForm): class Meta: model = Supplier fields = ('category','name','alternate_name','logo','address1','address2','city','zip','region','region_code','country','country_code','detail') class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('contact_type','job_title','first_name','last_name','phone','email','skype','wechat') def clean(self): if any(self.errors): return ContactFormSet = forms.inlineformset_factory(Supplier, Contact, form=ContactForm, extra=1) Views.py class CreateSupplierView(LoginRequiredMixin,CreateView): form_class = SupplierForm model = Supplier def form_valid(self, form): context = self.get_context_data() contacts = context['contacts'] with transaction.atomic(): self.object = form.save() if contacts.is_valid(): contacts.instance = self.object contacts.save() return super(CreateSupplierView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateSupplierView, self).get_context_data(**kwargs) if self.request.POST: context['contacts'] = ContactFormSet(self.request.POST) else: context['contacts'] = ContactFormSet() return context If supplier form is not valid it forwards it to add/edit form and show error but if supplier form is good the only contact has an error then it forwards that to supplier list and doesn't show any error. how can I show the same edit/add form with the error if contacts form is not valid?