Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: multiple models with one-to-many relation on admin page TabularInline
I have multiple models in an existing database that all have a many-to-one relation to another model. For example: class Collection(models.Model): start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'Program' class ItemA(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemA' class ItemB(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemB' What I want to do, is show these models in a single TabularInline on the admin page of the Collection model. I also want to be able to filter the models. Is this possible without inheritance in the database? (I don't want to add a general item table). In the documentation, I can only find how you can use TabularInline for a single model. So my question is basically: What would be the best approach to solve this? Is it maybe possible to define some kind of view model dat is not in the database, but that can be used to display all the items in a TabularInline? -
Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$']
i am making blog site but issue is as follows: In my home page i have blogs which i have added but when i am clicking them they are showing 500 error which is stated as : NoReverseMatch at /post/1/. My code body is as follows & My app name is Blog: Models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.BlogListView.as_view(), name='home'), path('post/<int:pk>/', views.BlogDetailView.as_view(), name='post_detail'), path('post/new/', views.BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', views.BlogUpdateView.as_view(), name='post_edit'), ] Views.py: from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView from . models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' context_object_name = 'anything_you_want' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = '__all__' class BlogUpdateView(UpdateView): model = Post fields = ['title', 'body'] template_name = 'post_edit.html' I am using Import Reverse to get back on the same page after adding the blog but it is showing same error too. -
like button in django: refresh pronblem
i was trying to create a like button for my django blog its working fine. the problem i'm facing is whenever i click the like button it refresh and give like. how can i stop it from refreshing page, its looks bad bcoz if i try to give like in user prolife or in post detail it redirect to home page. can anyone help me? models.py class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() likes = models.ManyToManyField(User,blank=True, default=None, related_name='post_likes') date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title @property def num_likes(self): return self.liked.all().count() def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) Like_Choice = ( ('Like','Like'), ('Unlike','Unlike'), ) class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) value = models.CharField(choices=Like_Choice,default='Like',max_length=20) def __str__(self): return str(self.post) views.py def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.likes.all(): post_obj.likes.remove(user) else: post_obj.likes.add(user) like, created = Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('Love Travel-User-Posts') urls.py path('user-posts/like/',like_post,name='User-Post-Like'), posts.html <form action="{% url 'User-Post-Like' %}" method="POST" class="ui form"> {% csrf_token %} <input type="hidden" name="post_id" value="{{ post.id }}"> <strong class="Likes ml-3 mr-2">{{ post.likes.all.count }}</strong> {% if user not in post.likes.all %} … -
Pytest doesn't find pytest.ini
I have pytest.ini located in current directory and when invokin pytest /src/foo/bar for some strange reason pytest picks /src/foo as project root even I do have following pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = myproj.settings python_files = tests.py tests_*.py *_tests.py django_find_project = false addopts = --rootdir=$PWD -p no:warnings --no-migrations --reuse-db --junit-xml=unittests.xml norecursedirs = .* static I'm running command within a docker but I assume it doesn't have any implications. -
Django Formtools Form Wizard is not showing data fetched from database
I'm taking first name and last name from user. In done() method, I'm updating the record in database. In get_form_initial() method, I prepopulate first name and last name from database. In this case, initialised form is empty. Notice that if I manually enter first name and last name in database (postgres), then form shows this data while initializing. Why is this happening ?? views.py def get_form_initial(self, step): initial = {} id = self.request.user.id user = User.objects.filter(id=id).values_list('first_name', 'last_name') print(user, end='\n') if step == '0' and user : initial.update({ 'first_name' : user[0][0], 'last_name' : user[0][1] }) return self.initial_dict.get(step, initial) def done(self, form_list, **kwargs): id = self.request.user.id data = [form.cleaned_data for form in form_list] first_name = data[0]['first_name'] last_name = data[0]['last_name'] #Save User details to DB if first_name != '' and last_name != '' : user = User.objects.filter(id=id) user.update(first_name=first_name, last_name=last_name) print('Added User Details') return redirect('morya:customer', id=user_id) -
How to use Django sessions to pass data from one form to another?
I have a view from which I want to pass a session variable into a form. The view looks like this: def admission(request): ... request.session['season_value'] = some_value The form looks like this: class DeterminingForm(forms.Form): season = forms.ModelChoiceField(queryset=Subject.objects.filter(...)) I want the value to be passed into the queryset in the season field. How do I do this? -
Django : Dropdown menu to show only unconfigured values
I have created two models - class DID_Definition_Model(models.Model): # DID to Region-Carrier Mapping region_carrier = models.ForeignKey(Telco_Carrier_Mapper_Model, on_delete=models.CASCADE) did_number= models.CharField(max_length=32, validators=[alphanumeric], primary_key=True) did_cost= models.DecimalField(max_digits=10, decimal_places=2) created_on_date = models.DateTimeField(default=timezone.now) class DID_Number_Assignment_Model(models.Model): #DID Number Assignment did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE, primary_key=True) subscriber_department=models.CharField(max_length=200) usage_assignment=models.ForeignKey(Usage_Assignment_Model, on_delete=models.CASCADE) employee_email=models.EmailField() employee_fullname=models.CharField(max_length=200) created_on_date = models.DateTimeField(default=timezone.now) And created the below view - def did_assignment_form(request, did_selector=0): if request.method =="GET": if did_selector==0: form = DID_Number_Assignment_Model_Form() else: did_assignment_item = DID_Number_Assignment_Model.objects.get(pk=did_selector) form = DID_Number_Assignment_Model_Form(instance=did_assignment_item) return render(request, 'MASTERHANDLER/did_assignment_form.html', {'form':form}) else: if id==0: context = DID_Number_Assignment_Model.objects.values('did_selector') if did_selector not in context: form = DID_Number_Assignment_Model_Form(request.POST) else: did_assignment_item = DID_Number_Assignment_Model.objects.get(pk=did_selector) form = DID_Number_Assignment_Model_Form(request.POST, instance = did_assignment_item) if form.is_valid(): form.save() return redirect('did_assignment_list') Form detail below - class DID_Number_Assignment_Model_Form(forms.ModelForm): class Meta: model = DID_Number_Assignment_Model fields = ('did_selector', 'usage_assignment', 'employee_fullname', 'employee_email', 'subscriber_department' ) labels = { 'did_selector' : 'DID Selector', 'usage_assignment' : 'Number Usage ', 'employee_fullname' : 'Employee Full Name', 'employee_email' : 'Employee Email', 'subscriber_department' : 'Employee Department', } def __init__(self, *args, **kwargs): super(DID_Number_Assignment_Model_Form,self).__init__(*args, **kwargs) # TO SET drop down default text for a field , optional - self.fields['did_selector'].empty_label = "Select" self.fields['usage_assignment'].empty_label = "Select" # TO SET a field which may be optional - self.fields['subscriber_department'].required = False #self.fields['region_assigned'].required = False This form works with no problems but with one little oddity. If … -
Django invalid form
I am creating an update modelformset form, it renders the data correctly but when I click the submit button nothing happens and in the terminal I can see the message invalid data. Here's the Views.py def post(request): tform = TeamForm() pform = modelformset_factory(Player, form=PlayerForm, extra = 1) pform = pform(request.POST or None, queryset = Player.objects.filter(id__isnull = True)) if request.method == 'POST': t = Team() tform = TeamForm(request.POST, instance=t) if tform.is_valid() and pform.is_valid(): tform.save() instances = pform.save(commit=False) for i in instances: player = Player() player.pname = i.pname player.hscore = i.age player.age = i.hscore player.save() t.player.add(player) t.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) def update(request, pk = None): team = Team.objects.get(id = pk) tform = TeamForm(instance = team) pform = modelformset_factory(Player, form=PlayerForm, extra=1) pform = pform(request.POST or None, queryset=Team.objects.get(id = pk).player.all()) if request.method == 'POST': tform = TeamForm(request.POST, instance=team) if tform.is_valid() and pform.is_valid(): tform.save() instances = pform.save(commit=False) for i in instances: player = Player() player.pname = i.pname player.hscore = i.age player.age = i.hscore player.save() t.player.add(player) t.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) I have added post function too so that I can show that there is no problem in that … -
This site can’t be reached www.127.0.0.1’s server IP address could not be found. (Error in djnago)
The code was perfectly working. Suddenly, when i gave command, py -3 manage.py runserver, www.127.0.0.1:8000 came instead of 127.0.0.1:8000. I tried using local host also but not working. www.127.0.0.1:8000 is written on the title as well.enter image description here -
How to pass an id of specific item
I am trying to pass an id to page where I would be able to change the data of that item. I have a page, where I am displaying all instances of specific item: {% for copy in bikeloan.bikeinstance_set.all %} <hr> <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}"> {{ copy.get_status_display }} </p> {% if copy.status != 'a' %} <p><strong>Due to be returned:</strong> {{ copy.due_back }}</p> {% endif %} <p><strong>Frame number:</strong> {{ copy.imprint }}</p> <p class="text-muted"><strong>Id:</strong> {{ copy.id }}</p> <a href="{{ copy.get_absolute_url }}">Loan</a> {% endfor %} I get a couple of results and I wanna be able to click on button loan and pass the id of that particular instance to new page. I have that in my models: class BikeInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular bike across whole stock') bike = models.ForeignKey('BikeLoan', on_delete=models.SET_NULL, null=True) frame_number = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) def get_absolute_url(self): return reverse("core:loan-user", args=[str(self.pk)]) and my urls: path('loan-user/<int:pk>', loan_bike, name='loan-user'), views.py: def loan_bike(request, pk): bikeloan = get_object_or_404(BikeInstance, pk=pk) return render(request, 'loan_user.html', context={'bikeloan': bikeloan}) When I enter a page, where all the instances are displayed I get that error: … -
Why isn't the related_name working for models?
There are question and answer tables related to each other. Each question has one answer. I need to check the answer field in the CompanyGeneralInfoAnswers model. class CompanyGeneralInfoQuestion(models.Model): rfi = models.ForeignKey(Rfis, models.DO_NOTHING) question = models.CharField(max_length=512) class Meta: db_table = 'company_info__questions' class CompanyGeneralInfoAnswers(models.Model): question = models.OneToOneField('CompanyGeneralInfoQuestion', models.DO_NOTHING, related_name='answer_to_question') answer = models.CharField(max_length=4096, blank=True, null=True) class Meta: db_table = 'company_info_answers' To do this, I make this request. round = kwargs.get('rfiid') exist_company_question = CompanyGeneralInfoQuestion.objects.filter(rfi=round) if exist_company_question: for q in exist_company_question: print(q.answer_to_question.answer) But got an error RelatedObjectDoesNotExist: CompanyGeneralInfoQuestion has no answer_to_question. -
Return can close Loop for? (python/django)
Does return on python close the Loop for? I'm asking that because I wrote a code that will search for me someone in a list and if know that person it will return me his age if not it will tell me "Person not found". If the person is in the first place of the Array if find it but if it is in the second he doesn't why? def lerDoBanco(name): lista_names = [ {'name': 'Joaquim', 'age': 20}, {'name': 'João', 'age': 25}, {'name': 'Ana', 'age': 27} ] for person in lista_names: if person['name'] == name: return person else: return {'name': 'Person not found', 'age': 0} def fname(request, name): result = lerDoBanco(name) if result['age'] > 0: return HttpResponse('The person was found, has ' + str(result['age']) + ' years old') else: return HttpResponse('Person not found') I ask that because if I comment the else statement it shows me all the people in the Array correctly. -
Pycharm Can't retrieve image ID from build stream
Want to connect pycharm docker interpreter. Here is my windows docker status and here is pycharm status how can I fix the issue -
How can i remove the name's field on the screen?
I have 2 question on the same subject if someone can help me please: 1.I display a form with django and i wanted to to remove the name of my field: Here is what the screen display : display and i want to remove "Columns:". Here is my form: class Features(forms.Form): columns = MultipleChoiceField(choices=FEATURES_CHOICES, widget=forms.CheckboxSelectMultiple) and here is my template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> </form> and here my view: def ChoiceView(request): context = {'form': forms.Features()} return render(request, 'data/home.html', context) Where I recover my result of selections or where go the results ? In which variable of which file (models, views,..) will go the results ? -
Token authentication for django channels
im trying to integrate React , django and django channels together , however im facing some trouble trying to authenticate the socket connection. There are some posts over here: first link enter link description here But they do not talk about how to utilize it over the front end portion. There are some posts which recommends to put the token within the URL , for example : WebSocket('wss://example.com/my-ws-endpoint/?token=' + token, ...) But there seems to be lots of security red flags in doing so. Therefore is there a simple easy way to resolve the token authentication issue for channel websockets here? -
Css not loading in Django
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs. Setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE … -
Router not displaying correct URL in Django RestFramework?
This is how I defined urls.py file of my app router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') router.register('profiles', views.UserProfileViewSet) router.register('schema', views.SchemaViewSet) router.register('creddefination', views.CredDefViewSet) router.register('overalltable', views.OverallViewSet) urlpatterns = [ path('', include(router.urls)), ] urls.py of Project: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('DIAPI.urls')), ] I am not getting correct address for creddefination. But when i manually go to http://127.0.0.1:7000/api/creddefination/ it is working. It is just not displaying correctly. What might be reason for this -
Get overview of SQL query count for every test in a test suite
I have a large Django application with tons of tests that need SQL query optimizations. I don't want to add assertNumQueries or django-assert-num-queries for each test individually, but instead produce an overview about how many SQL queries each one of all of the tests are triggering, to know which code needs the most optimization, like this: test | number of queries ------------------------------------------------ test_a.py::test_my_function1 | 5 test_a.py::test_my_function3 | 2 test_a.py::test_my_function5 | 7 Is it possible to configure a pytest hook in conftest.py which counts the number of SQL queries for each (DB) test and shows them in result - without the need to modify the source of my tests (like adding decorators)? -
Django : How to convert pdf file object to image using pdf2image?
I am trying to create a epaper web app, in which admin can upload file in pdf format and which is converted to image while rendering the page from client side. I have tried pdf2image but getting error something like this : PDFPageCountError at /city_list Unable to get page count. I/O Error: Couldn't open file '['/media/pdf/Akola/2020/04/24/page01.pdf']': No such file or directory. here is my code: models.py class City(models.Model): cityid =models.AutoField(primary_key=True) name = models.CharField( max_length=50) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> ab = instance.date.strftime("%Y/%m/%d") return 'pdf/{0}/{1}/{2}'.format(instance.city.name,ab, filename) class DailyFeed(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) date =models.DateField(auto_now=False, auto_now_add=False) page1 = models.FileField(upload_to=user_directory_path) page2 = models.FileField(upload_to=user_directory_path) page3 = models.FileField(upload_to=user_directory_path) views.py: def city(request): city_list = City.objects.all() daily = DailyFeed.objects.filter(date=timezone.now().date()).filter(city__name = "Akola") ab = [pdfurl.page1.url for pdfurl in daily ] path = r'{}'.format(ab) a = str(path) pages = convert_from_path('{}'.format(a), 200) for pdf in pages: pdf.save('{}.jpg'.format(a.name[:-4]), 'JPEG') return render (request,'main.html',{'city_list':city_list,'page':pdf}) urls.py re_path(r'^city_list',views.city,name='city'), I am have not getting where I am going wrong? -
How to change main folder name permamently in django
I want to change main folder name in django(folder with manage.py), because I think current title makes some issues while i try run it on Heroku ("app crashed"). Current title: ShoppingList 2.0 But when i change it to for example ShoppingList2, in PyCharm it looks like this: I want to have only "ShoppingList2" without old name in brackets. -
DJANGO 3.0.5 AUTH_USER_MODEL refers to model 'auth.UserManager' that has not been installed
I know that this question may be a duplicate, but not a single answer on comment on other questions like this has not worked for me. So I am developing django app for online learning, like online school. At first I used Django built in Users (for test), ant the I switch to custom users.When I try to python manage.py makemigrations, it fails with the following error: https://pastebin.com/AMcjgY0y. So my auth/models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_admin, is_staff, **extras): if not email: raise ValueError('Potrebno je unijeti email adresu') email = self.normalize_email(email) user = self.model( email = email, is_staff = is_staf, is_active = True, is_admin = is_admin, last_login = timezone.now(), date_joined = timezone.now() **extras ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email = None, password = None, **extras): return self._create_user(email, password, False, False, **extras) def create_admin(self, email, password, **extras): return self._create_user(email, password, True, True, **extras) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 200, unique = True) name = models.CharField(max_length = 200, null = True, blank = True) is_staff = models.BooleanField(default = False) is_admin = models.BooleanField(default = False) last_login = models.DateTimeField(null = True, blank … -
How can I change the value of a Django model field when a particular choice is selected?
I created a model on django for blog posts. Each post has two status choices: Publish or Draft. How can i change Publish to Published after the post is saved? This is my code: from django.db import models from django.contrib.auth.models import User Create your models here. STATUS = [ (0,"Draft"), (1,"Publish"), ] class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=1,choices=STATUS) class Meta: ordering = ['-created_on'] def __str__(self): return self.title from django.contrib import admin from .models import * Register your models here class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','status','created_on',) list_filter = ("status",) search_fields = ('title', 'content') prepopulated_fields = {'slug': ('title',)} admin.site.register(Post,PostAdmin) -
Django Celery High Memory Usage
I have a fairly simple Django app that checks an API, the API basically runs a task, some of these tasks can last from a few seconds to a whole day. my Django app checks this API for the status of the task every 30 seconds using celery if the status is pending it checks again until the status == completed, the issue I am having right now is Celery uses about 300MiB/1.94GB of memory for this, and I end up having other tasks blocked, I am also trying to scale up as I have multiple of this app running on my Docker container, adding more workers won't solve my problem as this will increase the memory footprint as I deploy more instances of my app. How can I reduce the memory footprint of celery -
Django, is it possible to create hierarchical status choice with a model?
I have created a form that give the possiblity to the users to select a choice from a multiple choices and based on your choice can select the second form. The latter changes based on the first choice. The structure of my dataset is the following: -ProductA: -->sub_product_a_1 -->sub_product_a_2 -->sub_product_a_3 -ProductB: -->sub_product_b_1 -->sub_product_b_2 -->sub_product_b_3 So if the client choose in the first box form Product A, in the second box can choose only sub_product_a_1, sub_product_a_2 sub_product_a_3. I only just managed to create the two different levels of choice, but I haven't been able to create a new model that summarize all product and sub product created in a single table like this: Product | Sub_Product Product A | sub_product_a_1 Product A | sub_product_a_3 Product B | sub_product_b_1 Product A | sub_product_a_2 here my code models.py class Product(models.Model): slug = models.SlugField() product_category = models.CharField() class Subproduct(models.Model): product_category = models.ForeignKey() sub_product_category = models.CharField() Class Inventory(models.Model): category= models.ForeignKey(Product) sub_category= models.ForeignKey(Subproduct) -
My questions disappeared in my index page (Django polls project)
I followed a tutorial on YouTube and my website showed the questions below as bullet point links on the index page: "What's your name?" "what's your age?" I think I may have deleted some part of the code by accident, as the header and footer still appear. Should it be in the index page? attached below: {% extends 'polls/base.html' %} {% block main_content %} <h1 class="display-3">Choose a question</h1> {% if latest_questions %} <ul> {% for question in latest_question %} <li><a href= '/polls/{{question.id}}'><b>{{question.question_text}}</b></a></li> {% endfor %} </ul> {% else %} <p>You don't have any questions. Please add some. </p> {% endif %}[enter image description here][1] {% endblock %} Thank you!