Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle UniqueConstraint failure in Django Meta Class?
I have created a UniqueConstraint Meta Class for my model, and it works when I test it by intentionally creating a duplicate but I am getting an error page instead of being redirected back to the original page. Where do I insert the code to go back to the page that I was just on? I assume the issue is in the view, but I have no idea what code to put in there and the Django docs contain nothing alluding to this problem. Model: class StudentScheduledClass(models.Model): student = models.ForeignKey("users.User", on_delete=models.CASCADE, db_column="Student") scheduled_class = models.ForeignKey("ScheduledClass", on_delete=models.CASCADE, db_column="ScheduledClass") grade = models.FloatField(db_column="Grade", blank=True, null=True) class Meta: managed = True db_table = "StudentScheduledClass" verbose_name_plural = "StudentsScheduledClasses" constraints = [ models.UniqueConstraint(fields=['student', 'scheduled_class'], name='student scheduled class restraint') ] View: class StudentScheduledClassCreateView(LoginRequiredMixin, CreateView): model = StudentScheduledClass context_object_name = "student_scheduled_class" fields = ["student"] def form_valid(self, form): scheduled_class = self.kwargs["scheduled_class"] form.instance.scheduled_class = ScheduledClass(scheduled_class) return super().form_valid(form) def get_success_url(self): scheduled_class = self.kwargs["scheduled_class"] return reverse("scheduled-class-detail", args={scheduled_class}) I'd like to just go back to the original page with an error message, instead I get this traceback: IntegrityError at /classes/student_scheduled_class_create/1/ UNIQUE constraint failed: StudentScheduledClass.Student, StudentScheduledClass.ScheduledClass Request Method: POST Request URL: http://localhost:8000/classes/student_scheduled_class_create/1/ Django Version: 2.2.2 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: StudentScheduledClass.Student, … -
How to disable django registration password helpt_tetxt
I am new in Django,I have a Django registration page for New users,I and I need to disable the password and username and help_text.I have read through some similar questions about disabling the help_texts but none seem to disable the password help_texts. Here is my code : class CustomUserCreation(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2',] help_texts = { 'email' : None, 'username' : None, 'password1' : None, 'password2' : None, } class UpdateUser(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['email','username',] class UpdateProfile(forms.ModelForm): profile_picture = forms.ImageField() class Meta: model = Profile fields = ['profile_picture',] and my init from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True) def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None print UserCreateForm() -
Design solutions for multiple Django forms for POST form fields
I have a template page for multiple forms. The user chooses the form of choice and it is rendered. After the form is filled out the user submits it and the data goes through to a POST. At the moment the code has a long amount of if/else implementation that links what the form is to the POST. Right now, if I were to add a new form, I have to update my function that helps the user choose a form and renders that form. In addition, I have to update my function that sends a POST request for that specific form. I'm looking for a better design solution so I won't have to update both functions every time a new form is added. My current implementation follows this scheme... My form selector function if type is FormA return formA() //render elif type is FormB return formB() ... My form fill function if type is FormA return formA(request.POST) elif type is FormB return formB(request.POST, request.FILES) ... -
pages' + button for drop down menu gone after applying theme
I am using Mezzanine and in the admin page, when I go to "pages" each row doesn't show me options to make lower hierarchy page. For instance, from what I remember there was a button like Add.. it allowed me to make each row's expanding item pages. I still have some rows that still have this "drop down" and still working but further creation seems to have been somehow blocked. I downloaded some themes and just extracted it to my mysite folder (and it works) but I think maybe it affected the behavior of the admin website? How can I fix this? Thank you for your answer in advance. -
StackedInLine model object acces
Unable to get object of a StackedInline model using get_object_or_404 def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) -
Execute js in pdf view
I have rendered html as a string which will be returned as a PDF response class ReportFileResponse(FileResponse): def __init__(self, report, output_format): ....... # queries if output_format == 'pdf': super(ReportFileResponse, self).__init__(streaming_content=my_pdf_str, content_type='application/pdf') The problem is that the string contains some js that definitely needs to be executed (modify some blocks). It works in browser (as html), but does not execute in the PDF response. Are there any way to execute JS code? I think of using Selenium and to execute JS code. But I how to do that when you need to go to the page. But in my case I can't do that. I can't go to the page, because I have rendered html P.S. For the rendering we use django-weasyprint -
Many to many field doesn't work in django
I am trying to make a book site in django latest version and i need to create a many to many field. I have tried just putting it in the model like this Book model models.ManyToManyField(Genre) genre model class Genre(models.Model): genre=models.CharField(max_length=100,unique=True) def __str__(self): return self.genre views obj = Book.objects.get(id=1) obj=obj.author.all but it doesn't work it returns None,Then upgrading the str element Book model class Book(models.Model): name = models.CharField(max_length=100,unique=True) genre = models.ManyToManyField(Genre) text = models.TextField(unique=True) def __str__(self): template = '{0.name} {0.genre} {0.text}' return template.format(self) def get_absolute_url(self): """Returns the url to access a particular instance of the model.""" return reverse('model-detail-view', args=[str(self.id)]) Genre model class Genre(models.Model): genre=models.CharField(max_length=100,unique=True) def __str__(self): return self.genre views obj = obj.genre.count() Expected results see comedy and other genres , actual results None -
Inline 'add more' link not displaying in admin view
I have a TabularInline that I have added to a admin class. The inline shows OK within the admin view however the 'Add More' link does not display I have checked JS is 100% enabled as this can be an issue according to the Django docs. I have also checked and there are no console errors or network errors with loading any standard JS files. I have changed max_num, min_num and extra variables within the Inline class and nothing has changed admin.py: from django.contrib import admin from django.forms.models import BaseInlineFormSet from .models import Evaluation, MV1_test class MV1test(admin.TabularInline): extras=3 max_num=5 model = MV1_test verbose_name = 'MV1 Test' verbose_name_plural = 'MV1 Tests' class evaluationAdmin(admin.ModelAdmin): save_on_top=True fieldsets=( ('General',{ 'fields':(('view_link'),('rma_number','evaluation_status','customer_name','customer_email','order_number','serial_number','firmware'),('evaluator','evaluation_date','replacement')) }), ('Visual Evaluation',{ 'fields':( ('condition_heatsink', 'heatsink_notes'), ('condition_stem', 'stem_notes'), ('condition_oven', 'oven_notes'), ('condition_door', 'door_notes'), ('condition_matte_uv', 'matte_uv_notes'), ('condition_plating', 'plating_notes'), ('condition_bypass', 'bypass_notes'), ('condition_coil', 'coil_notes')), }), ('App Evaluation',{ 'fields':( ('ghost_app_connection','ghost_app_connection_notes'), ('ble_connection', 'ble_connection_notes'), ('firmware_update_connection','firmware_update_connection_notes') ) }), ('Haptic Evaluation',{ 'fields':( ('vape_button_haptic','vape_button_haptic_notes'), ('power_button_haptic', 'power_button_haptic_notes'), ) }), ('Battery Evaluation',{ 'fields':( ('usb_charge','usb_charge_notes'), ('fast_charger_charge', 'fast_charger_charge_notes'), ('battery_removal','battery_removal_notes') ) }), ('Over Door Evaluation',{ 'fields':( ('door_sensor','door_sensor_notes'), ('latch_spring', 'latch_spring_notes'), ('oven_door','oven_door_notes'), ) }), ('Performance',{ 'fields':( ('taste_performance','taste_performance_notes'), ('odor_performance', 'odor_performance_notes'), ) }), ('ABV',{ 'fields':( ('abv_pic', 'abv_thumbnail'), ('abv_notes'), ) }), ('Evaluation Summary',{ 'fields':( ('evaluation_summary'), ) }) ) inlines=[MV1test] search_fields = ('serial_number', 'customer_name','customer_email','evaluator__username')#__username means … -
How to create a collapsable form in Django with JQuery?
I am trying to create a collapsible form in Django which would toggle a form once a button is clicked. I found that I could use the .toggle() option from JQuerry but I don't know how to connect the associated form with the function The "toggles all paragraphs" example from http://api.jquery.com/toggle/ seems to be what I need but I'm not sure how to integrate it. <form method="post"> {% csrf_token %} <div class="row align-items-center"> <div class="col-sm-8"> <table> {{ form1.as_table}} </table> <div class="mx-sm-2"> <input type="submit" value="Submit"> </div> <br> <br> <h3 class = "text-success">Add Sensor View</h3> <table> {{ form2.as_table}} </table> <div class="mx-sm-2"> <input type="submit" value="Submit"> </div> <br> <br> </div> <div> </form> I would like form2 to be toggled only once a button is pressed -
How to export .csv with Django-Tables2?
I'm trying to export a table in .csv with Django-Tables2, I've done the following so far. tables.py class ClientTable(ColumnShiftTable): class Meta: model = Client sequence = ('id', 'nome_razao_social', 'cpf', 'cnpj', 'sit_fiscal') template_name = 'django_tables2/bootstrap.html' views.py class ClientsView(ExportMixin, CustomListView): template_name = 'relatorios/clients/geral.html' model = Client table_class = ClientTable context_object_name = 'all_clients' permission_codename = 'view_clients' def get_context_data(self, **kwargs): context = super(RelatorioClientsView, self).get_context_data(**kwargs) table = ClientTable(Client.objects.all()) table.paginate(page=self.request.GET.get('page', 1), per_page=15) context['table'] = table RequestConfig(self.request).configure(table) export_format = self.request.GET.get('_export', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response('table.{}'.format(export_format)) return context template.html <div class="tabel" style="overflow-x: auto; white-space: nowrap;"> {% load render_table from django_tables2 %} {% render_table table %} {% export_url "csv" %} </div> But I get this error Invalid block tag on line 56: 'export_url', expected 'endblock'. Did you forget to register or load this tag? if I remove {% export_url "csv" %} the error stops appearing, but I do not have the link. -
Django queryset: order_by ForeignKey boolean attribute
I'm trying to order a queryset so that: the first elements of the queryset are those which have a ForeignKey boolean attribute (first) set to True, and amongst them, they are ordered by creation date the following elements are those having ForeignKey first attribute set to False, and again amongst them, they are ordered by creation date Here is an example of the models: class A(models.Model): first = models.BooleanField(blank=False, default=False) class B(models.Model): a = models.ForeignKey(A) created = models.DateTimeField(auto_now_add=True) The queryset looks like: queryset = B.objects.all().order_by("-a__first", "-created") This snipper, however, is not doing the work. A solution that I'm thinking of is to use two different databases call (one filtering for a__first=True and the other filtering for a__first=False), and then sum up the querysets results. But I would like to understand if there is a better and cleaner way of solving this problem. -
Django : Storage of unique, important and frequently changing constants
I am using django for my backend. I wanted to ask how to store import constants in django which are: 1) Unique ex. GST rate i.e. 0.18, some switch like constants which can turn some features on/off 2) Can change frequently , need to be updated by some non tech guy frequently. How to store such constants. Should it be stored in settings file? Then there will problem in updation without changing the code. Doesn't seem like a good option 2.Should be stored as an environment variable? Still some efforts required. 3 In Cache. Seems like a good options. But cant figure out the fatalities of storing in cache. 4 In Database. Seems good but what will be structure. Will there be a table containing all import constants with simple attributes like key and value and key is unique. 5)Combination of db and cache Could someone guide me what is the best option. -
Send logging messages with sentry for loggers with propagate false
I'm using django and sentry-sdk. In my django settings' logger section I have the following handler: 'loggers': { 'my_module': { 'level': 'WARNING', 'handlers': ['console', ], 'propagate': False } } And the sentry-sdk is initialized as follows: import logging import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.logging import LoggingIntegration sentry_logging = LoggingIntegration( level=logging.INFO, event_level=logging.ERROR ) sentry_sdk.init( dsn="...", integrations=[DjangoIntegration(), sentry_logging], ) However, the following example does not send an error event to sentry import logging logger = logging.getLogger('my_module') logger.error('Why do I not appear in sentry?') On the other hand, others do, as for example import logging logger = logging.getLogger('another_module') logger.error('Why do I not appear in sentry?') Question: How can I fix this for modules with propagate=False? -
Images are not getting loaded from static file
I have added bootstrap template to my Django project. I am facing the problem with the images are not getting load when check index.html in local host, when I inspect the html code it's showing error like this "GET /images/destination_4.jpg HTTP/1.1" 404 2300" while All other static files are getting loaded. Please let me know the solution. -
Django Template - Regroup and order by number of items in the re grouping?
Im regrouping a query set in a template and I then want to order the grouped results by how many items are in each group. printing our the regrouped list I get the below data: GroupedResult(grouper=<CircuitType: FTTC>, list=[<DeviceCircuitSubnets: DeviceCircuitSubnets object (7406)>]), GroupedResult(grouper=<CircuitType: DSL>, list=[<DeviceCircuitSubnets: DeviceCircuitSubnets object (7415)>, <DeviceCircuitSubnets: DeviceCircuitSubnets object (7321)>]), GroupedResult(grouper=<CircuitType: 4G>, list=[<DeviceCircuitSubnets: DeviceCircuitSubnets object (7412)>, <DeviceCircuitSubnets: DeviceCircuitSubnets object (7413)>, <DeviceCircuitSubnets: DeviceCircuitSubnets object (7414)>])] So looking at the above there are 1 x FTTC item, 2 x DSL items, and 4 x 4G items. Id then like the groups to be put in the order below when displayed in the template 4G,DSL,FTTC does anyone know if this is possible to do? Thanks -
Passing initial value in formset
Models attendance_choices = ( ('absent', 'Absent'), ('present', 'Present') ) class Head_of_department(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=30) def __str__(self): return self.first_name class Employee(models.Model): first_name = models.CharField(max_length=200, unique=True) last_name = models.CharField(max_length=200, unique=True) head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Attendance(models.Model): head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) employee = models.ForeignKey('Employee', on_delete=models.CASCADE, ) attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True) How to pass employees as initial values for attendance model as shown below in the images, employees will be rendered and rendered values have to be passed as employee in attendance model. Is there any workaround with modelformset or inlineformset ? I can't get it right -
How to use pg_restore with AWS RDS correctly to restore postgresql database
I am trying to restore my Postgresql database to AWS RDS. I think I am almost there. I can get a dump, and recreate the db locally, but I am missing the last step to restore it to AWS RDS. Here is what I am doing: I get my dump $ pg_dump -h my_public dns -U myusername -f dump.sql myawsdb I create a local db in my shell called test: create database test; I put the dump into my test db $ psql -U myusername -d test -f dump.sql so far so good. I get an error: psql:dump.sql:2705: ERROR: role "rdsadmin" does not exist, but I think I can ignore it, because my db is there with all the content. (I checked with \list and \connect test). Now I want to restore this dump/test to my AWS RDS. Following this https://gist.github.com/syafiqfaiz/5273cd41df6f08fdedeb96e12af70e3b I now should do: pg_restore -h <host> -U <username> -c -d <database name> <filename to be restored> But what is my filename and what is my database name? I tried: pg_restore -h mydns -U myusername -c -d myawsdbname test pg_restore -h mydns -U myusername -c -d myawsdbname dump.sql and a couple of more options that I don't recall. Most … -
Django infinite scroll by SIBTC
def test_test(request): if request.method == 'GET': query = request.GET.get("query") if query: mylist = range(1, 100) numbers_list = [i for i in mylist if (i % int(query) == 0)] else: numbers_list = range(1, 100) else: numbers_list = range(1, 100) """ Pagination """ page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 10) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) context = {'numbers': numbers} return render(request, 'myapp/test.html', context) -
Cant access my "Category" model in html file
I cant access my Category model in html. I access from shell by tapping " Category.objects.all()". I access my Item model but not Category model. It's about Category model's structure i guess. But i cannot figure out how to fix this. Here's my models.py: class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Item(models.Model): seller = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.PROTECT) title_image = models.ImageField(upload_to='media/img', default='None') created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(auto_now=True, verbose_name="Updated at") published_date = models.DateTimeField(blank=True, null=True) is_published = models.BooleanField(default=False, verbose_name="Is published?") end_date = models.DateTimeField(blank=False, default=seven_days_hence) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py : def category_list(request): categories = Category.objects.all() return render(request, 'blog/item_list.html', {'categories': categories}) urls.py : urlpatterns = [ path('', views.item_list, name='item_list'), path('', views.category_list, name='category_list'), path('item/<int:pk>/', views.item_detail, name='item_detail'), path('item/new/', views.item_new, name='item_new'), path('item/<int:pk>/edit/', views.item_edit, name='item_edit'), ] base.html : {% load staticfiles %} <html> <head> </head> <body> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> item_list.html : {% extends 'blog/base.html' %} {% block content %} {{ categories }} {{ items }} {% endblock %} -
Is there any way to get primary key using record when creating tables in django_tables2
I'm trying to get the primary key of my table in tables.py using django-tables2 by using the variables record.pk. I supposed that record.pk exist originally but somehow it's not. class TableServeur(tables.Table): type_server = tables.Column() memory = tables.Column(attrs={"td": {"class": "memory"}}, verbose_name="% Mem") cpu = tables.Column(attrs={"td": {"class": "cpu"}}, verbose_name="% Cpu") port = tables.Column() etat = tables.Column() # here is the problem T1 = '<a class="btn" href="/update/{{record.pk}}" >Icon</a>' action = CustomTemplateColumn(T1) class Meta: fields = ["type_server", "cpu", "memory", "port", "etat", "action"] template_name = "django_tables2/bootstrap4.html" So is there any way I can get the primary key directly when creating a table using django-tbales2? -
How to fix 'TypeError: isinstance() arg 2 must be a type or tuple of types' during running tests in django in docker on windows
I recently moved to docker. My application is working right now. I'm running python manage.py test in my project. But i got tons of errors 'TypeError: isinstance() arg 2 must be a type or tuple of types'. Same setup works under linux machine. And right now I am using Windows 10 one. Main docker image is ubuntu14.04, using python version 3.5.2, here is my pip freeze: amqp==2.5.0 atomicwrites==1.3.0 attrs==19.1.0 Babel==2.7.0 backcall==0.1.0 billiard==3.5.0.2 celery==4.1.0 decorator==4.4.0 dictdiffer==0.5.0.post1 dicttoxml==1.6.6 Django==2.0.2 django-common-helpers==0.9.2 django-cron==0.5.0 django-model-utils==3.0.0 django-params==0.3 django-pipeline==1.6.8 django-pytest==0.2.0 django-ranged-response==0.2.0 django-redis==4.8.0 django-simple-captcha==0.5.9 django-widget-tweaks==1.4.1 djangorestframework==3.7.7 et-xmlfile==1.0.1 factory-boy==2.8.1 Faker==0.7.7 fakeredis==0.8.2 flower==0.9.2 importlib-metadata==0.17 ipdb==0.12 ipython==7.5.0 ipython-genutils==0.2.0 jdcal==1.4.1 jedi==0.13.3 Jinja2==2.10.1 JPype1==0.6.1 kombu==4.1.0 lxml==3.6.0 MarkupSafe==1.1.1 more-itertools==7.0.0 openpyxl==2.4.1 packaging==19.0 parso==0.4.0 pathlib2==2.3.3 pexpect==4.7.0 pickleshare==0.7.5 Pillow==2.7.0 pluggy==0.12.0 prompt-toolkit==2.0.9 psycopg2==2.7.5 ptyprocess==0.6.0 py==1.8.0 Pygments==2.4.2 pyparsing==2.4.0 pytest==4.6.2 pytest-django==3.5.0 python-dateutil==2.8.0 pytz==2016.3 redis==2.10.6 reportlab==3.3.0 six==1.12.0 sqlparse==0.1.0 tornado==5.1.1 traitlets==4.3.2 vine==1.3.0 wcwidth==0.1.7 xlwt==1.1.2 zipp==0.5.1 self = <django.db.models.fields.DateTimeField: created_at>, value = datetime.datetime(2019, 6, 5, 16, 23, 2, 463090) def to_python(self, value): if value is None: return value > if isinstance(value, datetime.datetime): E TypeError: isinstance() arg 2 must be a type or tuple of types /usr/local/lib/python3.5/dist-packages/django/db/models/fields/__init__.py:1353: TypeError and here is full trace Traceback (most recent call last): File "/code/app/app/test_api.py", line 19, in setUp self.user= UserFactory(role=User.ROLE_ADMIN, is_superuser=True) File "/usr/local/lib/python3.5/dist-packages/factory/base.py", line 69, in __call__ return … -
POST to TestUpdateView updates existing object and creates new object
I have a test for an UpdateView that is: Updating the existing object Then trying to create a new blank object at the same time This behavior does not happen when I run through the view in the browser, so it is something to do with how the test is running. POST to the update URL Request runs through the UpdateView Form_valid() runs and hits instance.save() Then something is causing a second object to be created right after it saves the original object Any ideas? The Test class TestReviewUpdateView(TestCase): def setUp(self): self.review = ReviewFactory() self.submission = self.review.submission self.factory = RequestFactory() self.kwargs = {'submission_pk': self.submission.pk} def test_form_valid_with_object(self): self.request = self.factory.post(reverse( 'submissions:review_update', kwargs=self.kwargs)) # Create user self.request.user = StaffFactory() view = views.ReviewUpdateView() view.request = self.request view.object = self.review kwargs = { 'scores': self.review.get_list_of_scores() } form = forms.ReviewForm(**kwargs) form.cleaned_data = {'axe_0': '4', 'axe_1': '4', 'axe_2': '4'} response = view.form_valid(form) assert response.status_code == 302 The View class ReviewUpdateView( BaseReviewForm, UpdateView ): """ A view for updating reviews. """ def dispatch(self, request, *args, **kwargs): self.submission = self.get_submission() self.conference = self.submission.conference return super().dispatch(request, *args, **kwargs) def get_object(self): return self.model.objects.get( submission=self.submission, user=self.request.user) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({ 'scores': self.object.get_list_of_scores(), }) return kwargs def save_scores(self, form, instance): … -
Implement widget with forms.ModelForm
How to implement date picker or any widged with forms.ModelForm when you use fields = 'all' models.py class Posudba(models.Model): nazivKnjige = models.ForeignKey(Knjiga, on_delete=models.CASCADE, null=False) nazivProdavaca = models.ForeignKey(User, on_delete=models.CASCADE, null=False) nazivKupca= models.ForeignKey(Kupac, on_delete=models.CASCADE, null=False) Datum = models.DateField(null=False, blank=False) kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.nazivKnjige) + ', ' + str(self.nazivProdavaca) + ', ' + str(self.nazivKupca) + ', ' + str(self.Datum) Forms.py class PosudbaForma(forms.ModelForm): class Meta: model = Posudba fields = '__all__' -
Why is error displayed on the wrong form field in django?
I have django based website with django-form-ajaxified forms. On one page I have multiple forms with unique form id. Each form is loaded by ajax on the unique url. When some form field error occurs, error is displayed on the wrong field. Below is HTML code of one form returned by ajax (django-form-ajaxified). Django view is standard AjaxFormViewMixin, UpdateView all of testing, template changes,... <form id="1427" method="post" class="col-xs-12" action="URL" data-class="form_ajaxified"> <table class="table responsive"> <tbody> <tr> <th></th> <th></th> </tr> <tr> <td class="col-xs-5"> <div class="form-group"> <label class="control-label col-xs-8 " for="id_answer_date">Date</label> <div class=" col-xs-4 "> <input class=" form-control" id="id_answer_date" name="answer_date" type="text" value="01.01.2018"> </div> </div> </td> <td class="col-xs-2"> <div class="form-group"> <label class="control-label col-xs-8 " for="id_result">DDDDD</label> <div class=" col-xs-4 "> <select class=" form-control" id="id_result" name="result"> <option value="-">----</option> <option value="Ne">Ne</option> <option value="Ano" selected="selected">Ano</option> <option value="NR">NR</option> </select> </div> </div> </td> </tr> </tbody> </table> </form> -
How to manage 2 settings files in Django by using Honco app?
My question is based on the following existing question: Django: How to manage development and production settings? Basically if I want to have 2 or more settings.py files I could use Honcho https://honcho.readthedocs.org/en/latest/ to do it . Question is , in *.env file what exact code should I write to use for example following settings file: “myproject.production_settings.py” something like this? DJANGO_SETTINGS_MODULE=myproject.production_settings or it should be different somehow? Thank you!