Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can get last nth item of a query on PostgreSql
Question: How I can get the last 750 records of a query in the Database level? Here is What I have tried: # Get last 750 applications apps = MyModel.active_objects.filter( **query_params ).order_by('-created_at').values_list('id', flat=True)[:750] This query fetches all records that hit the query_params filter and after that return the last 750 records. So I want to do this work at the database level, like mongoDb aggregate queries. Is it possible? Thanks. -
Django form submit redirect to a different url
Please help action is set to =".", but django redirects to another url views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share'), ] detail.html <h2>Add a new comment</h2> <form action="." method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> When i click on submit button i expected it to remain on this url "http://localhost:8000/blog/2019/11/20/one-more-post", but it cut off the slug part and redirect to this: "http://localhost:8000/blog/2019/11/20/", there by throwing page not found error "Page not found (404)" -
Django - Pre-populating a ModelForm with parameters passed in url
I am trying to pre-populate a ModelForm with data from an url but get the following error message: Reverse for 'create_entry' with arguments '(1, datetime.date(2019, 11, 1))' not found. 2 pattern(s) tried: ['create_entry/<int:habit_id>/(?P<selected_day>\\d{4}-\\d{2}-\\d{2})/$', 'create_entry/$'] In the template, the url reads: {% url 'habitap:create_entry' habit.id date %} and in the url conf, I have: re_path(r'^create_entry/<int:habit_id>/(?P<selected_day>\d{4}-\d{2}-\d{2})/$', create_entry, name='create_entry') and path('create_entry/', create_entry, name='create_entry') ( I am using a view with optional arguments) If I take out habit.id from the url, the error goes away but the form doesn't get pre-populated and the url is not declared properly. Please do not hesitate to let me know if you need more information. Thank you for your help ! -
django.db.utils.ProgrammingError: column calculator_calculation._id does not exist using heroku and djongo
My app works on my local machine but when deployed to heroku with the exact same code I get errors when using get requests to my API views involving any DB interaction. I have a feeling heroku is trying to use postgres for some reason, even though I do not have any code dealing with postgres in my code. Any help is appreciated, I have done migrations a million different ways with no luck, even though mongo shouldnt need migrations. Error and code below 2019-11-21T18:26:15.428986+00:00 app[web.1]: Traceback (most recent call last): 2019-11-21T18:26:15.428989+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner 2019-11-21T18:26:15.428991+00:00 app[web.1]: response = get_response(request) 2019-11-21T18:26:15.428993+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response 2019-11-21T18:26:15.428995+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2019-11-21T18:26:15.428997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response 2019-11-21T18:26:15.429000+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2019-11-21T18:26:15.429002+00:00 app[web.1]: File "/app/calculator/views.py", line 22, in calculate 2019-11-21T18:26:15.429004+00:00 app[web.1]: print(calcs) 2019-11-21T18:26:15.429006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __repr__ 2019-11-21T18:26:15.429008+00:00 app[web.1]: data = list(self[:REPR_OUTPUT_SIZE + 1]) 2019-11-21T18:26:15.429010+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 274, in __iter__ 2019-11-21T18:26:15.429012+00:00 app[web.1]: self._fetch_all() 2019-11-21T18:26:15.429014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all 2019-11-21T18:26:15.429016+00:00 app[web.1]: self._result_cache = list(self._iterable_class(self)) 2019-11-21T18:26:15.429018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__ 2019-11-21T18:26:15.429020+00:00 app[web.1]: results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) 2019-11-21T18:26:15.429022+00:00 app[web.1]: File … -
Pycharm & Django w/ multiple settings and environment variables issues
I have an issue creating apps and running server from Terminal in PyCharm django project. I have used Pycharms manage.py tool option it doesnt work either. but I cant see my env variables in terminal when I type env. My settings.py looks like this: import os import json import dj_database_url import django_heroku if os.environ.get('DJANGO_DEV'): with open('config.json') as data: configs = json.load(data) from project.dev_settings import * else: configs = os.environ.get('SECRET_KEY') and at the bottom I have heroku settings like this(which works like a charm) DATABASES['default'].update(db_from_env) django_heroku.settings(locals()) when I type for example python manage.py runserver I get an error TypeError: 'NoneType' object is not subscriptable I am clueless at this point what is wrong since I have setup my env variables in pycharm configuration. -
Infinite list filtering does not work - Django
Creates the simplest infinite list that expands when it reaches the end of the page. My code looks something like this: views.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger query = Product.objects.all() #paginator page = request.GET.get('page', 1) paginator = Paginator(query, 21) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) in the template I use it this way: <!-- products list --> <div class=" infinite-container"> <!-- product query --> {% for product in numbers %} <div class="accordion accordion-spaced infinite-item"> <h1>{{ product }}</h1> </div> {% endfor %} <!-- end query --> </div> <!-- Load more --> {% if numbers.has_next %} <div class="mt-4 text-center"> <a href="?page={{ numbers.next_page_number }}" class="btn infinite-more-link">Loading...</a> </div> {% endif %} <!-- end pagination --> <!-- Infinite Scroll --> <script src="{% static 'assets/js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'assets/js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'assets/js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> If I try to add filtering by category, it works only for the first page, and the next items that showed after expanding are incorrect (it shows what should not). I do it this way: query = Product.objects.all() sort = request.GET.get('sort', False) if sort: query = query.filter(category=sort) #[... other elements in … -
Django admin site: customize the select_to_change.html
How to customize the Select_to_change.html? i just want that the viewi is like this not like this this is my model.py class gradingPeriod(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Grade_Scales_Setting= models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) StartDate=models.DateField(null=True,blank=True) EndDate=models.DateField(null=True,blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) class gradingPeriodsSetting(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) class gradingPeriodsSummary(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Grading_Periods_Setting= models.ForeignKey(gradingPeriodsSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Start_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) End_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) I dont know how to code it to admin.py, is it possible right? -
Bulk upsert with Django
bulk_create with ignore_conflicts=True insert new records only and doesn't update existing one. bulk_update updates only existing records and doesn't insert new one. Now I see only one variant to make upsert is a raw query: from catalog.models import Product with connection.cursor() as cursor: cursor.executemany( """ INSERT INTO app_table (pk, col1, col2) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE col1 = VALUES(col1), col2 = VALUES(col2); """, [ ('1', 'val1', 'val2'), ('2', 'val1', 'val2'), ] ) Is there another way to perform bulk upsert in Django? -
Pagination bar not rendering properly in html page
Using: https://medium.com/@sumitlni/paginate-properly-please-93e7ca776432 as reference. I am working with a couple hundred thousand rows of data and have been rendering the data in an html page. So far, I am properly displaying the first 10 rows of data but my pagination bar that should display under the table is not displaying, but I can change the page number by appending '?page=1' to the url. My view function and template are below, while url_replace.py and proper_paginate.py are unchanged from the link posted above: views.py def eventcode(request): meters_obj = Meterdiagbyday.objects.all() page = request.GET.get('page', 1) paginator = Paginator(meters_obj, 10) try: meters_obj = paginator.page(page) except PageNotAnInteger: meters_obj = paginator.page(1) except EmptyPage: meters_obj = paginator.page(paginator.num_pages) return render(request, 'searchengineapp/eventcode.html', {'meters_obj': meters_obj}) template {% if is_paginated %} {% load url_replace %} {% load proper_paginate %} <ul class="pagination"> {% if meters_obj.number == 1 %} <li class="disabled"><span>⇤</span></li> {% else %} <li><a class="page-link" href="?{% url_replace request 'page' 1 %}">⇤</a></li> {% endif %} {% if meters_obj.has_previous %} <li><a class="page-link" href="?{% url_replace request 'page' meters_obj.previous_page_number %}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator|proper_paginate:meters_obj.number %} {% if meters_obj.number == i %} <li class="disabled"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a class="page-link" href="?{% url_replace request 'page' i %}">{{ … -
Formset Factory Make Fields Required
I am using a modelformset_factory in Django to have a user fill out an unknown number of fields. I have made the fields required but in the HTML rendering Django does not add required to the HTML element, looking around online this seems to be a common issue but I have not seen any valid answers that apply for what I want and I feel like this should be simple. How do I make Django add the required tag to appropriate HTML elements? class ItemForm(forms.ModelForm): class Media: js = (formset_js_path,) class Meta: model = PurchaseOrderItems fields = ['name', 'vendor', 'quantity', 'price', 'description'] labels = { 'name': 'Item', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.fields['description'] .widget.attrs['required'] = 'required' self.empty_permitted = False self.fields['description'] = forms.CharField( required=False, label='Description', ) def clean(self): """ :return: """ cleaned_data = super().clean() # print(cleaned_data) ItemFormSet = modelformset_factory( PurchaseOrderItems, form=ItemForm, extra=0, min_num=1, validate_min=True, can_delete=True, ) Here is the HTML rendered for the name field, no required: <input type="text" name="form-0-name" maxlength="150" class="form-control" id="id_form-0-name"> -
Django related question. Should a client script import my models or have its own classes?
(note, this is for a private research database using django. This is not for a public website. Users can have access to all source code) I want to build the data for a django model in a script ran off server by a client. The client script will post json to a url where a django view will create the model and save to database on the server. On the client script side I plan to build objects of a class mirroring the model, then put that in json with a method that builds a dictionary. I'm wondering if there is some best practice for this which I am unaware of. Should the script import the actual django model code, or should a new class with the same properties but only derived from "object" be used. -
Django logout bootstrap navbar
I want to add a logout button to my bootstrap navbar but it doesn't look right. {# template.html #} <nav class="navbar navbar-light"> <div class="container"> <div class="navbar-expand"> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a href="#" class="nav-link">{{ user.get_username }}</a> </li> <form class="form-inline nav-item" action="{% url 'account_logout' %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-info">Log out</button> </form> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'account_login' %}">Log in</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'account_signup' %}">Sign up</a> </li> {% endif %} </ul> </div> </div> </nav> is there any way to make the button look like a bootstrap nav-link ? If not, how do I make it an anchor that will POST to Django's logout endpoint? -
In Django model how to use related models to check if employee's training is up to date?
Employees have periodic training. When they are hired they have an initial training "I". After a period of time based on TrainingCourse, all employees in a TrainingEvent are due for refresher training "R". I am trying to make a report that shows employees that are overdue for a training. However, I am having difficulty getting the records to "talk" to each other I.E. If John Doe has initial training, that training was overdue, then has refresher training the initial training now shows as NOT overdue. If employee takes courseIdentifier SAF001 with courseType I then they take courseType R of the same identifier they are up to date and not overdue. Do I need to change my database structure? The code is not live. How do I check if an individual attendee of a TrainingEvent is overdue on training? class Department(models.Model): departmentName = models.CharField(max_length = BIG_MAX_LENGTH) #Engineering departmentCode = models.IntegerField(unique = True) #department code, like 123 departmentDescription = models.CharField(max_length = BIG_MAX_LENGTH, blank = True) #like Engineering Department and Design requiredDepartmentTraining = models.ManyToManyField('TrainingCourse', blank=True, related_name = "trainings") def save(self,*args, **kwargs): print("self: ", self) if not self.id: #new/create super(Department, self).save(*args, **kwargs) super(Department, self).save(*args, **kwargs) def __str__(self): return self.departmentName class TrainingCourse(models.Model): courseName = models.CharField(max_length … -
Unable to get response from Django application when running it in docker
I've created a Django application and I was able to run it locally. But when I try to run it using Docker, I'm not getting response. Inside the Dockerfile, I've exposed the port 8000 using EXPOSE 8000 and built the docker image using docker build -t myimage_name . I've done port mapping for Django application container and my localhost using docker run -it -p 8000:8000 myimage_name The docker container runs successfully and I'm able to see the server starting in the console with no issues. Django version 2.2.7, using settings 'SA.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. But, when I hit the endpoint http://127.0.0.1:8000/ from Postman client, it is returning the below error: This site can’t be reached. 127.0.0.1.8000’s server IP address could not be found. What might be wrong? -
Decoding base64 string return None
I tried to generate uid for a user confirmation email. 'uid':urlsafe_base64_encode(force_bytes(user.pk)), so, it's works nice, it returns something like "Tm9uZQ" Then, when I tried to decode it, using force_text(urlsafe_base64_decode(uidb64)) it return None. The next string urlsafe_base64_decode(uidb64) also, return b'None' I tried to google it, and see different implementations, but copy-paste code not works. I write something like b64_string = uidb64 b64_string += "=" * ((4 - len(b64_string) % 4) % 4) print(b64_string) print(force_text(base64.urlsafe_b64decode(b64_string))) and the result still None: Tm9uZQ== None I don't understand how the default decode doesn't work. -
Django Slug Number Issues
When updating an existing topic in the admin panel, the slug value changes. An example in the first update is: post / testpost. The next update appears as: post / testpost-1 Because the value changes when I return to my site and refresh my page; For this reason, I get a Page not found error (404) How do I fix this problem? models.py class Post(models.Model): slug = models.SlugField(unique=True, editable=False, max_length=130, null=True, blank=True, allow_unicode=True) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while Post.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Post, self).save(*args, **kwargs) views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) def post_update(request, slug): if not request.user.is_superuser: return HttpResponse ("Lütfen giriş yapınız") post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.save() messages.success(request, 'Başarılı bir şekilde güncellediniz.') return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form, } return render(request, 'post/form.html', context) def post_delete(request, slug): if not request.user.is_superuser: raise Http404() post = get_object_or_404(Post, slug=slug) post.delete() return redirect('post:index') url.py urlpatterns = [ path('index/',views.post_index, name='index'), path('create/',views.post_create, name='create'), path('<slug>',views.post_detail, name='detail'), path('<slug>/update/',views.post_update, name='update'), path('<slug>/delete/',views.post_delete, name='delete'), ] -
How to Change Values of Serialized Data in RetrieveUpdateDestroyAPIView
First, I would like to present how my managers, models, serializers and views look like upfront. class PublishedManager(models.Manager): """ Only published articles. `due_date` is past. """ def get_queryset(self): now = timezone.now() return super().get_queryset().filter(due_date__lt=now) class UnpublishedManager(models.Manager): """ Only unpublished articles. `due_date` is future. """ def announced(self): return self.get_queryset().filter(announced=True) def get_queryset(self): now = timezone.now() return super().get_queryset().filter(due_date__gt=now) class Article(models.Model): content = models.TextField() due_date = models.DateTimeField() announced = models.BooleanField() # managers objects = models.Manager() # standard manager published = PublishedManager() unpublished = UnpublishedManager() class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ("content", "due_date") class ArticleRUDView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ArticleSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Article.objects.all() In this code, ArticleRUDView naturally responds with all Article because of Article.objects.all(), yet this is not what I want to do. What I want to do is: If the user is authenticated, then Article.objects.all(). If the user is anonymous, If the entry is published (which means its due_date is less than now), then serialize all fields. If the entry is not published (which means its due_date is greater than now), then still serialize, but content should be null in JSON. Or, in short, how do I alter the serializer's data in a view? Troubleshooting This section might get updated … -
form does not submit, nothing happens when submit button is clicked
My form just does not want to submit. My form looks like this: <form id="courseform" name="courseform" class="fs-form fs-form-full" autocomplete="off" method="POST" action="{% url 'checkout' %}"> {% csrf_token %} <input type="hidden" name="useremail" value="{{useremail}}"> <button id-"fs-submit-button"="" class="fs-submit" type="submit">Continue to payment</button> </form> At the very end of the page I have my javascript: $(".fs-submit").click(function(e) { $('#courseform').submit(); }); In my base project urls.py: from users import views as user_views urlpatterns = [ path('checkout/', user_views.checkout, name='checkout'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Absolutely nothing happens when the button is clicked. No javascript error in the console, nothing. -
Django rest framework show or hide API objects with checkbox in admin
I need to understand how show or hide objects in API serialize by django rest framework. I set a checkbox in my admin model to set active or inactive the object (true or false) class Video(models.Model): ... status = models.BooleanField('Activate video', default=False, help_text='If is checked show the video in the API') ... in my urls.py i set class VideoAPI(serializers.HyperlinkedModelSerializer): class Meta: model = Video fields = [...] class API_Video(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = VideoAPI Now how can i show or hide objects in the API Json with the checkbox in my model? -
Python Many to Many Save() Causes an Operational Error - Django
I have two models using Django, trying to relate Notes and Hashtags. The models are as follows. class Hashtag(models.Model): title = models.CharField(max_length=200, default="") class Note(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.DO_NOTHING) hashtags = models.ManyToManyField(Hashtag) Suppose I create a new note and want to associate it with some hashtags. When I do the following I get an operational error despite saving the items. In views.py: testHashtag = Hashtag(title="hello") testHashtag.save() tweet = Note.objects.create(title="foo", body="bar", author=request.user) tweet.save() tweet.hashtags.add(testHashtag) tweet.save() return redirect("/") The operational error is as follows. Django Version: 2.2.7 Exception Type: OperationalError Exception Value: no such column: core_note_hashtags.note_id I have also made sure all migrations have been performed. Any help would be appreciated. Thanks! -
Django case sensitive search
I have problem. I have model like this: class Teams(models.Model): Name = models.CharField(max_length=200) Short_name = models.CharField(max_length=200, default = "-") When I search team by short name, like "Har": models.Teams.objects.filter(SHort_name = "Har") I get results with "HAR" and "Har". Even if I try like this: models.Teams.objects.filter(SHort_name__exact = "Har"): I get same results ("HAR" and Har") The Short_name column is in utf8mb4_general_ci format, so it should be ok and database connection has this options: 'OPTIONS': {'charset': 'utf8mb4', 'use_unicode': True}, I don't know what is wrong or how to get exact one result. -
UnboundLocalError local variable 'context' referenced before assignment
I am stuck at this error(UnboundLocalError local variable 'context' referenced before assignment) while saving form of almost same type other are working fine but this one is not and showing error def clutchDetail(request): clutchDetail = ClutchDetail.objects.all() context = {'title': 'Clutch Detail', 'active': 'active', 'clutchDetail': clutchDetail, } return render(request, 'breedingRecApp/clutch_detail.html', context) def clutchDetail_add(request): if request.method == "POST": form = ClutchDetail_AddModelForm(request.POST or None) if form.is_valid(): try: form.save() return redirect('breedingRecApp:clutch_detail') except: pass else: form = ClutchDetail_AddModelForm() context = {'title': 'Species Detail Add', 'active': 'active', 'model': ClutchDetail, 'form': form, } return render(request, 'breedingRecApp/clutch_detail_add.html', context) Please help me to fix this error I am newbie to Django. I've an other form code which 100% same that is working fine but this one gives me an error I am stuck at it:( -
I get this error:Could not parse the remainder:
I was using for loop in HTML file and I get this error Could not parse the remainder: '(product)' from 'enumerate(product)' and my code is {%for count, Oneproduct in enumerate(product)%} <div class="col-xs-3 col-sm-3 col-md-3" > <div class="card" style="width: 18rem;"> <img src="(/media/{{product.i.image}})" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{product[count+1].product_name}}</h5> <p class="card-text">{{product[count+1].desc}}</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {%if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item "> {%if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item "> {%endif%} {%endfor%} -
How to have multiple choices in Django model retrieved from a csv file
i am looking a sipmple way to have django model field which generates a form where field choices can be selected from a csv file.. how to do it? As an alternative, how to retrieve data from an external API (instead of downloading it into a csv file?) -
How to pass optional parameters in url, via path () function?
I'm confused about passing optional parameter via url in Django with path() instead of url(). I found that I should use kwargs, so I added it to path: path('all/<str:category>/<int:page_num>/', views.show_all_objects, name="show-all-objects"), to path('all/<str:category>/<int:page_num>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"), Ok but now how to pass additional parameter from template, I tried with: <a href="{% url 'show-all-objects' category='restaurants' page_num=1 city=1 %}" which returns me common error for NoReverseMatch at / So I added it to url: path('all/<str:category>/<int:page_num>/<int:city>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"), But error is the same, I'm pretty sure, that this is not the proper way to do it, but I cannot find info about passing optional parameter via path(), all info is with url() Is it possible ?