Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GenericInlineModelAdmin & through model, "no ForeignKey" error
I have 3 models - Currency, Country and a through model Countries_Currencies: class Currency(models.Model): ..fields.. class Country(models.Model): ..fields.. class Countries_Currencies(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) is_default = models.BooleanField(default=False) I want to let the user adding the Currencies inline while adding Country. This is a part from admin.py: class СurrencyInline(admin.TabularInline): model = Currency extra = 3 class CountryAdmin(admin.ModelAdmin): inlines = [СurrencyInline] But I'm getting an Error "'core.Currency' has no ForeignKey to 'core.Country'." Makes sense :) so what should I enter instead of "model = Currency" in such case? Tried few ways, nothing worked. Thanks! -
Get values between two dates and display in the django template
I have two models, fluxo and relatorio, in the fluxo has a date field, and in the relatorio has two fields, data_inicio and data_fim, I want to make the relatorio display the records in the fluxo between the dates selected in the relatorio, the way I did does not return any record, it follows the code: model relatorio class Relatorio(models.Model): data_inicio = models.DateField(default=timezone.now) data_fim = models.DateField(default=timezone.now) def imprimir(self): return mark_safe("<a target='_blank' href='%s'>Imprimir</a>" % self.get_absolute_url()) imprimir.allow_tags = True def get_absolute_url(self): return reverse('fluxo_list', args=[self.pk, ]) and the method of RelatorioView def get_context_data(self, **kwargs): inicio = self.kwargs.get('data_inicio') fim = self.kwargs.get('data_fim') return dict( super(RelatorioDetail, self).get_context_data(**kwargs), fluxo_list = Fluxo.objects.filter(data__range=[inicio, fim]) ) -
Bootstrap Starter Template Not Working, No Code Showing In Page Source
Following a tutorial I've been creating a website for myself. I have reached the point where I am instructed to copy / paste the bootstrap starter template into my base.html page of my project. I copied / pasted it and attempted to add padding to my "entries" on the page by using but nothing happened. Then when I click on "view page source" in Google Chrome, none of the code that I pasted into Sublime Text shows up at all. I found out that I might need to update an old link, so I went back to the bootstrap website and updated my links to the most recently posted by them, but am experiencing the exact same issue. Thank you. <DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% if title %} <title>Cale Myrick - Projects</title> {% else %} <title>Django Portfolio</title> {% endif %} </head> <body> <div class="container"> {% block content %}{% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
GenericForeignKey Inline in Django admin
I have a multiple product models: class ProductModelA(.. class ProductModelB(.. class ProductModelC(.. Model Order and SubOrder which stores information about quantity. So every Order can have multiple SubOrders which stores tuple product and quantity. class Order(.. class SubOrder(models.Model): order = models.ForeignKey('orders.Order',on_delete=models.CASCADE,related_name='suborders') product = GenericForeignKey() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='suborders') object_id = models.PositiveIntegerField() amount = models.PositiveIntegerField(..) I'm trying to make user friendly admin interface with inline suborder. Choosing from existing products would be enough (alongside with amount field) but can't figure out how to do that. I tried: class SubOrderInline(GenericTabularInline): model = SubOrder @admin.register(Order) class OAdmin(admin.ModelAdmin): inlines = [SubOrderInline] But it doesn't work: I don't want to choose from Order objects, I want to choose from either ProductModelA,ProductModelB or ProductModelC objects. Is there a built in way? -
Why does get_success_url keep directing me to the same page? (Django)
So I am new(ish) to Django, but have been working on a project for a few months. I decided to completely restructure the project to make it take more advantage of Django's Models. Basically what is happening here is I'm populating a form with a model-based view (CreateView) which gives the user a drop down selection of choices for which device they would like to interact with. However, whenever the form submits, it will always redirect me to the same page instead of 'success.html' I have tried making the default template_name 'success.html' just to confirm that it can be displayed and also just tried returning 'success.html' without reverse, which still gives me the same page. Apologies in advance if I've left out something really small, I've been looking all over the place but haven't been lucky so far. views.py class DeviceChoiceView(CreateView): model = DeviceChoice form_class = DeviceChoiceForm success_url = 'success.html' template_name = 'index.html' def form_valid(self,form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('success.html') urls.py from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('port_reset/', include('port_reset.urls')), ] port_reset/urls.py from django.urls import path from port_reset.views import DeviceChoiceView from . import views urlpatterns = [ path('', DeviceChoiceView.as_view(), … -
Django - Accepting full sentence in query parameters
I'm putting together a small API that just converts the message coming in to Spongebob mockcase. I've got everything rolling, but coming back I'm realizing I've been testing with a single value & thus just noticed the following URL entry will not be able to accept spaces/%20. url(r'^mock/(?P<message>\w+)/$',mock, name='mock'), I've looked all over, but not sure how to phrase what I'm looking for appropriately to find anything useful. What would I be looking for to accept a full sentence. Worth noting this will be coming from a chat message, therefore, it will be sent as is, not percent encoded. -
Django: is there any way to get templates to identify themselves
When you are using template inheritance with Django, and have to view a web page source, it would be nice if you could immediately see what file contains the text that you are staring at. Example: I have a template file {% block extrascripts %} {{ block.super }} /* this is ocustomers/customer_form2.html */ // a little bit of JS ... {% endblock extrascripts %} The comment identifies the file that the script is defined by, but it's all too easy to forget to edit it when the file is renamed. Is there any not-too-difficult way I can do something like /* contributed by {{this_file}} */ NB, {{this_file}} is not necessarily the file which the template_name referred to by the view resolves to. It may be in a {{block.super}} thereof. -
Django - page not found
I'm trying to run this library, but each time i get this error: Using the URLconf defined in django_google_authenticator.urls, Django tried these URL patterns, in this order: ^admin/login/$ ^admin/ The empty path didn't match any of these. I don't know what's wrong, can anyone help me? -
Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<blog_id>\\d+)/$']
the blog_post.html is working properly until the "edit post" link is passed , generating the error above , on the other hand it works if i removed the "blog_id" argument from the url pattern and "blog.id" from the "edit post" link ,but accordingly another error occurs when i click the "edit post" link and open the edit_post.html page it demands the missing (edit_post) argument , if i re-pass the argument again then the url patterns are not matching. `from django.conf.urls import url from . import views app_name = 'blogs' urlpatterns = [ #index url(r'^$',views.index,name='index'), #make page for blogposts url(r'^blogposts/$',views.blogposts,name='blog_post'), #page for making a new post url(r'^new_post/$',views.make_post,name='add_post'), #page for editting post url(r'^edit_post//(?P<blog_id>\d+)$', views.edit_post, name = 'edit_post'), ]` -
DRF - Serialize multiple models
please help! How can I can get this JSON { "value": 9998, "startDate": "01-03-2019T06:59", "endDate": "31-03-2019T23:59", "days": 11111111, "name": "Juices", "Stores": [ 921, 923 ] } Because , with my code I only retrive this JSON [ { "AS400Promotion": 9998, "days": 11111111, "name": "Prueba", "promotionType": 999 } ] How can I do it? I read the drf documentation but it didn't work, what I'm doing wrong? here is my code my models.py class Store(models.Model): modular = models.ForeignKey(Modular, on_delete=models.CASCADE) store_nbr = models.IntegerField(primary_key=True, help_text="Numero Tienda") name = models.CharField(max_length=255, help_text="Nombre de sucursal") def __str__(self): return self.name class Campain(models.Model): AS400Promotion = models.IntegerField(default=9998) days = models.IntegerField(default=1111111) name = models.CharField(max_length=50) store = models.ForeignKey(Store, related_name='stores', on_delete=models.CASCADE) promotionType = models.IntegerField(default=99) here are my serializer.py class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = ('modular', 'store_nbr', 'name', 'address', 'commune', 'region', 'open_status', 'manager_name') class CampaignSerializer(serializers.ModelSerializer): stores = StoreSerializer(many=True, read_only=True) class Meta: model = Campaign fields = ('value1', 'days', 'name', 'stores', 'promotionType') my viewsets.py class CampaignViewSet(viewsets.ModelViewSet): queryset = Campaign.objects.all() serializer_class = CampaignSerializer and my routes.py router.register(r'campaign', CampaignViewSet) -
Django + TradingView integration
i need help on tradingview integration with django (2.5.1 and python 3.6). Is there anyone here who's already done it? I have the following error: PAGE NOT FOUND http://localhost:8000/js/charting_library/static/en-tv-chart.aa0061904b783ada8056.html Here is my app structure: - project_name - app_name - locale - media - static - css - images - js market.js wallet.js - charting_library - datafeeds - template apps.py backend.py cognito.py custom_storage.py tests.py urls.py views.py - project_name __init__.py settings.py urls.py wsgi.py .gitignore db.sqlite3 manage.py requirements.txt charting_library and datafeeds are provided by tradingview. Here is what's inside charting_library: - charting_library - static - bundles - fonts - images -lib ar-tv-chart.aa...........8056.html ... ... ... en-tv-chart.aa...........8056.html # this is the file not found ... ... ... zh_TW-tv-chart.aa...........8056.html charting_library.min.d.ts charting_library.min.js datafeed-api.d.ts test.js And inside datafeeds folder: - datafeeds - udf - dist bundle.js polyfills.js - lib data-pulse-provider.js ... ... ... udf-compatible-datafeed-base.js udf-compatible-datafeed.js .npmrc package.json README.md rollup.config.js tsconfig.json README.md please don't mind the typescript files, i'm using javascript. Finally, this is a part of the init script also provided by tradingview: var widget = window.tvWidget = new TradingView.widget({ symbol: 'AAPL', // BEWARE: no trailing slash is expected in feed URL // tslint:disable-next-line:no-any datafeed: new window.Datafeeds.UDFCompatibleDatafeed('https://demo_feed.tradingview.com'), interval: 'D', container_id: 'tv_chart_container', library_path: '/js/charting_library/', # i think this … -
TypeError build_attrs() got an unexpected keyword argument 'id' in django
In general, what can cause a build_attrs() got an unexpected keyword argument 'id' error? In particular after a migration of my project from one server to another I face this error.All templates rendered well apart from one. I do not know where to search in order to fix it. Could it be an error raised from the template? My view @method_decorator(user_access_to_log, name='dispatch') class StatisticsView(LoginRequiredMixin,ListView, FormMixin): model = RequestRequest login_url = '/login/' template_name = 'statistics.html' form_class = DateMonthForm def get_context_data(self, **kwargs): context = super(StatisticsView, self).get_context_data(**kwargs) #logins = AuditEntry.objects.exclude(username='neuro') count = AuditEntry.objects.filter(action='user_logged_in').exclude(username='demo').exclude(username='neuro').values('username').annotate(total=Count('username')).order_by('total') #print(count) usernames = [] counts = [] for c in count: usernames.append(c['username'].encode('ascii','ignore')) counts.append(c['total']) print(usernames) requests = RequestRequest.objects.filter(referer__icontains='/shops/rest_new/',response=200,path='/rest/pharmakeia/').exclude(user=None).exclude(user__username='demo').exclude(user__username='neuro').values('user__username').annotate(total=Count('user__username')).order_by('total') print(requests) usernames_r = [] counts_r = [] for r in requests: usernames_r.append(r['user__username'].encode('ascii','ignore')) counts_r.append(r['total']) if self.request.POST: self.date_year = self.request.POST['date_year'] self.date_month = self.request.POST['date_month'] monthform = DateMonthForm(self.request.POST or None) context ['form'] = monthform context['counts_r'] = counts_r context['usernames_r'] = mark_safe(usernames_r) context['counts'] = counts context['usernames'] = mark_safe(usernames) #context['logins'] = logins return context My Traceback TypeError at /logging/ build_attrs() got an unexpected keyword argument 'id' Request Method: GET Request URL: .../logging/ Django Version: 1.11.16 Exception Type: TypeError Exception Value: build_attrs() got an unexpected keyword argument 'id' Exception Location: widgets.py in render, line 77 Python Executable: /usr/bin/python Python Version: 2.7.12 … -
Troubles understanding a django 2fa authentication library
I'm trying to add 2fa to my Django project, so i decided to adopt this library. To understand how it works, i'm following their example. My idea would be to "merge" my current work, so that i can have both what i already have and what the example gives. Now i'm trying to edit the example's login form, but i can't find it. Normally, in django, i expect a login form to be defined in a views.py file, and it looks something like that: if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: messages.error(request, "Invalid username or password") But i can't find anything that looks like this on the example folder. Can anyone give me some help? -
How to compare counts in django ORM?
I have model like this: class A(models.Model): done = models.Boolean() And want to check if all done are True: A.objects.count() == A.objects.filter(done=True).count() But how to do the same thing inside DB in one query? ??? A.objects.annotate(Count('done??')).aggregate(??) ??? -
How do I return my posts by section according to the id of my foreign key?
I'm new in Django Framework and I need help! I have a model in which I register sections and have another model where I have registered publications. Each publication has a foreign key to the registered sections. In my views.py, I need to return all posts that pertain to the section I chose in my template, but my views.py is returned all the id's. How can I fix this? models.py class Section(models.Model): section_name = models.CharField(verbose_name='Nome da coluna', max_length=50, blank=False, null=False, unique=True) slug = models.SlugField() class Meta: verbose_name='Coluna' verbose_name_plural='Colunas' def __str__(self): return self.section_name # case insensitive def clean(self): self.section_name = self.section_name.capitalize() def save(self, *args, **kwargs): self.slug = slugify(self.section_name) super(Section, self).save(*args, **kwargs) models.py class Publication(models.Model): section = models.ForeignKey(Section, verbose_name='Coluna', blank=False, null=False, on_delete=models.CASCADE) date = models.DateField(verbose_name='Data da publicação', blank=False, null=False) spotlight = models.BooleanField(verbose_name='Destaque', default=False) authors = models.CharField(verbose_name='Autor(es)', max_length=150, blank=False, null=False) title = models.CharField(verbose_name='Título da publicação', max_length=256, blank=False, null=False, unique=True) slug = models.SlugField() subtitle = models.CharField(verbose_name='Subtítulo da publicação', max_length=300, blank=True, null=True) cover_publication = models.ImageField(verbose_name='Capa da publicação', upload_to='media/cover_publication', blank=True, null=True) link_video = EmbedVideoField(verbose_name='Link do vídeo', null=True, blank=True) publish = models.BooleanField(verbose_name='Publicar', default=True) class Meta: verbose_name='Publicação' verbose_name_plural='Publicações' ordering = ['-date'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Publication, self).save(*args, **kwargs) views.py class SecPubListView(ListView): … -
Django appends white space to views
So I have recently started looking into the Django framework, but it appends some white space in the top of my views even though the layout.html and layout.css is the same for each view. layout.html, with html tags excluded <head> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'layout.css' %}" /> <link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' /> </head> <body> <div class="content"> <div class="navbar"> <a href="/" class="navbar-brand">Homepage.</a> <a href="{% url 'home:index' %}" class="navbar-item">Home</a> <a href="{% url 'projects:index' %}" class="navbar-item">Projects</a> <a href="{% url 'home:about' %}" class="navbar-item">About</a> </div> <div class="text"> {{ greetings }} </div> </div> </body> This is my views def index(request): return render( request, 'home/index.html', { 'greetings': "Welcome to my site!", } ) def about(request): return render( request, 'home/about.html', { 'greetings': "Welcome to my site!", } ) about page pushed down As seen in the image the view for the about.html page is push down, and I really cannot figure out why. Anyone who can help me out? -
Dynamic drop down in Django
I'm Trying to load a list of folders within a local system in drop down menu of the django form using dynamic path(have to take path dynamically) . please give me an idea to do that. thanks in advance -
Django: saving username by default in a form
I´m trying to build a task manager. I should have a field for the creator user and another for the destination user. I realized that I can´t define 2 foreign key fields pointing to the same users list, so I have the destination user field as a foreign for the creator user to choose and then I´m trying to set the active user name as the creator in views. The form stores all the collected data but not the one set in the view. I get no error, but the value is not saved. The model class Tareas(models.Model): creador = models.CharField(max_length=100, help_text="Creador", blank=True, null=True) destinatario = models.ForeignKey(User, help_text="Estatus del contenido", blank=True, null=True, on_delete=models.CASCADE) titulo = models.CharField(max_length=100, help_text="Título de la tarea", blank=True, null=True) tarea = models.TextField(max_length=500, help_text="Explicación de la tarea", blank=True, null=True) resuelto = models.BooleanField(default=True) fecha_creacion = models.DateField(help_text="Fecha de creación", default=datetime.date.today, blank=True, null=True) fecha_limite = models.DateField(help_text="Fecha límite", default=datetime.date.today, blank=True, null=True) fecha_resuelto = models.DateField(help_text="Fecha de resolución", default=datetime.date.today, blank=True, null=True) def __str__(self): return str(self.titulo) The form class FormularioTareas(forms.ModelForm): class Meta: model = Tareas widgets = {'fecha_limite': forms.DateInput(attrs={'class': 'datepicker'})} fields = ["destinatario", "titulo", "tarea", "resuelto", "fecha_limite", "creador", "fecha_creacion"] The view @login_required def TareasView(request): tareas_form = FormularioTareas(request.POST) tareas = Tareas.objects.all() tareas = tareas.order_by("-fecha_creacion") if request.method … -
events for Django Admin built-in calendar
In Django Admin, the DateField with the built-in Today and Calendar anchors..how do I capture click/change events for those with jQuery? I currently run event handlers on the textbox element which the date anchors are connected to. I can handle events with manipulation directly on the textbox with this: $(document).on("input","#id_textbox",function() { $(this).processConstructionDates(); }); But if a date is input by clicking on the Today or Calendar, no input event fires on the textbox (#id_textbox). Django's automatic HTML for the Today and Calendar anchors looks like this: <span class="datetimeshortcuts"> <a href="#">Today</a> <a href="#" id="calendarlink1"><span class="date-icon" title="Choose a Date"></a> The Today anchor has no name to reference in JQuery. So which name can I reference for it? And, which event fires for Today? Click? And which event can I bind to for calendarlink1 when a date is selected? -
Django rest framework keep user logged in
I have an APi that supports log-in functionality and whenever i switch page to index page, user is not logged in anymore at this point i have no idea what am i doing wrong tbh. this is my views for logging in @csrf_exempt @api_view(["POST", "GET"]) @permission_classes((AllowAny,)) def login(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) request.session.save() return Response({'Success': 'Logged in'}, status=HTTP_200_OK) and this is a simple test view for index page, my session.items() is blank and request.user outputs AnonymousUser def test_view(request): print(request.session.items()) print(request.user) return HttpResponse(request.COOKIES.keys()) and in my settings i have 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), -
Why Django Queryset variable will lead to extra query?
I am using DRF for a project and I use a Serializer to convert a list of object to data in Json. I don't have an issue with N+1 call. However it seems CurrencySerializer will query my database although. Passing currencies in parameters leads to another query. Can someone explain why the variable itself leads to an extra query ? The code is as follow: Viewset : class CurrencyInUseViewSet(APIView): def get(self, request): currencies = Currency.objects.all().order_by('iso_code') res = CurrencySerializer(currencies, many=True).data return Response(res) Serializer: class CurrencySerializer(serializers.ModelSerializer): class Meta: model = Currency fields = '__all__' Model: class Currency(models.Model): name = models.CharField(max_length=64, null=False, blank=False, unique=True) is_active = models.BooleanField(default=True) iso_code = models.CharField(max_length=64, null=False, blank=False, unique=True) -
Django crontab logs :ModuleNotFoundError: No module named 'sslserver'
I have a django crontab running at the server, if I see it's log it gives me the following error. File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sslserver' How ever if I runt the cron manually by running python manage.py crontab run it runs fine. Also I tried running pip install -r requirements.txt, it says dependency already satisfied. Any idea how can I get past this? -
How to auto update chocie fields in django?
hello i have categories and products. i use django-mptt library for only showing descendants categories for products. i have written custom subcategories field to only show descendants category. After update Categories ,the subcategories does not update in products corresponding field. and i should restart the server. how can i do this without restarting the server from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: level_attr = 'mptt_level' order_insertion_by = ['name'] def __str__(self): return self.name class Product(models.Model): nodes = Genre.objects.all() CHOICE_SUBCATEGORIES = [ ] for node in nodes: if node.is_leaf_node(): node.get_descendants(include_self=False) print(node.get_descendants(include_self=False)) CHOICE_SUBCATEGORIES.append((node.id, node.name)) name = models.CharField(max_length=128) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True, blank=True, default=None) subcategories = models.CharField(max_length=128, choices=CHOICE_SUBCATEGORIES, default=None, null=True, blank=True) def __str__(self): return self.name -
Django - get Month and Year from (Datepicker filter data)
This is forms.py class dateFilter(forms.Form): date = forms.DateField(input_formats=['%Y-%M-%D'],label='',required=False, widget=forms.DateInput(attrs={ "placeholder": " Select a date", "class": "dateClass", "id": "datepicker", "name": "dateFilter"})) This is my views.py def bsoCharts(request): #-----------Filter Section------------------------------------------ dateFilter = forms.dateFilter() FilteredDate = request.POST.get('date') return render(request, 'BSO/BSO_dashboard2.html', 'dateFilter':dateFilter ) This is my template where I render the form: <div class="container"> <div class="row"> <div class="col-12 col-sm-12 col-md-6 col-lg-4"> <form action="{% url 'BSO:BSO_Dashboard' %}" method="post" autocomplete="off"> {% csrf_token %} {{dateFilter}} </form> </div> </div> </div> This is my JQuery for the datepicker: <script> $("#datepicker").datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'yy-m-d', onSelect: function(dateText, inst) { $(this).parents("form").submit(); } }); This is the photo image of the datepicker, and the value after selecting a date: enter image description here After getting the results back in my views.py using this get method: FilteredDate = request.POST.get('date') i'd like to grab only the month and the year using the below method so I can use it as a filter(contains) to another queryset: FilteredDate.month However, it's giving me this error: Django Version: 2.1.5 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'month' Please Help! -
Breaking or stopping a forloop.counter in django
I applied a forloop.counter to label each object numerically in a for loop But I want it to number only the first fifty(50) objects and ignore the rest. Here is my code {% load thumbnail %} {% for image in most_viewed %} <div class="image"> <a href="{{ image.get_absolute_url }}"> {% thumbnail image.image "200x200" crop="10%" as im %} <span class="forloop">**{{ forloop.counter }}**</span> <a href="{{ image.get_absolute_url }}"> <img src="{{ im.url }}"> </a> {% endthumbnail %} </div> {% endfor %} Basically, obects 51 and above should be without numbers