Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the content from web page on the inter net using django [closed]
I want to get the content from html page in the internet using django /python, note that: i want to get the content after the web page fully rendered from inspect element not from page source does there any idea ? example -
How to auto-translate other-languages fiels using django-modeltranslation
Is there any way in which the other-languages fields can be auto-translated Like in this picture I want to auto-translate the Name[pt] , Body[pt] fields by seeing the (en)-fields. -
How can get Post data form Category in Django?
I tried using Django a bit. Now I'm stuck with posting issues in the category. I want to know how we can use it. Are there any filters that I should use? Code in my model.py class Category(models.Model): title = models.CharField(max_length=255, verbose_name="ชื่อหมวดหมู่") content = models.TextField(default='ใส่เนื้อหาบทความ') slug = models.SlugField(max_length=200, default='ใส่ลิงค์บทความ ตัวอย่าง /your-post-content') parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): id = models.AutoField category = models.ForeignKey('Category',on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default='media/noimg-l.jpg') title = models.CharField(max_length=200,unique=True,default='ใส่ชื่อบทความ') content = models.TextField(default='ใส่เนื้อหาบทความ') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_viewcount = models.PositiveIntegerField(default=0,) slug = models.SlugField(max_length=200, default='ใส่ลิงค์บทความ ตัวอย่าง /your-post-content') status = models.IntegerField(choices=STATUS , default=1) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_cat_list(self): k = self.category # for now ignore this instance method breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] and my view.py def cat_list(request): categories = Category.objects.all() return render(request, 'blog/categories.html', {'categories': categories}) def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) return render(request, 'blog/category_detail.html', {'category': category}) and my urls.py urlpatterns … -
Changing default value of cell using DJango and SQlite3
I have a problem, I am doing project in Django for my University, and I don't know how can I change value of cell in Database using views.py. My application is an application to do exams online and problem is that many users need to use it at the same time, so I need to do relations in database, like every question has an answer and that answer is provided by one user. And there is problem, I don't know how can I change this dynamically in Views.py. This is my code from Views.py: if form.is_valid(): if username == Users.objects.latest('name'): Choice.objects.username = Users.objects.get('name') And my models.py: class Answers(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text class Users(models.Model): name = models.CharField(max_length=30) pass = models.CharField(max_length=30) def __str__(self): return self.name class Choice(models.Model): username = models.ForeignKey(Users, null=True, on_delete=models.CASCADE) question = models.ForeignKey(Questions, null=True, on_delete=models.CASCADE) answer = models.CharField(null=True,max_length=50) class Questions(models.Model): text = models.CharField(max_length=150) madeBy = models.ForeignKey(User, null=True, blank=False, default='kacper', on_delete=models.CASCADE) def __str__(self): return self.text Also if you have any other idea how could I improve this would be great, it's first time that I'm doing something in DJango. -
Multiple plots on same chart with Django and chart.js results in points only (no line)
I'm currently trying to visualize my data which is stored in a MySQL database using Django combined with Chart.js. I have already managed to find a way to retrieve data from my database and plot something on a graph. However, I'm struggling to plot multiple datasets on the same chart. My database consists of 4 columns: id,data_type, value, sent_on (=string representing date and time). As I have 4 different data types, what I'm trying to do is to plot a line graph for every data type on a single chart. On the x-axis the date&time (sent_on column) and on the y-axis the values. My html file is as follows: var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for item in qs %}'{{item.sent_on}}',{% endfor %}], datasets: [{ label: 'Battery', data: [{% for item in qs %}{% if item.data_type == 'BT' %}{{item.message}}{% endif %},{% endfor %}], fill: false, backgroundColor: 'rgba(153,255,51,0.4)', borderColor: 'rgba(153,255,51,0.4)', borderWidth: 1 }, { label: 'Tire pressure', data: [{% for item in qs %}{% if item.data_type == 'TP' %}{{item.message}}{% endif %},{% endfor %}], fill: false, backgroundColor: 'rgba(255, 0, 0, 1)', borderColor: 'rgba(255, 0, 0, 1)', borderWidth: 1 }] }, And the chart … -
Notifications in django
I am working on ecommerce website project using django. What I want is that when somebody makes an order, I must be notified through mail or sms. So how can I achieve that? -
Django Rest Framework + React JWT authentication, 403 Forbidden on protected views
I'm trying to make a CRUD website with DRF + react, i've somewhat followed this tutorial for authentication https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta (with some differences since i'm using DRF and React completely separatedly) authentication is fine, i can already login, logout and signup, however any view that requires the permission "IsAuthenticated" gets me a 403 Forbidden, i've tried to also get the data through postman using the headers: Accept : application/json Authorization : JWT "myaccesstoken" but i also get a 403 with "detail": "You do not have permission to perform this action." Here's some of the code Settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', (#I've already tried commenting out basic and session auth) ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT ',), 'USER_ID_FIELD': 'username', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } CORS_ORIGIN_ALLOW_ALL = True And the protected view views.py class PostList(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) (#I've tried with or without this) authentication_classes = () (# if i take this out i get a 401 insteand of a 403) queryset = Post.objects.all() serializer_class = PostSerializer I'm not showing any of the react code since i think … -
How to create an additional table to link the models?
There are two models Modules() and ParentCategory(). They are not linked in any way in the database. class Modules(models.Model): ..... class ParentCategory(models.Model): .... I want to make the connection between them on the following principle. One module contains several categories. Described this structure with a dictionary where dictionary key - module name and the value of the list of categories belonging to this module. pc_to_modules_assign = { "DTH": ['COMMON S2P', 'COMMON SOURCING', 'SERVICES', 'SOURCING'], "KLK": ['COMMON S2P', 'COMMON SOURCING', 'SERVICES', 'SXM'], "ODJU": ['COMMON S2P', 'SERVICES', 'Analytics'], "TD": ['COMMON S2P', 'SERVICES', 'CLM'], "MNH": ['COMMON S2P', 'SERVICES', 'eProcurement'], "OPI": ['COMMON S2P', 'SERVICES', 'I2P'], "AP": ['COMMON S2P', 'SERVICES', 'I2P', 'AP'], "DF": ['COMMON S2P', 'COMMON SOURCING', 'SERVICES', 'SOURCING', 'SXM', 'Analytics', 'CLM'], "CVB": ['COMMON S2P', 'SERVICES', 'eProcurement', 'I2P'], "GFT": ['COMMON S2P', 'COMMON SOURCING', 'SERVICES', 'SOURCING', 'SXM', 'Analytics', 'CLM', 'eProcurement', 'I2P'] } There is one primary category in the list. What kind of connections should be used in such a model or what fields are needed approximately. Something like that. class PCtoModules(models.Model): m = .....Modules pc = ....ParentCategory primary = models.BooleanField(default=False) But I'm confused as to what type of connection to apply. -
VK error no access_token passed when get list of friends
Мое приложение регистрирует пользователя с помощью вконтакте и выводит его имя и список 5 друзей, имя выводится, но при попытке получить друзей выводит ошибку: access_token '******' code '*****' data {'error': {'error_code': 5, 'error_msg': 'User authorization failed: no access_token passed.', 'request_params': [{'key': 'order', 'value': 'random'}, {'key': 'count', 'value': '5'}, {'key': ' ' 'access_token', 'value': '*****'}, {'key': 'v', 'value': '5.103'}, {'key': 'method', 'value': 'friends.get'}, {'key': 'oauth', 'value': '1'}]}} first_name 'Марсель' greeting_string 'Здравствуйте, Марсель Абдуллин, вы авторизованы. <br>' last_name 'Абдуллин' r <Response [200]> request_link ('https://api.vk.com/method/friends.get?order=random&count=5& ' 'access_token=*****&v=5.103') user_id 224454327 Строка в которой ошибка: array_of_friends_ID = data['response']['items'] -
Django, Python 3.6.9 OSError: [Errno 38] Function not implemented
When executing a command: python3 manage.py collectstatic i get: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/root/system/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/system/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/system/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/root/system/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/root/system/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/root/system/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/root/system/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file self.storage.save(prefixed_path, source_file) File "/root/system/lib/python3.6/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/root/system/lib/python3.6/site-packages/django/core/files/storage.py", line 268, in _save for chunk in content.chunks(): File "/root/system/lib/python3.6/site-packages/django/core/files/base.py", line 60, in chunks data = self.read(chunk_size) OSError: [Errno 38] Function not implemented Python 3.6.9, django 2.1.3, Ubuntu 18.04 LTS /dev/shm mounted -ld /dev/shm drwxrwxrwx 2 root root 40 мая 13 17:37 /dev/shm How can i fix it? -
How do I define __str__() method in a model which has a Foreign Key of User model and get the values of fields in Django?
I have below model in my Django app and it has a Foreign Key of Django's default User Model with __str__() function. class Subject(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=100) subject = models.CharField(max_length=100) def __str__(self): return f'{self.user.username}' What I want to do is to show the subject name in the Admin Panel, when we open the Subjects Model/Table in the Admin Panel. Suppose that if we have a user with username 'khubi' and he has two subjects, then the Admin Panel just shows the username of the user that is 'khubi' instead of showing the subject's names. Below is the screenshot: I have tried to put this: return f'{self.user.username.subject}' But it gives the error that 'str' object has no attribute 'subject' and I have tried it as well: return f'{self.user.subject}' and it gives me the error 'User' object has no attribute 'subject' Can anyone guide me how will I get the name of the subject in the __str__() function and anywhere outside as well? Thanks in advanced. -
Is it possible for one Django model to inherit from two other models, one as abstract, one as proxy?
Is it possible for one model to both inherit from abstract model, while acting as proxy model of another? from django.db import models class Vehicle(models.Model): brand = models.CharField(max_length=30) class Meta: abstract: true class Car(models.Model): brand = models.CharField(max_length=30) color = models.CharField(max_length=30) # Is this possible? class MyCar(Car, Vehicle): class Meta: proxy = True Would MyCar be a proxy of Car with the added fields from Vehicle? -
Django static Files not loaded on Docker?
I am using Django 3.0.6 and want to dockerized my project. everything is worked fine except static files. Static files are loaded completely when I run my project normally. But, after dockerization, they are not loaded and throw a 404 error. my project layout as follow: ├── nginx │ ├── Dockerfile │ └── nginx.conf ├── src ├── applications ├── configuration │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Dockerfile ├── manage.py ├── requirements.txt ├── static │ ├── build │ ├── images │ └── vendors └── templates settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV SRC_DIR=/var/www/project/src RUN mkdir -p $SRC_DIR WORKDIR $SRC_DIR ADD ./requirements.txt $SRC_DIR/requirements.txt RUN pip install --upgrade pip RUN pip install -r requirements.txt ADD . $SRC_DIR docker-compose.yml: version: '3' services: web: build: context: ./src dockerfile: Dockerfile command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 -w 4 configuration.wsgi" env_file: ./src/.environment volumes: - ./src:/var/www/project/src - ./src/static:/var/www/project/src/static ports: - 8000:8000 depends_on: - db nginx: build: context: ./nginx dockerfile: Dockerfile ports: - 80:80 volumes: - ./src:/var/www/project/src - ./src/static:/var/www/project/src/static depends_on: - web nginx.conf: upstream view { server web:8000; … -
Display possible values (choices) of SlugRelatedField in drf-yasg OpenAPI and Swagger views
I have several models that I use as enums (basically, the model is just a name and a slug), like currencies and countries etc, and I'm trying to show the available choices in drf-yasg without success. My last attempt was adding this to the serializer's Meta class: swagger_schema_fields = { 'currency': {'enum': list(Currency.objects.values_list('slug', flat=True))} } But of course it failed miserably - not only it didn't show the enum values, it also broke the serializer (because it used the strings instead of the actual model). Is there any way of doing this? -
how can i create Quiz app using django framework?
I am trying to make a quiz app which randomly ask 5 quetions.Before that I used a forein key in models.I go through a django document.Now I want to render all quetions and its 4 option on same page.while going through document it creates a link for each quetion which render on only one quetion using its id. Now if if i render on same page it do not separate radio busttons for each quetion. Link of reference:https://docs.djangoproject.com/en/3.0/intro/tutorial01/ my code is given below: models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py def index(request): latest_question_list = Question.objects.all() context = {'latest_question_list': latest_question_list} return render(request, 'index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return … -
Django debug toolbar and include in urls.py (supposedly)
Django 3.0.6 Main urls.py urlpatterns = [ path('', HomeView.as_view(), name='home'), path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons. path('post/', include('post.urls')), ] if DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) post.urls.py urlpatterns = [ path('<int:pk>/', PostDetailView.as_view(), name='detail'), ] Problem When I try these addresses: http://localhost:8000/, http://localhost:8000/admin/, Django Debut Toolbar is showing. But when I try http://localhost:8000/post/1/, the debug toolbar is not showing. Supposedly, it has something to do with include. But I'm not sure. Could you hep me here? -
Error running docker-compose: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
I am writing a Django Rest API and till today I was using venv until today I decided to switch to docker environment. And I'm not able to connect to the database in docker. Here is the docker-compose file: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=mydatabase volumes: postgres_data: This is the .env.dev file: SECRET_KEY=its_a_secret DEBUG=1 SQL_ENGINE=django.db.backends.postgresql_psycopg2 SQL_DATABASE=mydatabase SQL_USER=postgres SQL_PASSWORD=postgres SQL_HOST=db SQL_PORT=5432 On my local environment.. I have mydatabase running on a postgres server on port 5433. But when I docker-compose up I get the following error -
Second app and second auth system in django
I want to make 2 apps in django with 2 tables of users, i don't know how to make 2 others custom models of user and 2 other auth systems for this apps -
What does Django model field option 'through=SomeModel' do?
I'm following a tutorial and it has 2 models: class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey('Tweet', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) ... What is the role of the through=TweetLike and how is it working? -
(Django) Can't understand why my Python classes inherit the wrong method
I created a parent class as such: class ProjectCreateMixin(CreateView): model = Project form_class = ProjectCreationForm def get_form_kwargs(self): kwargs = super(ProjectCreateMixin, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs And then two sub classes that inherits from ProjectCreateMixin, as such: @method_decorator(login_required, name="dispatch") class CreateProjectView(ProjectCreateMixin): template_name = 'projects/project_create.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() ProjectUser.objects.create(user=self.request.user, project=self.object, role='admin') return redirect("projects:list") class ProjectWizardCreate(ProjectCreateMixin): template_name = 'wizard-project-create.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() ProjectUser.objects.create(user=self.request.user, project=self.object, role='admin') return redirect("timesheets:default-current-week") When I'm calling the ProjectWizardCreate on a URL: path("wizard/project", ProjectWizardCreate.as_view(), name="wizard-project"), and successfully submits its form, why is it redirecting to ("projects:list") and not to ("timesheets:default-current-week")? -
Include in urlpatterns and 404
Django 3.0.6 post/urls.py from django.urls import path from .views import PostDetailView urlpatterns = [ path('<int:pk>', PostDetailView.as_view(), name='detail'), ] The project's urls.py urlpatterns = [] if DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ path('', HomeView.as_view(), name='home'), path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons. path('post/', include('post.urls')), ] URL in browser http://localhost:8000/post/1/ Reslut Page not found (404) Request Method: GET Request URL: http://localhost:8000/post/1/ Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order: __debug__/ ^media\/(?P<path>.*)$ [name='home'] admin/ post/ <int:pk> [name='detail'] The current path, post/1/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Coulb you help me cope with this problem? -
Django inheriting filtered query set to subclass
I have a base class which creates a query set, that is filtered by url parameters from a form. class MyListView(ListView): model = Foo limit = 1000 # Default limit def get_queryset(...): ... limit = self.request.GET.get('limit') ... object_list = model.objects.filter(q_objects).order_by(*o_by)[:limit] return object_list And I have another view for exporting the Listview class ExportCSVView(MyListView): template_name = 'export.csv' content_type = 'text/csv' My problem now is, that the Listview has a filtered query set (object_list), which works perfectly in the browser view, but the export view always exports the object_list based on the default parameters and not the ones from the url parameters. How can I get the export view to use the url parameter filtered object_list without implementing the complete get_queryset() functionality again? -
Django rest API Serialization
Hi i am a beginner at django and im learning about the rest framework. Can someone please explain to me how the parameters in the functions work and what does 'instance' and 'validated data' refer to? Thank you from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance -
Database Design in django application representing a Graph: Multiple tables for Nodes or just one
I am running a django application with a postgresql database attached to it and I am not sure about my database implementation. I want to implement a graph with nodes and edges. Every node has specific coordinates and in the end I want to draw the graph onto a map. I will send about 10000 nodes in an API call, so data can increase quite quickly. I have three different type of nodes (let's call them Node1, Node2 and Node3). The nodes share some common properties but also have their own fields that they don't share with the other nodes. My question regarding the db is if in my use-case it is better to have one large table or if it is better to split this up into smaller tables. Option1: Create one big table with a type field for the specific node type in the model. The downside would be that this leaves many table cells empty when I create the nodes. class Node(models.Model): name = models.CharField(max_length=120, blank=True) graph = models.ForeignKey(Graph, on_delete=models.CASCADE) node_type = models.ChoiceField(....select type of Node...) custom-field-node1 = ... custom-field-node1 = ... custom-field-node2 = ... custom-field-node2 = ... custom-field-node3 = ... custom-field-node3 = ... I could send … -
how to pass the selected check box id of a input tag to views in django and bulk update the selected rows in table
** 1.how to pass the selected check box id of a input tag(which is in for loop, so the name and value of input tag are dynamic ) to views in django and bulk update the selected rows of table in django** <div class="jumbotron"> <form method="post" action=""> {% csrf_token %} {{form|crispy}} <input class = "btn btn-primary" type="submit" value="Search"> </form> <h3 > Model values </h3> <ul> <table class="table" id="tab1"> <thead> {% if teams %} <tr> <th>Select</th> <th>#</th> <th><b>Logo</b> </th> <th><b> Team </b></th> </tr> </thead> <tbody> {% for value in models %} <tr> <td><input name="lol" type = "checkbox" value = "{{value.id}}"/> </td> <td> {{forloop.counter}}</td> <td> <img class="w3-display-topmiddle w3-container" src="{{ value.logUri.url }}" alt="alt txt" height="910" width="910"></td> <td> {{ value.name }} </td> </tr> {% endfor %} </tbody> </table>