Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value of select field from a django for loop in template and passing seledted field value via ajax to server side django
I have a static select option in my template within a customer orders for loop.. now i want to change status (select) via js and send the data back to django view. but how am i suposed to do that. i have tried in many ways but nothing seems to work -
Django create unique function index
With postgresql we can create unique function index: create unique index user_date_checkin on unique_user_date (user_id, (timezone('UTC'::text, create_time)::date)); But with Django 3.2: class UserCheckin(GeneralModel): id = models.BigAutoField(primary_key=True) user_id = models.BigIntegerField() create_time = models.DateTimeField() class Meta: indexes = [ models.Index("user_id", TruncDate("create_time"), name="user_date_checkin"), ] can only got such sql generation: create index user_date_checkin on test (user_id, (timezone('UTC'::text, create_time)::date)); And UniqueConstraint constraints = [ models.UniqueConstraint( fields=["user_id", TruncDate("create_time")], name="user_date"), ] got refers to the nonexistent field 'TruncDate(F(create_time)) error So how can I create unique index with function in Django 3.2? -
Git bash "Watching for file changes with StatReloader" stuck and never loads
I have setup a Django project on a virtual environment on my PC. When using the command python manage.py runserver 0.0.0.0:8000 Bit Bash stops doing anything and I have to end the program to start over. I have waited several minutes and when I end the session, a dialogue says: Processes are running in session: WPID PID COMMAND 14904 1534 c:\Users\mine\AppData\Loca Close anyway? I have looked at every related question to this and tried every solution but I cannot get this to work, on or off the virtual environment. -
Showing unreserved times in frontend of django booking app
Im trying to build a booking app with Django. this is my "Event model" in my model.py: user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL) date = models.DateField(null=True) time = models.TimeField(null=True) end_time = models.TimeField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) #date: Date the user want to come #time: The time the user want to come. #end_time: the time that the owner guesses for ending the job that user want time for it. What i want to do?: I want to take that time the user want to come. and after this action, owner select the #end_time. (between these times Users cant reserve time...) Question: I need to show empty or unreserved times to user in template... if you have any idea or respones in both logical side and front side, please help me and type it for me. -
Updating a model when an object it references through a ManyToMany relation is deleted
I have a model, for instance class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): last_modified_time = models.DateTimeField() as = models.ManyToManyField('ModelA') when I delete an instance of ModelA I would like to also update the last_modified_time field on all ModelB instances that referred to ModelA. I can use a predelete signal for this, i.e. def pre_delete_handler(sender=None, instance=None, *args, **kwargs): # update all using instance.modelbs... models.signals.pre_delete.connect(pre_delete_handler, sender=ModelA) but then every time a new model references it via a ManyToMany this bit of code needs to be updated which isn't the best from a maintenance point of view. I am looking for a way to enumerate all models that ModelA is referenced by so I can have a single update that covers all cases but can't figure out the best way to do this. What is the proper way to enumerate all objects that ModelA is related to? -
if there is not Error why its color dont changed?
this is my github, i dont know why even though there is not error the color of stule.css didnt ocuerr? https://github.com/Angelheartha/tera i dont know even though polls/templates/polls/index.html indicate polls/static/polls/style.css when i do python manage.py runserver and http://localhost:8000/polls/ i cant see that the colors changed to green i tried to test if there is error but there is not error so why the color didnt changed? -
How to add get_queryset function in apiview of Djnago rest framework?
I am using Django APIView to include all my CRUD operation in a single api endpoint. But later on I had to use filtering logic based on the query parameters that have been passed. Hence I found it to include in a get api of APIView and made a separate api using generic view, ListAPiview. Here is the view: class LeadsView(APIView): permission_classes = [IsAuthenticated] def get(self, request, pk=None, *args, **kwargs): id = pk if id is not None: abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc) return serializer.data def post(self,request,*args,**kwargs): abc = LeadSerializer(data=request.data,many=True) if abc.is_valid(): abc.save() return Response(abc.data, status=status.HTTP_201_CREATED) return Response(abc._errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request,pk, *args, **kwargs): Now, I have to use filter class and also some custom filtering logic, I need to use get_queryset. Hence I have to create another api just for get method which I dont want. class LeadAPIView(ListAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Lead.objects.all().order_by('-date_created') serializer_class = LeadSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] pagination_class = CustomPagination # filterset_fields = [ 'email','first_name','last_name','phone'] filterset_class = LeadsFilter def get_queryset(self): source = self.request.GET.get("source", None) # lead_status = self.request.GET.get("lead_status", None) if source is not None: source_values = source.split(",") if lead_status is not None: lead_status_values= lead_status.split(",") return Lead.objects.filter(source__in=source_values,lead_status__in=lead_status_values) else: return Lead.objects.filter(source__in=source_values) elif lead_status is … -
how to update django table data?
I created attendance management system and i want that when user enter attendace , if attendance for that date already exist than it only update. How to update attendance field in attendance table if data is already exist of that date ? This is my views file def index(request): staffs = staff.objects.all() a = staff.objects. values_list('id', flat=True) attendances = attendance.objects.all() amounts = amount.objects.all() date = datetime.date.today() if request.method == "POST" : for i in a : print(i) stf = 'staff_id' + str(i) print(stf) atd = 'attendance' + str(i) print(atd) staff_id = request.POST.get(stf, None) attendances = request.POST.get(atd, None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() return HttpResponseRedirect("/index") date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'amount': amounts, 'date': date}) This is my template file where their is form <form action="/index" method="POST"> {% csrf_token %} {% for staffs in staff %} <input type="hidden" name="staff_id{{staffs.id}}" value="{{staffs.id}}"> <input type="hidden" name="attendance{{staffs.id}}" id='input_attendance{{staffs.id}}'> <tr> <td> {{staffs.id}} </td> <td> {{staffs.name}} </td> <td> <div class="btn-group"> {% for attendances in attendance %} {% if attendances.staff_id|add:0 == staffs.id|add:0 %} {% if attendances.attendance == 'present'%} {% if attendances.date == date %} <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='present{{staffs.id}}'> Present </button> {% else %} <button type="button" … -
di_form's is_valid() not working properly
models.py class DeviceInterface(models.Model): MODULE_ID_CHOICES = ( ('TenGigabitEthernet','TenGigabitEthernet'), ('FortyGigabitEthernet','FortyGigabitEthernet'), ('GigabitEthernet','GigabitEthernet'), ('Ethernet','Ethernet'), ) moduletype = models.CharField(max_length = 50,choices = MODULE_ID_CHOICES) firstportid = models.CharField(max_length=50) lastportid = models.CharField(max_length=50) I2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.moduletype forms.py class DeviceInterfaceForm(ModelForm): class Meta: model= DeviceInterface fields= ['moduletype', 'firstportid', 'lastportid'] labels = { "moduletype":"Module Type", "firstportid": "First Port ID", "lastportid": "Last Port ID" } Part of views.py if di_form.is_valid(): deviceI=di_form.save(commit=False) print(deviceI) for instances in deviceI: instances.I2DKEY=new_device instances.save() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) else: print(deviceI.errors) I have the following codes above, few weeks ago it is working. But now its not working. When i submit my form, it somehow goes is_valid()=True. So meaning my text fields for this model can be empty and the form can still be saved somehow. PS: This webpage have a total of 3 different forms. So if this form's field are all empty, it saves the the other models instead. Can anyone explain to me what am i doing wrongly? -
How to change files name of django InMemoryUploadedFile before upload to S3 without models?
Environments Django==3.24 DRF==3.11 boto3==1.16 django-storages==1.10 I want to change files name before upload to s3 without saving in DB(model). I tried like this. # in Post request files = request.FILES.getlist('files') res = [] for file in files: random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8)) ext = file.name.split('.')[-1] file_name = f'{random_car}.{ext}' # -------- try start --------- # I want to change file name to file_name # This code throws an error. # FileNotFoundError: [Errno 2] No such file or directory: '8.jpeg' -> 'kVuepnuR.jpeg' os.rename(file.name, file_name) # -------- try end --------- file_path_within_bucket = os.path.join( file_directory_within_bucket, file.name ) default_storage.save(file_path_within_bucket, file) file_url = default_storage.url(file_path_within_bucket) res.append(file_url) How can I change the name if InMemoryUploadedFile? -
Django - Verify AWS Cognito token is valid before processing endpoint request
So I have this code below for checking a AWS Cognito token. I obviously don't want to add these 6 lines of code to every endpoint. How can I authenticate the AWS amplify token that comes with every request to ensure the user is properly logged in. Can I get the user's email from this token somehow? views.py def post(self, request): # 'Bearer z324weroko2iorjqoi=+3r3+3ij.2o2ij4=' token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] print(token) # TODO this should be separated out to a login module try: res = jwt.decode_cognito_jwt(token) return Response(status=status.Http_200_OK) except: return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) -
TypeError: list indices must be integers or slices, not str in Django 3.0
While converting the csv file data in django models i am getting an issue def upload_timesheet(client, user1, csv_file): field_map_1 = { 'Date' : 'date', 'Client Name' : 'worked_on', 'Employee Name': 'user', 'Employee Number': 'employee_number', 'Start Time(HH:MM:SS)': 'start_time', 'End Time(HH:MM:SS)': 'end_time', 'Break Taken(HH:MM:SS/HH:MM)': 'breaktime', 'Assignment id': 'assignment', 'Rate': 'work_assign', } def get_values_remapped(row): return {field_map_1[key]: row[key].strip() for key in field_map_1} Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 3011, in upload_timesheet remapped_row = get_values_remapped(row) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in get_values_remapped return {field_map_1[key]: row[key].strip() for key in field_map_1} File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in <dictcomp> return {field_map_1[key]: row[key].strip() for key in field_map_1} TypeError: list indices must be integers or slices, not str [2021-09-01 09:34:29,484: ERROR/ForkPoolWorker-1] list indices must be integers or slices, not str Traceback (most recent call last): File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 3011, in upload_timesheet remapped_row = get_values_remapped(row) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in get_values_remapped return {field_map_1[key]: row[key].strip() for key in field_map_1} File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in <dictcomp> return {field_map_1[key]: row[key].strip() for key in field_map_1} TypeError: list indices must be integers or slices, not str When trying to fetch the data of the uploaded csv file getting the following error in Django 3.0 to python 3.7 please help me to … -
How to print first 100 character in django?
I want to print first 100 character of string in django. {% if dt.faq_info|length < 100 %} {{dt.faq_info}} {% else %} {{dt.faq_info[:100]}} {% endif %} But I recieved TemplateSyntaxError Could not parse the remainder: '[:100]' from 'dt.faq_info[:100]' Is there any other way to do this? -
How to restore a dump database backup for a Django project with existing models and migrations?
Setting up a mysql database from an existing dump is very easy # open prompt cd into the directory where the dump is located # login to mysql create database mydb use mydb source mydb.sql And all is done! But the problem comes with Django. Django has troubles with existing schemes and data that have not been created from models and migration system. And in Django, everything must come from models and migrations. I perfectly know that I have this option python manage.py inspectdb > models.py But this is only suitable when creating a blank new Django project using existing database. What if I want to run an existing Django project to another machine and the Django project uses a database? The project already has existing models with some manage=false set, I cannot simply inspectdb it. And if I restore the database outside Django, the Django ORM will no longer recognize it. Then what is the correct way to restore a database from a database backup for a project with existing models and migrations? -
How to mark cloned form from inline as deleted so Django knows what to save and what not to save
views.py: def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) dd_form = DeviceDetailForm(request.POST) di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'),widgets={ 'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=1,max_num=3, can_delete=False) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) print(deviceI) for instances in deviceI: instances.I2DKEY=new_device instances.save() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) else: device_frm = DeviceForm() dd_form = DeviceDetailForm() di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), widgets={ 'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=1, max_num=3, can_delete=False) di_form=di_formset(queryset = DeviceInterface.objects.none()) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) HTML: {{di_form.management_form}} <div id = "rowAddition"> {% for form in di_form %} <div> <div class="row"> <div class="col-md-2"> <div class="form-group"> <label for="{{di_form.moduletype.id_for_label}}">Module Type<span class="text-danger">*</span></label> {{form.moduletype}} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="{{di_form.firstportid.id_for_label}}">First Port ID<span class="text-danger">*</span></label> {{form.firstportid}} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="{{di_form.lastportid.id_for_label}}">Last Port ID <span class="text-danger">*</span></label> {{form.lastportid}} </div> </div> </div> </div> {%endfor%} <div id="empty-form" style="display: none;"> <div class="row"> <div class="col-md-2"> <div class="form-group"> <label … -
How to get filter param as part of the queryset for Django
Context I want the parameters I am filtering on to be present in the queryset e.g. my_list = ["abx", "xyz" ...] Foo.objects.filter(some__name__icontains=my_list) I want "abx" to be part of the queryset object foo.some_param == "abx" or foo1.some_param == "xyz" Essentially I want the matching param to be present in the output queryset Is there an easy way to do that? Any help is highly appreciated -
How to display json details in a webpage using Django?
I have created a Django project which scrape data from a website and stores data in a JSON file, I want to create a Search bar in a webpage which searches and display Whole contents of data from Json file in a table. For ex: My JSON file looks like this. [ {"course_speed": "325.9\u00b0 / 9.3 kn", "current_draught": "5.3 m", "navigation_status": "Under way", "position_received": "0 min ago ", "imo": "9423841 / 246346000", "call_sign": "PBPQ", "flag": "Netherlands", "length_beam": "100 / 16 m"} ]. What I need is if I enter IMO number in Search bar, this json details should be displayed on a table. Thanks. -
How to create a ChoiceField for user email from EmailAddress model of allauth in django restframework?
I am using django allauth and restframework in backend for API. My question is how can i create a ChoiceField in my serializer with the email addresses of the logged in user as values so that instead of a textfield the form will create a Select field for email field. so far I have created a AuthUserSerializer serializer for my user API. users/serializers.py from rest_framework import serializers from users.models import * emails = [(email.email, email.email) for email in EmailAddress.objects.all()] class AuthUserSerializer(serializers.ModelSerializer): email = serializers.ChoiceField(choices=emails) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'avatar', 'bio', 'country', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined') extra_kwargs = { 'is_staff': { 'read_only': True }, 'is_superuser': { 'read_only': True }, 'last_login': { 'read_only': True }, 'date_joined': { 'read_only': True } } I have initialized the email field as a ChoiceField in the above code and the choices are the emails got from the EmailAddress model. But I want to get the emails created by the requested user. I don't know how to do it. I tried creating a CustomChoiceField like below, but still it does not work. class CustomChoiceField(serializers.ChoiceField): def __init__(self, **kwargs): user = self.context.get('request').user emails = [(email.email, email.email) for email in EmailAddress.objects.filter(user=user)] … -
Problem with downloading and saving excel file with django
I have a 3 problems, cannot figure it out, maybe there are connected. Problem 1.1: file is exported in django documentation and it works, but when I try to rename it, it has some error. I want to be like this with pd.ExcelWriter(newdoc + 'output.xlsx') as writer: in order to every file has a "new" name. Problem 1.2: How to add path where to save? Problem 2: I get to download file but it is empty, and name of document is Donwload.xlsx. I want to be like this, but this got many errors... filename = newdoc + '_calculated.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response This is views.py def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with pd.ExcelWriter('output.xlsx') as writer: #problem 1 for name, df in dfs.items(): #pandas code for uploaded excel file out.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' #problem 2 return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) -
Getting a bad request when pointing domain to vps
Hey everyone after deploying my Django App I tried to point my domain name to my VPS via A records and for some reason it just takes me to a bad request (400). I checked and the dns is resolving for the A records so I'm stuck on what the problem could be. http://31.220.62.130/ this is the IP address of the website and it works when I put this into the URL. Hustlestriking.com is the domain name that gives me the bad request. Im using hostinger for the VPS and the domain name. -
Gantt Charts In Django
I have been trying to make gant charts in Django but not being able to so. In python I have tried this: import plotly.figure_factory as ff df = [dict(Task="Job-1", Start='2017-01-01', Finish='2017-02-02', Resource='Complete'), dict(Task="Job-1", Start='2017-02-15', Finish='2017-03-15', Resource='Incomplete'), dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Not Started'), dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Complete'), dict(Task="Job-3", Start='2017-03-10', Finish='2017-03-20', Resource='Not Started'), dict(Task="Job-3", Start='2017-04-01', Finish='2017-04-20', Resource='Not Started'), dict(Task="Job-3", Start='2017-05-18', Finish='2017-06-18', Resource='Not Started'), dict(Task="Job-4", Start='2017-01-14', Finish='2017-03-14', Resource='Complete')] colors = {'Not Started': 'rgb(220, 0, 0)', 'Incomplete': (1, 0.9, 0.16), 'Complete': 'rgb(0, 255, 100)'} fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True) fig.show() but I want the same to run in Django. Thanks. -
How to create a custom API views in Django Rest Framework
I want to create a custom API view based on existing data. models.py class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) score = models.SmallIntegerField(null=True) correct = models.SmallIntegerField(null=True) wrong = models.SmallIntegerField(null=True) not_answered = models.SmallIntegerField(null=True) class Meta: managed = True db_table = 'practice' def __str__(self): return str(self.practice_id) serializers.py class PracticeSerializer(serializers.ModelSerializer): class Meta: model = Practice fields = ('practice_id', 'score', 'correct', 'wrong', 'not_answered', ) views.py @api_view(['GET']) def practice_detail(request, pk): try: practice = Practice.objects.get(pk=pk) except Practice.DoesNotExist: return JsonResponse({'message': 'The practice does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': exercises_serializer = PracticeSerializer(practice) return JsonResponse(exercises_serializer.data) With the code above I get the results of the API view as below using practice id 485 : /api/practice/485 { practice_id: 485, score: 10, correct: 2, wrong: 3, not_answered: 0, } Now I want to create a custom API view with the result as below : { labels: ["Practice"], datasets: [ { label: "Correct", data: [2], }, { label: "Wrong", data: [3], }, { label: "Not_answered", data: [0], } ] } How to do that? Is possible to achieve that without create new models? -
'InMemoryUploadedFile' object has no attribute 'to_excel' - Django
I got a problem, I got this script in python pandas and it working perfectly, I needed to do like this in order to process pandas in whole document, but now when I'm trying to put in django I got this error... Any ideas? Error AttributeError at / 'InMemoryUploadedFile' object has no attribute 'to_excel' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.6 Exception Type: AttributeError Exception Value: 'InMemoryUploadedFile' object has no attribute 'to_excel' Exception Location: /home/user/django-pandas/myapp/views.py, line 50, in my_view Python Executable: /usr/bin/python Python Version: 3.9.6 This is views.py def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = request.FILES['docfile' dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with pd.ExcelWriter('output_.xlsx') as writer: for name, df in dfs.items(): #pandas code # after pandas code output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') newdoc.to_excel(writer, index=False) #error (this is line 50) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) Thanks in advance! -
Django - Going back to a directory at a upper level from the template with href in django
trying to keep the question simple! I am currently in the directory which has a template cart.html: 8000/shop/cart/6/M/user and I want to go to the directory: 8000/shop/shirts So I just wrote in the cart.html: <a href="{% url 'shop' 'shirts' %}"> Which gives me an error: Reverse for 'shop' not found. 'shop' is not a valid view function or pattern name. So, I believe that its because I am trying to go from a lower directory back into a higher directory in the hierarchy so is there a way I can edit the href in cart.html in order to go to the shirts directory? Thanks in advance, -
How to iterate in subitems of a object in a django template
views.py: from django.views import generic from .models import Servico class ServicoView(generic.DetailView): model = Servico context_object_name = 'servico' template_name = 'servico.html' models.py: from djongo import models class PublicoAlvo(models.Model): def __str__(self): return '' alvo1 = models.CharField(max_length = 126) alvo2 = models.CharField(max_length = 126, blank = True, default = '') class Meta: abstract = True class Servico(models.Model): t_id = models.CharField(primary_key = True, unique = True, max_length = 252) alvos = models.EmbeddedField( model_container = PublicoAlvo ) urls.py: from django.urls import path from . import views urlpatterns = [ path('servicos/<slug:pk>/', views.ServicoView.as_view(), name = 'servico') ] I think these are the relevant files in my Django app folder. Back to the question, how can I iterate over the values that are going to be stored in servico.alvos in my template? If I want to show t_id, I just use {{ servico.t_id }} and it works fine. I could write something like: {{ servico.alvos.alvo1 }} {{ servico.alvos.alvo2 }} And that would show the values that I want, but that would make things uglier and more limited (imagine if I decide to change the model and add more 6 values in the PublicoAlvo class). I tried the following: {% for alvo in servico.alvos.all %} {{ alvo }} {% …