Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Response returns code=415, message=Unsupported Media Type in Android-Rest API
I am trying to implement a user login in Android using Kotlin. In the backend runs Django. The API is created in RestFramework. The API works fine when tested in a browser. But when the same endpoint is tested using Android it returns 415 status code as follows. Response{protocol=http/1.1, code=415, message=Unsupported Media Type, url=http://endpoint/login/} The following is the post function fun post(){ val loginCredentials = UserModel("sampleuser","password") val gson = GsonBuilder().create() val payload=gson.toJson(loginCredentials) val okHttpClient = OkHttpClient() val requestBody = payload.toRequestBody() val request = Request.Builder() .method("POST", requestBody) .url("http://endpoint/login/") .build() request.headers("Content-Type:'application/json'") okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("Responed tO Post",e.message) } override fun onResponse(call: Call, response: Response) { val body = response?.body?.string() val user = gson.fromJson(body,UserModel::class.java) Log.e("res body user",user.username.toString()) } }) -
Why IndexError at / list index out of range in Django
I don't know why happens that with this code, I'm a Python Begginer, the original code is in https://github.com/yo-alan/horarios IndexError at / list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.22 Exception Type: IndexError Exception Value: list index out of range Exception Location: /Users/oscarfrancisco/PycharmProjects/ProyectosGithub/horarios-master/calendario/views.py in index, line 76 Python Executable: /Users/oscarfrancisco/PycharmProjects/ProyectosGithub/bin/python Python Version: 2.7.10 Python Path: ['/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/horarios-master', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python27.zip', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-darwin', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-mac', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-tk', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-old', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/site-packages'] Server time: Jue, 4 Jul 2019 20:02:39 -0300 def index(request): if not request.user.is_authenticated(): return render(request, 'calendario/index.html') if str(list(request.user.groups.all())[0]) == 'Profesionales': persona = request.user.usuario.persona especialidades = Especialidad.objects.filter(estado='ON', profesional=persona)\ .order_by('nombre') espacios = Espacio.objects.filter(~Q(estado=Espacio.OFF)) calendarios = Calendario.objects.all() context = { "espacios": espacios, "especialidades": especialidades, "calendarios": calendarios} else: institucion = request.user.usuario.instituciones.all()[0] especialidades = Especialidad.objects.filter(estado='ON', institucion=institucion)\ .order_by('nombre') espacios = Espacio.objects.filter(~Q(estado=Espacio.OFF), institucion=institucion) calendarios = Calendario.objects.all() for calendario in calendarios[:]: if institucion != calendario.espacio.institucion: calendarios.remove(calendario) profesionales = Profesional.objects.filter(estado="ON") for profesional in profesionales[:]: usuario = Usuario.objects.get(persona=profesional) if institucion not in usuario.instituciones.all(): profesionales.remove(profesional) context = { "espacios": espacios, "especialidades": especialidades, "profesionales": profesionales, "calendarios": calendarios} #~ try: #~ usuario = Usuario.objects.get(user=request.user) #~ except: #~ usuario = request.user return render(request, 'calendario/home.html', context) -
Trying to create a detail view with a list in the view with a sublist for each item. And I can create a item for every item on the same view
I am trying to finish this feature of my Django project. I have already created a list view and I am able to click on a topic on the list view and go into its detailed view. Once I am on that topic's detailed view there are a list of items that are associated with this topic. At the top of the page I have a form that when submitted will create an item and put it at the end of the item's list on the same detail view. For each item there are a list of subitems. For each subitem I am trying to create a submit button for it. So when I do click the submit button that subitem will be appended to the end of the list it was created under. Everything looks good but when I try to create a subitem it doesn't create the subitem for the right item. I hope this made since, can anyone point me in the right direction please?? I have created a list in a detailed view For each item in the list I have created a sublist For every item on any list I am trying to create a … -
Django Querysets - Objects including entire set in ManyToMany
I have a model, Respondent, related to another model Questionnaire via a ManyToMany field named finished. I have a set of four Questionnaire objects and would like to retrieve all Respondent objects that have a finished relationship with all four. I would also like to retrieve the inverse: Any Respondent object which doesn't have a finished relationship with all four selected Questionnaire objects. I've been looking through the docs, and haven't found something that works for me. I am able to get all of the Respondent objects that match at least one of the Questionnaire objects with Respondent.objects.filter(finished__in=questionnaire_queryset) but that's as far as I've gotten. -
How to generate extra files with the command `python manage.py startapp xxx`?
There is some way for the "python manage.py createapp xxx" command to generate some extra files like, e.g. xxx.urls, statics.dir, template.dir, etc. I would like to be able to avoid the work of having to generate the files and directories that I might need later. files as for example; app.urls, statics.dir, etc -
How to capture inputs in html and send to python
Im trying to set a web page that only shows inputs that collect: A EXCEL PATH SHEET RANGE and then a python script uses the variables to open the excel and take a screenshot of the Sheet:Area i have already the python script but to transfer from cmd to web i dont have any idea Im already try django and flask both i dont understand their use This is my html <form name = "search" action="." method="POST"> <label>Ruta:</label> <input type="text" name="path"> <label>Hoja:</label> <input type="text" name="sheet"> <label>Rango:</label> <input type="text" name="range"> <p></p> <label>Ruta de Guardado:</label> <input type="text" name="path2"> <label>Alto:</label> <input type="number" name="height"> <label>Ancho:</label> <input type="number" name="wid"> <p></p> </form> In the app.py (flask) project app.route('/', methods=['POST']) def getValue(): path = request.form['path'] sheet = request.form['sheet'] range = request.form['range'] path2 = request.form['path2'] he = request.form['height'] wd = request.form['wid'] excel2img.export_img(path,"test8.png", sheet, range) My python script (works with cmd) enter code here import excel2img from PIL import Image import os path = input('Introduce la ruta del archivo: ') sheet = input("Introduce el nombre del hoja: ") range = input("Introduce el rango: ") save = input("Introduce ruta de guardado") he = int(input("Introduce alto de la imagen: ")) wd = int(input("Introduce el ancho de la imagen: ")) path = … -
Why my django project servers static files from two URLS?
My django app serves my static files from '/static/' and from '/'. I have one folder called "static" where i put my favicon, but django load it two times in two differents urls Example: 127.0.0.1/favicon.ico (max-age = 60) 127.0.0.1/static/favicon.ico (miss max-age header) Note: My project have two "files" folder, one where I load manifest.json, robots.txt, etc, files that I want to have at '/'. I call that folder "templates" and render the files inside using templateview in urls (code below). In the other folder called "static" I have my javascript and my favicon. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'colorfield', 's3direct', 'apps.contact', 'apps.info', 'apps.products', 'apps.scheleudes', 'apps.messages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # compress js and css 'django.middleware.gzip.GZipMiddleware', # compress html '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', 'django.middleware.locale.LocaleMiddleware' # Internationalization for the admin site ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'views/dist/prod/templates') ], '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', ], }, }, ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'views/dist/prod/static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns = [ # routes path('', TemplateView.as_view(template_name='index.html')), path('productos/', TemplateView.as_view(template_name='index.html')), path('api/', include('apps.contact.urls')), path('api/', include('apps.info.urls')), path('api/', include('apps.products.urls')), path('api/', … -
Display form for a Custom User
I am build a custom user in Django by following this tutorial: https://wsvincent.com/django-custom-user-model-tutorial/ I manage to create it and add new fields such as: phone, location, firstname etc. However, when I click signup, these new fields do not appear. I do know know how to: 1) Make the added fields appear 2) Modify the html/css with bootstrap of that specific html signup page because I cannot find it I tried to add these fields in admin.py in list_display = ['email', 'username'] but doe snot work In admin.py I have: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username'] # HERE I TRIED TO ADD THE FIELDS SUCH AS 'location' BUT IT DOES NOT WORK admin.site.register(CustomUser, CustomUserAdmin) In forms.py I have: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name', 'organization', 'location', 'postcode', 'phone') In my models.py I have: `from django.contrib.auth.models import AbstractUser from django.db import … -
How to add a SQLServer Full Text Search in Django QuerySet?
In Django, one can use full text search natively when using Postgres. However, when using it with SQL Server (and django-pyodbc-azure) there is no simple way to do it (as far I know). To do a full text search in SQL Server you use the CONTAINS(column, word) function as described in the docs, but Django ORM contains do: LIKE '% text %'. I did find two alternative methods to bypass this problem. One is using RAW SQL the other is using django extra. Snippet using django raw SQL: sql = "SELECT id FROM table WHERE CONTAINS(text_field, 'term')" table = Table.objects.raw(sql) Using django extra: where = "CONTAINS(text_field, 'term')" table = Table.objects.extra(where=[where]) There is two problems with it: Raw queries are harder to mantain. Django docs. recommend against using the extra method. So I want to know if there a better way to do this, using "pure" django ORM if possible. -
Django REST framework. APITestCase. How test views which response for download data to csv
I have views like: class StudentAPIPerformanceReport( generics.RetrieveAPIView, ): def get(self, request, *args, **kwargs): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' writer = csv.writer(response) for student in Student.objects.filter(pk=self.kwargs['pk']): assigned_courses = CourseParticipant.objects.filter(student=student) completed_courses = assigned_courses.filter(completed=True) headings = ( "student full Name", "number of assigned courses to student", "number of completed courses by student" ) rows = ( student.full_name, assigned_courses.count(), completed_courses.count() ) writer.writerow(headings) writer.writerow(rows) return response Urls: path( 'student/report/<int:pk>/', StudentAPIPerformanceReport.as_view(), name='student_performance' ) And test for it view: class StudentAPIPerformanceReportTestCase(APITestCase): def setUp(self): self.student_obj = Student.objects.create( first_name='test', last_name='student', email='test_student@gmail.com', ) self.course_obj = Course.objects.create( name='test', ) student_obj = CourseParticipant.objects.create( course_id=self.course_obj.pk, student_id=self.student_obj.pk, ) def test_student_unassigned_from_course(self): data_id = self.student_obj.pk rud_url = api_reverse('student:student_performance', kwargs={'pk': data_id}) get_response = self.client.get(rud_url, data_id) self.assertEqual(get_response.status_code, status.HTTP_200_OK) But i have Traceback: Error Traceback (most recent call last): File "/home/project/test_task/student/tests.py", line 120, in test_student_unassigned_from_course get_response = self.client.get(rud_url, data_id) File "/home/project/test_task/venv/lib/python3.7/site-packages/rest_framework/test.py", line 292, in get response = super(APIClient, self).get(path, data=data, **extra) File "/home/project/test_task/venv/lib/python3.7/site-packages/rest_framework/test.py", line 199, in get 'QUERY_STRING': urlencode(data or {}, doseq=True), File "/home/project/test_task/venv/lib/python3.7/site-packages/django/utils/http.py", line 93, in urlencode for key, value in query: TypeError: 'int' object is not iterable Api which i wont to test just make some csv file in format: test student,1,0 How i can test it? I will be grateful for the help -
Postgres & Django - DataError: time zone not recognized
We are getting the following error from some of our users: DataError: time zone "Asia/Qostanay" not recognized We've found out that the problem was coming from the following SQL query: SELECT * FROM "app_foobar" WHERE ( EXTRACT('hour' FROM "app_foobar"."date" AT TIME ZONE 'Asia/Qostanay') = 0 ); -
query prints objects instead of some names in django
Is there a simple way to remove query set objects in my template just to print product name without the objects what it prints class SellerAccountMixin(object): products = [] def get_products(self): account = self.get_account() products = Product.objects.filter(seller=account) self.products = products return products class SellerDashboard(SellerAccountMixin,FormMixin, View): def get(self, request, *args, **kwargs): context["products"] = self.get_products() return render(request, "sellers/dashboard.html", context) template {% if products %} <div class='pull-left col-sidebar '> {{ products }} </div> -
Authenticate VueJS app to Django DRF back end using sessions
Good afternoon, I am writing an app structured with two docker containers. Docker1 is the front end VueJS app, Docker2 is the backend Django DRF API. I would like to manage access using Sessions (NOT JWT's). I am having trouble finding resources to help me get started on this approach. Does anyone have any good resources on how to interact with authenticating and managing Django sessions over DRF? Most of the examples use a DJango template form to do initial authentication which is not an option in this case. Thanks for your help. BCBB -
Regular expression not matching the given pattern
regular expression not matching. The current path, attendance/B-2019-07-05, didn't match any of these. ^attendance/(?P<date>\[AB]-\d{4}-\d{2}-\d{2})/$ [name='update_data'] -
Django model with dynamic fields based on foreign key
I am trying to implement a model where only a subset of the fields should be presented in forms, based on a foreign key in the model. The total number of fields is relatively low (~20), but may change frequently with different values of the foreign key. I would like to use something like single table inheritance, but with a single model (no inheritance). I looked at existing packages eav, dynamic models... but they did not seem to fit my needs. I part of the requirement is that I would like to query the models by sql without too many joins. Here is a use case representing applications to grants based on a request for application (rfa). The rfa is entered in the admin by staff and the applications are made by end users. application class rfa (request for application): foreign key field_1 ... field_20 rfa class: app_fields (coma separated list of field names) In the forms, only the fields in app_fields should be visible for a particular rfa. I have the rfa part covered with django-separatedvaluesfield and I was wondering how to implement the application pages so that they work with generic views in the frontend and admin, and … -
Django 2.0 + Sublime Text 3 + Windows, how can I start
I'm beginner in the python (sure not so novice, but it's not important) So, I'm gonna create web-app with using Django 2.0 in Sublime Text 3. In the internet not so many tutorials, special for Windows. To all other, they are all using PyCharm and hit "auto create project with venv". Due to it, I can't start! I want to know if Sublime Text 3 has a plugin for work with Django more easy, special if that plugin can create auto project with venv. Sorry for question not about code problem, but that problem so bad for me now! -
UWSGI default log not showing REMOTE_USER
In my UWSGI default log REMOTE_USER is empty. Could anybody please help me how to send this from Django Application. Or is there any way to have both default uwsgi log and custom log -
Static file does not work: Not Found: /{static 'logo.png'}
In my Django app I created a navbar. I want to diplay a small png image on the top-left of it. So I used the static file. In my mysite folder I created a folder called static_files. In this folder, I added my png image with the name logo.png The I changed my settings.py of mysiteas follows: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static_files/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' My base.html contains: {% load staticfiles %} <nav class="navbar navbar-light bg-light"> <a href=""> <img src="{static 'logo.png'}" alt="" class="d-inline-block alight-top"/> </a> <a class="" href="fdklsmflds">Login</a> <a class="" href="fdklsmflds">Sign up</a> </nav> I finally run python3.6 manage.py collectstatic BUT I GET THE ERROR: [04/Jul/2019 18:13:53] "GET / HTTP/1.1" 200 1379 Not Found: /{static 'logo.png'} [04/Jul/2019 18:13:54] "GET /%7Bstatic%20'logo.png'%7D HTTP/1.1" 404 2139 -
Listview display immediately after loading page in Django
I'm trying to write a small online store on django and I have a small problem: I want to display the listveiw immediately after the page loads, but django does not allow it I tried to make a display by pressing a button, and it worked, but I would like to make a display as soon as the page loads urlpatterns = [ path('', views.index, name = 'INDEX'), path ('prod/', ListView.as_view(queryset=Product.objects.all(), template_name="mainPage/homePage.html")) ] Can you help me? -
Django REST framework. APITestCase. How to fix ' bad_value, referenced_table_name, referenced_column_name'
I have the following models: class Student(models.Model): first_name = models.CharField(verbose_name='student first name', max_length=64) last_name = models.CharField(verbose_name='student last name', max_length=64) email = models.EmailField() class Meta: db_table = 'student' def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True, blank=True, default=None) end_date = models.DateField(null=True, blank=True, default=None) class Meta: db_table = 'course' def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE) completed = models.BooleanField(null=False, default=False) class Meta: db_table = 'course_participant' def __str__(self): return self.course, self.student Urls: app_name = 'student' urlpatterns = [ path( 'student', StudentAPIView.as_view(), name='list' ), path( 'student/detail/<int:pk>/', StudentAPIDetailView.as_view(), name='detail' ), path( 'student/assign_student_to_course', StudentAPIAssignToCourse.as_view(), name='assign_student_to_course' ), path( 'student/assigned_to_course', StudentAPIAssignedToTheCourseView.as_view(), name='assigned_to_course_list' ), path( 'student/assigned_to_course/detail/<int:pk>/', StudentAPIUnassignedFromTheCourseView.as_view(), name='unassigned_to_course_list' ), path( 'student/report/<int:pk>/', StudentAPIPerformanceReport.as_view(), name='student_performance' ) ] Views: import csv from django.http import HttpResponse from rest_framework import mixins, generics from course.models import ( CourseParticipant ) from student.models import ( Student ) from student.serializers import ( StudentSerializer, AssignStudentToCourseSerializer, StudentAssignedToTheCourseSerializer ) class StudentAPIView( mixins.CreateModelMixin, generics.ListAPIView ): serializer_class = StudentSerializer def get_queryset(self): queryset = Student.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class StudentAPIDetailView( mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView, ): serializer_class = StudentSerializer def get_queryset(self): query_set = Student.objects.all() return query_set def … -
cannot import name 'RemovedInDjango110Warning'
I cloned a django project from github and then I created a virtual env and installed requirements from requirements.txt file and when I load server I get following error: -
Pass object id from nested serializer to parent serializer in Django Rest Framework
I've created two serializers - ASerializer and BSerializer. A model has b many-to-many field with relation to B. My goal is to be able to update multiple nested B objects while updating A object. My serializers: class ASerializer(WritableNestedModelSerializer): b = BSerializer(many=True) class Meta: model = A fields = '__all__' read_only_fields = ['id'] def update(self, instance, validated_data): info = model_meta.get_field_info(instance) bs_data = validated_data.pop('b', None) for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: field = getattr(instance, attr) field.set(value) else: setattr(instance, attr, value) if bs_data: for b_data in bs_data: b_serializer = BSerializer(data=b_data) if b_serializer.is_valid(): b = B.objects.update(**b_data) instance.b.add(b) else: raise exceptions.ValidationError(todo_serializer.errors) return instance class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = '__all__' read_only_fields = ['id'] And models: class A(models.Model): name = models.CharField('Name', max_length=250) content = models.TextField('Content') b = models.ManyToManyField('bs.B', blank=True, null=True, verbose_name='todo', related_name='as') class B(models.Model): name = models.CharField('Name', max_length=250) description = models.TextField('Description') The problem I encountered is, that during update (PATCH), printing bs_data, all I get is [OrderedDict([('name', 'test'), ('description', 'none')]), OrderedDict([('name', 'another'), ('description', 'one')])] And I cannot update all nested B objects - every nested object gets the content of last provided one (so in this example above, every nested object would be filled with 'another' name and … -
How to copy m2m fields when copying one model to another
I am able to copy all of the properties of a model except the m2m fields using a post_save signal. The QuerySet returns empty when using the same steps that work in the shell so I am unable to add the fields to the new object/model. signals.py @receiver(post_save, sender=RecurringEventItem) def create_calendar_event(sender, instance, created, **kwargs): if created: min_date = datetime.now() - timedelta(days=365) max_date = datetime.now() + timedelta(days=365) recurring_event = RecurringEventItem.objects.get(pk=instance.id) print(recurring_event.attendee) print(recurring_event.attendee.all()) if recurring_event.attendee is not None: attendees = recurring_event.attendee.all() if instance.recurrences is not None: calendar_item_list = [] recurrence_dates = list(instance.recurrences.between(min_date, max_date)) for date in recurrence_dates: new_calendar_item = CalendarItem(name=instance.name, start_date=instance.start_date, completion_date=instance.completion_date, description=instance.description, end_date=datetime.date(date)) if attendees: new_calendar_item.calendar_attendees.add(attendees) calendar_item_list.append(new_calendar_item) CalendarItem.objects.bulk_create(calendar_item_list) Works in the shell: test = RecurringEventItem.objects.get(pk='42f59a0ba1ac40858256a607fd8c57a3') test_2 = test.delegated_to.all() test_2 <QuerySet [<Contact: Test Person>]> Result of the QuerySet when the app is running. <QuerySet []> -
How to iterate a value based on an object value in django template
I have a model which is 'Saloon' class. I want to iterate saloon name based on the value of capacity. I tried many answers (forloop.counter, Custom template tags and filters) but could not manage to do it. I only want to repeat the saloon's building and name based on the capacity value models.py class Saloon(models.Model): building= models.CharField(max_length=55) name= models.CharField(max_length=125) capacity= models.IntegerField() views.py from django.shortcuts import render from .models import Saloon def salonogrenci(request): saloons = Saloon.objects.all() return render(request, 'salonogrenci/home.html', {'saloons':saloons }) home.html <table class="table table-hover"> <tbody> {% for saloon in saloons %} {% for i in range(saloon.kapasite) %} <tr> <th scope="row">{{ saloon.building }}</th> <td>{{ saloon.name }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> -
What is usecase of Django Management script?
I heard of about Django Custom Management script in lots of community and i am not getting why should i write custom management script as django manage.py a lot of useful command? I am very new in django... Can anyone tell me some usecase of custom management script? Thanks