Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get the instances of a class with some certain conditions?
I have a model Order from which I want to get all the data in the "ref_code" field but then I want to filter it by the item. So basically what I mean is I want to get all the ref_code of a particular items (which is also a field by a manytomany). I don't know how to tweak it to work. I can only get all the ref_code so far. Any help will be appreciated. Model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) item = models.ForeignKey( 'blog.Post', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True, blank=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.ref_code) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = f'qr_code-{self.ref_code}.png' buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) def get_total(self): total = 0 for order_item … -
how to pass without double " " pass parameters an function in python Django Command
manage.py> generate_stock_nodes --no_of_bays 1 --no_of_racks 5 --no_of_rows 5 --no_of_columns 5 --last_bay_no 17 --creation_type 2 --last_bin_number 0501 --type_id 68 --stock_point_name INDO WESTERN -
How to cache django permissions?
I have implemented permission in django. But for example, {% if perms.application %} <li> </li> {% endif %} Django fetches the permission every time user makes a request, so which means am getting two extra queries: How to cache these permission so that the whole session uses the same ? Is there any better solutions for this ? -
Manually referencing dummy file in Django HttpRequest for testing form submission
In Django, I am trying to create automated tests for a project that includes a file submission via ModelForm. One of the model fields is a FileField, and a test file has already been placed into the project directory so it can be referenced. In order to test the form submission I am creating a dummy user and manually generating an HttpRequest() containing POST data. However, I am unsure of how to manually insert the file into the FileField portion -- I assume I need to reference it somehow, but I don't know exactly how to do that. The test is below: def test_form_submit(self): user = User.objects.create_user( username="testuser", email="asdfasdf@asdf.com", password="asdfasdf" ) request = HttpRequest() request.POST = { "file": [insert file here], # is a FileField "name": "Richard", "date": "2022-01-28", "desc": "A test submission." } form = FileSubmissionForm(request.POST, user=user) form.save() self.assertEqual(Submission.objects.count(), 1) How do I properly reference the file for this test case? The dummy file is located at $MEDIA_ROOT/testing/dummy_file.txt. Thanks! -
django admin mptt: how to show TreeNodeChoiceField instead of ModelChoiceField when add/change with FK
I'm working on a django app that includes some mptt based tree models. I have these models (simplified): class Asset_Type(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', verbose_name='Parent') name = models.CharField(max_length=64, unique=True, verbose_name='Asset Type Name') class Asset(models.Model): name = models.CharField(max_length=64, unique=True, verbose_name='Asset Name') type = models.ForeignKey(Asset_Type, on_delete=models.CASCADE, blank=False, null=False) I have these admin classes declared (simplified): class Asset_TypeAdmin(DraggableMPTTAdmin): mptt_level_indent = 20 admin.site.register(models.Asset_Type, Asset_TypeAdmin) class AssetAdmin(admin.ModelAdmin): list_display = ['name','type'] list_display_links = ['name'] admin.site.register(models.Asset, AssetAdmin) Everything works almost perfect, except this: When I add a new asset I get a template/form with a drop-down list where I can select the Asset_Type. The issue is that the drop-down list is of the class ModelChoiceField so it does not show the tree hierarchy. It shows this in the drop-down list: --------- Root 1 Child 1.1 Child 1.1.1 Root 2 Child 2.1 Child 2.1.1 I would like it to be class TreeNodeChoiceField so it shows this: Root 1 --- Child 1.1 ------ Child 1.1.1 Root 2 --- Child 2.1 ------ Child 2.1.1 I've found information related to this here: https://django-mptt.readthedocs.io/en/latest/forms.html#id4, but honestly I have no clue on how/where should I tell django that the field to use in the add/change form should be TreeNodeChoiceField. I've … -
ModuleNotFoundError: No module named 'spotify'
guys. I made a mistake, when i was creating the file to access the spotify api with my application i accidentally created the folder 'spotify' inside my app folder. Now i tried to move the spotify folder into the django folder, so it would be in the same directory as my app. The issue is that when i try to migrate it shows: "ModuleNotFoundError: No module named 'spotify'. Do you guys have a tip? Thanks in advance! -
annotate - Django ORM optimization
I want to annotate similar product from Order-Line.where Line has a foreign-key relation with products. im showing what ive done so far. recommended_product_ids = Line.objects.all() recommended_product_ids = recommended_product_ids.annotate( rank=Sum('quantity'), ).filter(rank__gte=2).order_by('-rank')[:max_count] -
Django and redis adding :1 to keys
I'm using django-redis to store some data on my website, and I have a problem where Redis is adding :1 at the beginning so my key looks like this: :1:my_key I'm not sure why is it doing this, I've read the documentation on django-redis and I couldn't find anything related, so my guess it has something to do with redis but I can't figure out what. In my settings.py I have the regular: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://xxxxx/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } And in my tasks.py I set keys like the documentation says: from django.core.cache import cache cache.set(my_key, my_value, 3600) So now I can't get the values using the cache.get(my_key) -
Django gives error at {% result_list cl %} when accessing models
unsupported operand type(s) for +: 'Listing' and 'float' Error Django admin The error seems to only happen when trying to access the models on the admin page, whats the cause? Views.py -
Unable to log-in in admi site using aadhaar no in django using custom model
I created a custom django model where I used aadhar number as USER_FIELD which does not give me any error but after creating the superuser I can't log-in in the admin site of django. -
How to solve 'NoneType' object has no attribute 'fields' in Graphene-django
Have this mutation class AddStudentMutation(graphene.Mutation): class Arguments: input = StudentInputType() student = graphene.Field(StudentType) @classmethod @staff_member_required def mutate(cls, root, info, input): try: _student = Student.objects.create(**input) except IntegrityError: raise Exception("Student already created") return AddStudentMutation(student=_student) Before executing the above mutation in graphiql, I add the request header "Authorization": "JWT <token>" so that the user is authorized. But I get the error graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'fields'. The error doesn't occur when I remove the header. It also works fine when I include it in requests for queries. Am I doing something wrong? I need the authorization to happen for mutations too. I tracked the Traceback and it leads to file .../site-packages\graphql_jwt\middleware.py. It appears it's a bug in the package in function allow_any() line 18 field = info.schema.get_type(operation_name).fields.get(info.field_name). New to this I need help. I'm using graphene-django==2.15.0 and django-graphql-jwt==0.3.4 -
Django with django-tenant, unable to perform migrations
Context I am trying to setup django-tenants for my Django application by following the official installation guide. My Django app used to run perfectly fine when I ran manage.py runserver. My settings.py looks exactly as in the guide: SHARED_APPS = ( 'django_tenants', 'iam', # the tenant models (Client & Domain) reside in this app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... ) TENANT_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', ... ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... # rest of middleware ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # the option for django-tenant 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { "ENGINE": 'django_tenants.postgresql_backend', ... # other db settings } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "iam.Client" TENANT_DOMAIN_MODEL = "iam.Domain" Problem After following all the steps in the installation guide I try to use python manage.py migrate_schemas --shared. This results in the following stacktrace: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File … -
Django inline formsets with Class-based view
I'm trying to do Django class-based CreateView inline formsets. I have a product model and a productImage model and productImage is inline everything looks fine but after i submit my product the images that are selected in formset will not save. Here is my code models.py: class Product(models.Model): name=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True), description=models.TextField(blank=True), vector_column=SearchVectorField(null=True, editable=False), meta={"indexes": (GinIndex(fields=["vector_column"]),)} category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%y/%m/%d') def __str__(self): return self.product.name views.py class ProductCreate(StaffAccessMixin, ProductFormValidMixin, ProductFieldsMixin, CreateView): model = Product def get_context_data(self, **kwargs): context = super(ProductCreate, self).get_context_data(**kwargs) if self.request.POST: context['product_image_formset'] = ProductImageFormset(self.request.POST) else: context['product_image_formset'] = ProductImageFormset() return context template_name = 'products/product-create-update.html' ProductFormValidMixin: class ProductFormValidMixin(): def form_valid(self, form): context = self.get_context_data() product_image_formset = context['product_image_formset'] if self.request.user.is_superuser: self.obj = form.save() if product_image_formset.is_valid(): product_image_formset.instance = self.obj product_image_formset.save() return redirect('administration:product-update', pk=self.obj.pk) else: self.obj = form.save(commit=False) self.obj.available = False return super().form_valid(form) ProductFieldsMixin: class ProductFieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["name", "slug", "description", "category", "price", "available", "image", ] else: raise Http404 return super().dispatch(request, *args, **kwargs) forms.py: from django.forms.models import inlineformset_factory from .models import Product, ProductImage ProductImageFormset = inlineformset_factory(Product, ProductImage, fields=('image',), extra=3) Formset template: … -
How to automatically add repeated data migrations in Django using Djangos ORM?
I am new to Django and have read the basic and advanced tutorial along with some parts of the documentation on migrations and data migrations: https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations Also, I have read about fixtures but this seems to be suitable only for initial data provision: https://docs.djangoproject.com/en/4.0/howto/initial-data/#providing-data-with-fixtures The task I want to accomplish is to bulk insert data repeatedly from "outside" in a clean way using using Djangos ORM and all the benefits of migrations. So far, I haven't found a full example on how to do this because using the first option of data migration would require to touch a file everytime I insert/migrate new data. Any hints on how to accomplish this or am I missing something? Thanks in advance! -
django passing id in popup
In my Django project, I want to edit users from the user list on the popup {%for data in data%} <tr> <td>{{data.firstname}}</td> <td>{{data.phonenumber}}</td> <td> <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> view Savings </button> </td> </tr> {%endfor%} popup <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header" style="background-color:#136de4;color:white" > <h5 class="modal-title" id="staticBackdropLabel">Edit Profile</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="card-body"> <form method="post" id="formOne"> {% csrf_token %} {{form.as_p}} <div class="modal-footer"> <a href="{%url 'customer:savingsprofile' data.id%}"><button type="submit" class=" btn bg-gradient-info text-white btn-sm m-1" data-bs-dismiss="modal">Save Changes</button></a> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> but on the popup it is showing only the first (while clicking another row) data of the table -
Django customize Label of form
whenever I add a Labels to ModelForm, the Label will look in the HTML like this: #v check this colon <label for="id_url">URL:</label> When I created the labels like this: class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) labels = { 'title': 'Title', 'url': 'URL' Where do the colons at the end of the Label in the HTML come from and how to remove them? -
Run periodic celery task with a dynamic schedule in django application
I am wondering if it is possible to have my end users dynamically adjust the schedule of a periodic task. So something along these lines: # celery.py def get_schedule(): config = get_user_config() # returns a model object of sorts return config.frequency_in_seconds app.conf.beat_schedule = { 'my_periodic_task': { 'task': 'my_periodic_task', 'schedule': get_schedule, # schedule updated based on `get_schedule` function }, } This way, if a user were to change the frequency_in_seconds field in their user config setting, it would dynamically update the beat schedule. My preference would be to do this outside of the Django Admin site and without any additional packages (e.g. django-celery-beat). Any thoughts or ideas would be much appreciated. Thanks -
How can I join two serilaizers in django rest framework that have a similar field value
I have two models in my Django Restframework. In my views I want to get all properties and for each property I get Profile data of that user who created it. How can I achieve this? example: #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=200) location = models.CharField(max_length=200) class Properties(models.Model): title = models.CharField(max_length=200) price = models.CharField(max_length=200) category = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) #serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = [ 'title','price','category','created_by' ] #views.py class PropertiesView(generics.ListAPIView): serializer = PropertySerializer queryset = Property.objects.all() -
User generated item multiple choice field Django
I am looking for a way to have a multiple choice field populated with choices made by a user. For example, they could have the following 3 entries: Yes, No, Unsure. I want a way to be translate this to a model. I understand this can be done with pre-defined options using a CharField, or ChoiceField, but I haven't seen anything with "dynamic" data, such as user-generated data. -
Run node things in docker (Django, Angular)
A have a frontend(angular) project inside a backend(django) project with this structure [structure][1] compose.yml services: db: image: postgres:13-alpine container_name: db restart: always env_file: .env.dev environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage volumes: - postgres_data:/var/lib/postgresql/data/ web: build: context: . dockerfile: Dockerfile image: web container_name: web env_file: .env.dev environment: - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage restart: always volumes: - ./:/leostudy links: - db depends_on: - db ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" redis: image: "redis:alpine" expose: - 6379 celery: restart: always build: context: . command: celery -A students worker -l info env_file: - ./.env.dev volumes: - ./:/leostudy/ depends_on: - db - redis - web volumes: postgres_data: Dockerfile # set work directory WORKDIR /proj # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev libffi-dev openssl-dev RUN apk --update add \ build-base \ jpeg-dev \ zlib-dev # install dependencies COPY ./requirements.txt . RUN pip install --upgrade pip \ && pip install -U pip setuptools \ && pip install -r requirements.txt # copy project COPY . . # run entrypoint.sh RUN ["chmod", "+x", "./entrypoint.sh"] ENTRYPOINT ["./entrypoint.sh"] So, I need to somehow build static with gulp … -
Django for loop data not displaying in template
I am not saving data in my data base. I am using an api service and I don't want to to save those api data in my data base. I just want to display those data in my html template. The problem only first data of for loop showing in template where I can see all for loop data from my terminal. I want to display my all for loop data in my html template. here is my code: views.py: for i in results[search_type]: if search_type == "organic_results": title = i["title"] print(title) context = {"title":title} I know I can use append method but it's showing all data together in my template as list. I want to so theme in my template using for loop like this: html {%for i in title %}{{i}}{%endfor%} my terminal result: Facebook - Log In or Sign Up https://www.facebook.com/ Newsroom | Meta - Facebook https://about.fb.com/news/ Facebook - Apps on Google Play https://play.google.com/store/apps/details?id=com.facebook.katana&hl=en_US&gl=US Facebook - Wikipedia https://en.wikipedia.org/wiki/Facebook Facebook Careers | Do the Most Meaningful Work of Your ... https://www.facebookcareers.com/ Facebook - Twitter https://twitter.com/facebook why only first data of for loop showing in my template? -
django.db.utils.OperationalError: fe_sendauth: no password supplied despite having supplied password in settings.py
I am trying to do python manage.py migrate to do migrations for my django app but i keep getting this error even though i have supplied the db name, user, password in settings.py. Any help will be appreciated. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accountant', 'USER': 'json', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '5432' } } Full stacktrace: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in … -
Middleware in django keeps redirecting, visiting admin-site not possible
I am writing a django project where I need to separate the pages and the accounts. Do to so, I wrote a LoginCheckMiddleWare. The problem is that I am not able to visit the django-admin site anymore, because it keeps redirecting me. I don't what I did wrong. I also have an EmailBackEnd.py file, that I use for logging in with the email and not the username. LoginCheckMiddleWare.py from django.http.response import HttpResponseRedirect from django.urls import reverse from django.utils.deprecation import MiddlewareMixin class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ user = request.user if user.is_authenticated: if user.user_type == '1': if modulename == 'user.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('user:admin_index')) elif user.user_type == '2': if modulename == 'instructor.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('instructor:instructor_index')) elif user.user_type == '3': if modulename == 'student.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('student:student_index')) else: return HttpResponseRedirect(reverse('user:login_user')) else: if request.path == reverse('user:login_user') or modulename == 'django.contrib.auth.views': pass else: return HttpResponseRedirect(reverse('user:login_user')) EmailBackEnd.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackEnd(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: … -
django multiple form separated in the html, merge again with submit
there is a formmodel like: class foo(forms.ModelForm): a = forms.BooleanField(label='a', required=False) b = forms.BooleanField(label='b', required=False) c = forms.BooleanField(label='c', required=False) d = forms.BooleanField(label='d', required=False) e = forms.BooleanField(label='e', required=False) f = forms.BooleanField(label='f', required=False) g = forms.BooleanField(label='g', required=False) h = forms.BooleanField(label='h', required=False) #... further there are multiple instances of foo in a list: L = [] L.append(foo(instance=object_1)) L.append(foo(instance=object_2)) L.append(foo(instance=object_3)) #... L.append(foo(instance=object_n)) this is shown on the html in different tables in different columns. The problem now is to send the data back correctly with subbmit. I have to put the tables and lines back together correctly. I was thinking of something like this: <form class="form-inline" action ="{% url 'bla:blo' %}" method="post"> Table #1 | ID of Form | Value #1 | Value #2 | Value #3 | Value #4 | | ---------- | -------- | -------- | -------- | -------- | <form id=1>| 1 | a1 | b1 | c1 | d1 |</form> <form id=2>| 2 | a2 | b2 | c2 | d2 |</form> <form id=3>| 3 | a3 | b3 | c3 | d3 |</form> <form id=4>| 4 | a4 | b4 | c4 | d4 |</form> Table #2 | ID of Form | Value #1 | Value #2 | Value … -
Django correct way to place form in template
this is my test model form class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) It has two fields but for design reasons I need each input in a seperate DIV in the template like so (just an example) <form> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> </form> When I just add {{ form }} every input is in the form without a surrounding container. What is there correct way 2022 (not a Django 1.1 or 2016 tutorial) to place inputs manually in the template and then connect it with the model?