Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "<User: user.name>: must be a "User" instance
I am having an issue writing a custom django migration where I am trying to set a field value for a model to a user. The model in question is shown below (CustomerMachine). This model uses the django-simple-history module to track changes in model instances. I am attempting to query the instance history in the migration and set the review_submitter value to the last user which edited the instance. The result of the history query history_user returns a <class 'django.contrib.auth.models.User'> type, but when I try to set the review_submitter to that value I get the following error: ValueError: Cannot assign "<User: user.name>": "CustomerMachine.review_submitter" must be a "User" instance. Any insight into whats going on here? simplified class example class CustomerMachine(models.Model): review_submitter = models.ForeignKey(settings.AUTH_USER_MODEL, default=None) history = HistoricalRecords() custom migration from __future__ import unicode_literals from __future__ import absolute_import from django.conf import settings from django.db import migrations, models from django.contrib.auth.models import User from acceptance.models import CustomerMachine def set_submitter(apps, schema_editor): machines = apps.get_model('acceptance', 'CustomerMachine') for machine in machines.objects.all(): history = CustomerMachine.history.filter(serial=machine.serial) if history: history_user = history.last().history_user machine.review_submitter = history_user machine.save() def reverse_func(apps, schema_editor): pass # code for reverting migration, if any class Migration(migrations.Migration): dependencies = [ ('acceptance', '0031_auto_20200914_1611'), ] operations = [ migrations.RunPython(set_submitter, … -
Django Admin multiple count issue
I have an issue with duplicated call of count method from Django Admin. Here is my code. class AdminPaginator(Paginator): @property def count(self): cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table]) count = int(self.cursor.fetchone()[0]) return count ... Code from Admin Model list_per_page = 50 show_full_result_count = False def get_queryset(self, request): """ Overrides default query to exclude test entities. """ qs = super().get_queryset(request) active_entities = qs.filter(is_active=False) return qs.exclude(id__in=active_entities) count method calls for 4 times and I don't know why. Thanks for your help! -
Django can't get REMOTE_USER
I need to create SSO Authentication using Kebreros in my Django project. I faced with problem when tried to get username from request.META['REMOTE_USER']. KeyError happens. It seems that variable REMOTE_USER is not set but I don't understand why. I added RemoteUserMiddleWare and RemoteUserBackend as it's said in docs. 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.auth.middleware.PersistentRemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend',] Apache config: <VirtualHost *:80> ServerName test.wit.net ServerAlias test.wit.net DocumentRoot /var/www/test.wit.net/public_html ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ ProxyPreserveHost On ProxyTimeout 300 RequestHeader set X-Forwarded-Proto "http" <Location "/"> # Kerberos authentication: AuthType Kerberos AuthName "SRV-APP auth" KrbMethodNegotiate on KrbMethodK5Passwd off KrbServiceName HTTP/test.wit.net@WIT.NET KrbAuthRealms WIT.NET Krb5Keytab /etc/krb5.keytab KrbLocalUserMapping On Require valid-user </Location> SSO works Apache authentificate user successfully, but I can't pass REMOTE_USER to Django. What could be wrong? -
Create new models from an existing one
need some help with the next issue: I got this model in Django: class myModel(models.Model): Name = models.CharField(max_length=50) parameter1 = models.IntegerField(null=True) parameter2 = models.IntegerField(null=True) # # parametern = models.IntegerField(null=True) The "Name" field is limited to 5, and it gets data to update the rest of the fields, giving as result a main table with n entries wich repeat name but have differents parameters. I want to create 2 table from this main one as follow: The first table has to group up the data by names adding the values of each parameter. The result should be a table with 5 names and the total of each parameter. The second table is the same, but giving the average for each parameter. One solution may be to create and delete each table every time the main table its updated, but im not sure if this is the best way to do it. appreciate any help! Thx to everyone! -
Ajax Upload Image files- Django Forms
I try to upload image, using Ajax with django forms. It not return errors.(This field is requred). So Please help me any one, Here is my code. forms.py class RegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = Employee fields = ( 'name', 'photograph', ) models.py photograph = models.FileField(upload_to="employee/") Ajax $(document).ready(function () { $('#saveEmployee').click(function (e) { var serializedData = $("#employee").serialize() e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "empcheckurl" %}', data: serializedData, success: function (data) { alert('data.successMessage'); } }); return false; }); }); views.py def post(request): form = RegistrationForm() if request.method=="POST": form = RegistrationForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): alldata = form.save() return JsonResponse({'alldata': model_to_dict(alldata),'successMessage':'Employee resisters successfully'}, status=200) else: return redirect('registeredusers') -
restore postgreSQL database on Django project
I'm working on an application that runs on Ubuntu 18.04, it consists of Django App and PostgreSQL server, each on runs in a separate Docker container. I created a backup for my database, so I can keep it and runs it on a test server for test cases. Now I'm moving my backup database to another test server, but the problem is when I run: docker-compose -f production.yml up both containers of Django & PostgreSQL run fine, the problem is which should I do first to make everything working on the test server, like everything working on the production server? should I restore backup database first then run: python manage.py migrate or should I migrate then restore backup database, actually I ran both, and each time after successfully end both I got this error: ProgrammingError at /accounts/login/ so what should I do to restore backup database? Anther question: I tried to ignore the backup database and just run: python manage.py migrate and create a database from scratch but I got the same error as before!!! I'm there is something common I'm wrong with, so help me with any information on the theory of backup database, please. -
string indices must be integers while passing ObjectId through URL in Django
I am building a website in django and using mongodb as a database. I want to pass the objectID of mongodb document through url. I am applying the custom filter on it, but I am keep getting this error "string indices must be integers" on 'object|mongo_id' what am I doing wrong? Here is my code: user.html {% load get_id %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Document</title> </head> <body> <nav class="navbar navbar-inverse"> <div style="padding-left: 1200px;" class="container-fluid"> <button class="btn btn-danger navbar-btn"><a href="{% url 'login_view' %}">Log Out</a></button> </div> </nav> <br> <div style="padding-left: 1100px;"> <button type="button" class="btn btn-success"> <a href="{% url 'new_job' object|mongo_id %}">Post Job</a> </button> </div> </body> </html> get_id.py from django import template register=template.Library() @register.filter(name="mongo_id") def mongo_id(value): return str(value['_id']) -
Taggit in list_filter doesn't refresh if any of the tags is deleted in Django
I'm using Taggit for tagging a post in my Django app. I've added list_diplay and list_filter for the Admin model view and both are working. The problem is that if I go and delete a tag as an Admin, the list_filter won't refresh and stop showing that tag. If I add another tag, the list will refresh and work. Admin.py class UploadedAdmin(admin.ModelAdmin): list_display = ('name', 'time_uploaded', 'file', 'tag_list') list_filter = ['time_uploaded', 'tags'] def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): return u", ".join(o.name for o in obj.tags.all()) # Register your models here. admin.site.register(Uploaded, UploadedAdmin) -
Passing slug into ListView URL
I wanted to pass slug into ListView. But it was not as simple as passing it to DetailView. That's because, ListView doesn't have built-in slug support. I found answer of my question and I want to share with you, guys. -
Unable to resolve Reverse for 'create_order' with no arguments not found
The issue is already been discussed here... Reverse for 'create_order' with no arguments not found i get an error. django.urls.exceptions.NoReverseMatch but there is nothing mentioned on how to solve the issue. can somebody help? This is code iam getting an error .. dashboard.html <div class="col-md-7"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' customer.id %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{order.product}}</td> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td> </tr> {% endfor %} </table> </div> // When i remove the link href ( i,.e create order ) then the URL works fine Corresponding views def createOrder(request, pk): #def createOrder(request): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra = 10 ) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method == 'POST': #form = OrderForm(request.POST) formset = OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context = {'formset':formset} return render(request, 'accounts/order_form.html', context) there some one told the create order button is commented, but nothing. This the part of the exception iam getting Tracee Error Internal Server Error: / Traceback (most recent call … -
TypeError when Django authenticate function tries to bind to custom authenticate function
I am attempting to implement an authentication method where: the user submits their email I generate a token for that user that is stored in the database, or I retrieve the token if it already exists I generate a link to log in and email it to the user, with the token as an HTTP parameter The token is extracted from the link and used to search for an active user The user info is passed to the template Note that this isn't for any mission-critical production software - I'm reading the Obey The Testing Goat O'Reilly book and this is the authentication method the author has us implement. So when the user clicks the link in their email, this is the view function that handles it: from django.contrib.auth import authenticate, login def login(request): uid = request.GET.get('uid') user = authenticate(uid=uid) if user is not None: login(request, user) return redirect('/') In that view function, we call the authenticate function that is provided by django.contrib.auth. Here is that function: def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): backend_signature = inspect.signature(backend.authenticate) try: backend_signature.bind(request, **credentials) except TypeError: # This backend doesn't accept … -
A Coroutine is returning a coroutine after await
I'm writing tests for a fastAPI on django with an ASGI server (adapted this tutorial). My fastAPI side of the test keeps returning errors and I'm trying in vain to fix it. My need is about creating a user to test the API. @sync_to_async async def _create_user(self, username, email): try: return User.objects.create(username=username, email=email) except Exception as e: await print(e) return None async def setUp(self): task = asyncio.create_task(self._create_user(username="user", email="email@email.com")) self.user = await task Running this test, it turn out that self.user is a coroutine and it's impossible to access the attributes I expect. How to solve this ? -
problem on loading tensorflow models in django website backend in pythonanywhere hsoting
I trained few tensorflow models and saved them using h5 extension.I am trying to load them in django backend in a view.All versions that i use are latest for django,tf and python. models['1'] = load_model("static/car_model.h5",compile=False) models['2'] = load_model("static/model1.h5",compile=False) models['3'] = load_model("static/model2.h5",compile=False) models['4'] = load_model("static/model3.h5",compile=False) models['5'] = load_model("static/model4.h5",compile=False) This code worked for me in testing.BUt when i try to host it in pythonanywhere First i got errors on path as model not found.Later I tried to change path to os.get_dir("static")+modelname.h5 After running it there is a error message saying could not load backend "Error code: 502-backend" I am confused what to change and where is actual problem.please help thanks. -
pdfkit : header containing watermark not repeating
In my Django project, I need to add watermark on all the pages of the pdf document being generated. I initially tried with regular css but ended up getting multiple watermarks per page. To work around it, i created a template only for header and mapped it against a url. my header.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <style> #watermark { position: fixed; z-index: 99; opacity: 0.5; top: 300px; } </style> </head> <body> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div> </body> </html> in my urls.py re_path(r'^header/$', views.header), I'm passing this as options in pdfkit as follows : _options = { 'cookie': [ ('csrftoken', options.get('csrftoken','none')), ('sessionid', options.get('session_key','none')), ], 'footer-center': 'Page [page] of [topage]', 'footer-right': DOC_VERSION.get(doctype,''), 'footer-font-size': '9', 'header-html': 'http://127.0.0.1:8000/b/header/', } ISSUE : when pdf is generated, the header is getting printed only on the first page and the footer related configurations have been lost. -
How can i get the name of the Foreign Key on Django List View with qyery returns None
I want to display on the page the name of categoria When there is at least one series, I can get the name. Otherwise, it just returns none! I am trying to create a new context variable to pass the categoria name. But I fell I am doing something wrong... and complicated also... Can someone help me to pass the categoria name into template even if there is no series returned? Thanks... Error Displayed DoesNotExist at /categoria/15 Categoria matching query does not exist. Request Method: GET Request URL: http://localhost:8000/categoria/15 Django Version: 3.1 Exception Type: DoesNotExist Exception Value: Categoria matching query does not exist. view.py class CatergoriasSeriesView(ListView): model = Serie template_name = 'categorias_series_of.html' paginate_by = 10 def get_queryset(self): return Serie.objects.filter(categoria=self.kwargs['categoria']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cat'] = self.kwargs['categoria'] context['cat_name'] = Categoria.objects.get(categoria=self.kwargs['categoria']) return context models.py class Categoria(models.Model): categoria = models.CharField( max_length=200, verbose_name="Nome da categoria", help_text="colocar aqui o texto de ajuda") class Meta: verbose_name_plural = "Categorias" verbose_name = "categoria" def get_absolute_url(self): return reverse('series_da_categoria', kwargs={'pk': self.pk}) class Serie(models.Model): serie = models.CharField( max_length=200, verbose_name="Série", help_text="colocar aqui o texto de ajuda") categoria = models.ForeignKey( Categoria, default=1, on_delete=models.SET_DEFAULT) HTML template {% if object_list %} {% for serie in object_list %} <div> {% if forloop.first %} <h1 … -
How to reload Django context from JavaScript w/out redirect?
I am developing a dictionary application and a simple bookmark page where bookmarked definitions are displayed. I am using JavaScript to add/remove a definition to/from bookmarks through a button. The button works. However, when I am on the bookmarks page and I press it to remove a definition from my bookmarks, the definition stays there until I reload the page. I would like the definition to disappear as soon as I hit the button through JavaScript. I tried to remove the parentNode of my button (the div for definition) but it looks horrible, and that's not what I am looking for. I am now trying to send an AJAX request to my Django bookmarks view to re-load the context, but so far I haven't been able to do it. Can anybody help? Here is my Javascript code (the ? is where I am stuck): function toggleBookmark(event) { // Get definition id. let id = event.target.id.split("-")[1]; // Send AJAX request to bookmark view. $.get("/bookmarks/bookmark/" + id, function (data) { if (data.added) { alert('Definition added to your bookmarks.') event.target.innerHTML = 'Remove definition from your Bookmark'; } else if (data.removed) { alert('Definition removed from your bookmarks.') event.target.innerHTML = 'Add definition to your Bookmarks'; … -
sql query don't work in django: "not enough arguments for format string error in django"
I write a SQL query in MySQL and It runs correctly but when I use this query in Django, it runes with error. I delete space of "Title" in the database. When user enter something in the search field, I also delete space in the user text, and then start to search in the database whether the user text contains in title or not. Error: SQL query: Model: # Business (کسب و کار) Model class Business(models.Model): title = models.CharField(verbose_name = 'عنوان', max_length = 255) slug = models.SlugField(verbose_name = 'شناسه', unique = True) FK_CEO = models.ForeignKey(User, verbose_name = 'admin', related_name = 'business_admin_user', on_delete = models.SET_NULL, null = True) description = models.TextField(verbose_name = 'توضیحات', blank = True) createdate = models.DateTimeField(verbose_name = 'تاریخ ثبت', auto_now_add = True) state = models.CharField(verbose_name = 'استان', max_length = 50, blank = True) city = models.CharField(verbose_name = 'شهر', max_length = 50, blank = True) address = models.TextField(verbose_name = 'آدرس', blank = True) FK_Point = models.ManyToManyField('Point', verbose_name = 'امتیازات', related_name = 'business_point', blank = True) FK_Comment = models.ManyToManyField('Comment', verbose_name = 'نظرات', related_name = 'business_comment', blank = True) phone = models.CharField(verbose_name = 'شماره تماس', max_length = 11, blank = True) support_number = models.CharField(verbose_name = 'شماره تماس پشتیبانی', max_length = 11, … -
ValueError: Field 'id' expected a number but got 'choice'
please help when I execute python manage.py migrate I get this error Traceback: (FM) C:\projects\AM\FM\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0009_auto_20200914_1002...Traceback (most recent call last): File "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'choice' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self.remake_table(model, create_field=field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in remake_table self.effective_default(create_field) … -
Creating Login/Logout View Django REST API
My Question is: How to create a Login and Logout View, were the user is able to Login/Logout? I am using DjangoRestFramework-SimpleJWT, The user is able to obtain a JSONWebToken. Thanks. -
Is it possible to pass a list into includes variables with Django?
I'm trying to create a reusable sub template to use on my pages that's something like this: <div> <h1>{{ heading }}</h1> <p>{{ copy }}</p> <ul> {% for list_item in list %} <li>{{ list_item }}</li> {% endfor %} </ul> </div> But, I'm wondering if it's possible to pass a list into the include? Maybe something like this? {% includes 'template.html' with list="['list_item1', 'list_item2']" %} -
Change Django self describing api
I built an api using django which has a user. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) phone = models.CharField(validators=[validate_phone_number], max_length=20) I am using ModelViewSet to automatically generate the crud methods. However, I add two new routes which are login and signup: class ClientViewSet(viewsets.ModelViewSet): queryset = models.Kindergarten.objects.all() serializer_class = serializers.KindergartenSerializer @action(detail=False, methods=['POST'], name='signup') def signup(self, request): return self.create(request) @action(detail=False, methods=['POST'], name='login') def login(self, request): serializer = serializers.UserSerializer(data=request.data) username = request.data['email'] raw_password = request.data['password'] user = authenticate(username=username, password=raw_password) login(request, user) return Response(serializer.data) Then I route like this : router = routers.DefaultRouter() router.register(r'client', views.ClientViewSet) My problem is when I open my documentation I get to fill field that I do not need : How can I better customize the self description view ? Thanks ! -
While defining method for autosaving in CreateView for ManyToMany field Error shows
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are: Personal_info Models.py class Personal_info(models.Model): gen_choices = ( ("पुरुष", "पुरूष"), ("महिला", "महिला"), ("तेस्रो", "तेस्रो"), ) pinfo_id = models.AutoField(primary_key=True) userid = models.OneToOneField(User, on_delete=models.CASCADE) nfullname = models.CharField(validators=[max_len_check], max_length=128) efullname = models.CharField(validators=[max_len_check], max_length=128) dob_ad = models.DateField() dob_bs = models.DateField() gender = models.CharField(max_length=6, choices=gen_choices) citizen_no = models.CharField(max_length=56) cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE) cissue_date = models.DateField() language = models.CharField(max_length=56) p_district = models.CharField(max_length=56) p_vdc = models.CharField(max_length=56) p_ward = models.CharField(max_length=2) p_city = models.CharField(max_length=56) t_district = models.CharField(max_length=56) t_vdc = models.CharField(max_length=59) t_ward = models.CharField(max_length=2) t_city = models.CharField(max_length=56) telephone = models.BigIntegerField(null=True, blank=True) mobile = models.BigIntegerField() mother_name = models.CharField(validators=[max_len_check], max_length=128) mother_cit = models.CharField(max_length=10, null=True) father_name = models.CharField(validators=[max_len_check], max_length=128) father_cit = models.CharField(max_length=10, null=True) gfather_name = models.CharField(validators=[max_len_check], max_length=128) gfather_cit = models.CharField(max_length=10, null=True) spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True) spose_cit = models.CharField(max_length=10, null=True, blank=True) image = models.FileField(upload_to="photos/", null=True, blank=True) cit_image = models.FileField(upload_to="citizens/") inclu_image = models.FileField(upload_to="inclusions/", null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager def __str__(self): return str(self.efullname) Educational Models.py class Education(models.Model): edu_id = models.AutoField(primary_key=True) userid = models.ForeignKey(User, on_delete=models.CASCADE) institute = models.CharField(max_length=255, validators=[max_len_check]) board = models.CharField(max_length=128, validators=[max_len_check1]) pexam = models.CharField(max_length=16, choices=exam_choices) faculty = models.CharField(max_length=16, choices=fac_choices) division = models.CharField(max_length=16, validators=[max_len_check2]) tmarks = models.IntegerField() percent = models.FloatField(null=True, blank=True) mainsub … -
Crispy Forms: Align dynamically
I add some forms to my page dynamically - I always start with a name field and add multiple others depending on a database entry in the data field: class ProductModelForm(ModelForm): class Meta: model = Product fields = ("name", "data") def __init__(self, user, *args, **kwargs): super(ProductModelForm, self).__init__(*args, **kwargs) user_layouts = models.Layout.objects.filter(user__id=user.id) all_fields = {} self.helper = FormHelper() self.helper.form_method = 'POST' HTML_SAVE = HTML(f"""<button type="submit" name="submit" value="save">save</button>""") NAME_FIELD = Column(Field('name'), css_class='form-row') self.helper.layout = Layout(NAME_FIELD) DATA = Field("data", type="hidden") for i in range(0,n): tmpField = Column(Field( ...), css_class=...) self.helper.layout.append(tmpField) self.helper.layout.append(HTML_SAVE) Now my problem is, that because of using column I get a new line for every entry - but I actually would like the forms to be aligned more space preserving. But I never know which kind of form I add - could be a MultipleChoiceField, a BooleanField or a simple CharField. Is there a way so cripsy will align the forms for me in the page? I could stop using Column but which other field benefits me most? -
django form validation: field error not displayed
I am lost with form validation and the way to display error messages I have a "customized" form display in my template (displayed field by field) I need validation between 2 fields so I should use clean method If the checkbox is ticked, text input can't be empty I would like to bind a error message to my text field but error message is not displayed... forms.py class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["bra_00A_act"] = forms.BooleanField(label = "", required = False) self.fields["bra_00A_lib"] = forms.CharField(label = "", required = False) def clean(self): cleaned_data = super(CreateForm, self).clean() if cleaned_data["bra_00A_act"] and cleaned_data["bra_00A_lib"] == "": raise forms.ValidationError('error') return cleaned_data template html <form id="randomization_settings_form" method="POST" class="post-form"> {% csrf_token %} <input id="new_parameters" type="hidden" name="parameters" value=""> {{ form.non_field_errors }} <table id="table_parametrage" class="table table-hover"> <thead> <tr> <th>Bras A</th> <th>-----</th> </tr> <tr> <td colspan="2"> <div class="fieldWrapper"> {{ form.bra_00A_act.errors }} {{ form.bra_00A_act }} {{ form.bra_00A_lib.errors }} {{ form.bra_00A_lib }} </div> </td> </tr> </thead> </table> ... </form> -
Passing model field as a slug to URL
models.py: class Article(models.Model): title = models.CharField('Title', max_length=99) slug = AutoSlugField(max_length=99, populate_from='title', unique=True) view_counter = models.IntegerField(default=0) topic = models.ManyToManyField('Topic', related_name='articles') country = models.ManyToManyField('Country', related_name='country', blank=True) class Country(models.Model): slug = models.CharField(max_length=50) name = models.CharField(max_length=50) urls.py: urlpatterns = [ path('', ArticlesListView, name='articles-list'), path('api/', ArticlesApiView, name='articles-api'), path('<slug:country>/', ArticlesListView2.as_view(), name='articles-list1'), path('nope/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] views.py: class ArticlesListView2(ListView): model = Topic template_name = 'articles/articles-list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["topics"] = Topic.objects.values() context["countries"] = Country.objects.values() return context I want to pass manytomany model field to url. When I run this code, I get the page, but with a problem. If I write a value that doesn't exist into URL, it doesn't throw error. It shows it as it exist. How can I pass it? Giving slugfield to manytomany field gives error as well.