Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to initialize the hidden fields in django
This is my view: def my_view(request): if request.method == 'GET': form = MyForm(initial={'user': "my_user"}) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): print("form is valid") else: form = MyForm() return render(request, 'my_template.html', {'form': form}) And this is the form class MyForm(forms.Form): my_field = forms.CharField(max_length=100) user = forms.CharField(widget=forms.HiddenInput()) def clean(self): cleaned_data = super(MyForm, self).clean() my_field = cleaned_data.get('my_field') if not my_field: raise forms.ValidationError('error') Nothing is printed on the console (print("form is valid")), so the form is not valid, and this problem comes from the hidden field. When I work without the hidden fields, the form is valid What's wrong with my code ? How to initialize the values of hidden fields from the view function (or another way to do it without including it in the HTML) ? -
Conditionally display with Crispy Forms - error 'tuple' object has no attribute 'get'
I am trying to follow solution for this question: Conditionally display a Fieldset with Crispy Forms. However, I am not able to completed it due to error: Request Method: GET Request URL: http://127.0.0.1:8000/project/customer/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' model.py: class Project(models.Model): project_name = models.CharField(max_length=50, primary_key=True) # who owns the project? owner = models.ForeignKey(User, on_delete=models.PROTECT) created_date = models.DateTimeField(auto_now=False, auto_now_add=True) is_active = models.BooleanField(default=True) ## when on call starts 5 pm? on_call_begings = models.TimeField(auto_now=False, auto_now_add=False, default=datetime.time(17, 00)) ## when on call ends 9 am? on_call_ends = models.TimeField(auto_now=False, auto_now_add=False, default=datetime.time(9, 00)) country = CountryField() follow_holidays = models.BooleanField(default=True) slug = models.SlugField() class Meta: verbose_name = "Project" verbose_name_plural = "Projects" def __str__(self): return self.project_name def get_absolute_url(self): return reverse("Project_detail", kwargs={"slug": self.slug}) Forms.py from django import forms from core.models import Project from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Field, Layout class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ("project_name", "is_active", "on_call_ends", "on_call_begings", 'country', 'follow_holidays') def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(args, kwargs) self.username = kwargs.pop('user', None) self.helper = FormHelper(self) self.helper.attrs = {'novalidate': ''} self.helper.layout = Layout( Fieldset("project_name", "is_active", "on_call_ends", "on_call_begings", 'country', 'follow_holidays') ) if self.username and self.username.is_staff: self.helper.layout.append(Fieldset( 'owner', ) ) The problem is there. When I remove … -
Having troubles in usage custom font in template on Heroku
I have a problem with using custom font on Heroku. In order to show Russian text correctly on generated pdf pages I use following custom font in my html: <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Boat pdf</title> <style type="text/css"> @font-face { font-family: Palatino Linotype; src: url({% static "fonts/Palatino.ttf" %}); } body { font-family: Palatino Linotype, Arial, sans-serif; color: #333333; } </style> </head> It works fine locally but after migration to Heroku whenever I am trying to generate pdf file based on the html I get an exception: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name 2019-06-26T09:52:03.873127+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2019-06-26T09:52:03.873128+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'fonts/Palatino.ttf' This is the only error I get related to staticfiles. All other static works fine. I have tried to manually run collectstatic one more time and even placed this font to staticfiles folder manually – no success. In production static assets are served by Whitenoize. Development setting related to static are: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', STATIC_ROOT = os.path.join(BASE_DIR, "static") # new STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' production settings are: STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Question is how to serve this font on … -
How to adjust the zoom of website at different browser at different screen size?
I have deployed a website http://www.muskan-group.com/ it's zoom is fine at screen resolution 1920x1080. I want to zoom 80% at screen resolution 1366x768. I tried to set @media only screen and (min-width: 768px) { zoom: 80%; } It works fine in chrome but not working properly in internet explorer and microsoft edge. I have used meta tag for viewport. <meta name="viewport" content="width=device-width, initial-scale=0.6, maximum-scale=1, user-scalable=0"> I expect the output that at screen resolution 1366x768 the zoom of page is set to 80%. And it should be compatible with all browser. -
Access related fields through inline_formset
I am trying to view (not edit) related fields in an inline formset. In this case I want to display the item cost in the quantity formset. models.py class Item(models.Model): name = models.CharField(max_length=40) notes = models.CharField(max_length=200, blank=True) cost = models.DecimalField(default=0.00, max_digits=8, decimal_places=2, blank=True) class Quantity(models.Model): quantity = models.IntegerField(default=0) item = models.ForeignKey(Item, on_delete=models.CASCADE) forms.py class QuantityForm(ModelForm): def __init__(self, *args, **kwargs): super(QuantityForm, self).__init__(*args, **kwargs) class Meta: model = Quantity fields = ['id','item', 'quantity'] views.py QuantityFormSet = inlineformset_factory(Option, Quantity, form=QuantityForm, formset=QuantityInlineFormSet, extra=1) quantityForm = QuantityFormSet(instance=option) I imagine I have to do something like this. for form in quantityForm.forms: form.item_cost = form.fields['item'].selected.cost But I'm a little stuck. Surely doing this in forms.py is a better place? -
relation " " does not exist
I am creating a project in django using postgresql database. When I run my server the page returns the error relation "backtest_trade" does not exist LINE 1: INSERT INTO "backtest_trade" ("pos", "neg", "profit", "trans... when i try to save my model in the database using back.save(), where back is a variable of the model. I have registered the model in models.py of my app. I understand that there is no table being created in the database but my understanding is that admin.register should do it. I tried looking up but none of the questions asked was able to help me. from django.contrib import admin from django.db import models from django.contrib.postgres.fields import ArrayField # Create your models here. class trade(models.Model): pos = models.IntegerField(default = 0) neg = models.IntegerField(default = 0) profit = models.IntegerField(default = 0) transaction = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default= 0), default = list) investment = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default = 0), default = list) sell = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9, default = 0), default = list) entry_date = ArrayField(models.CharField(max_length = 20, default=''), default = list ) exit_date = ArrayField(models.CharField(max_length = 20, default = ''),default = list) name = models.CharField(max_length = 100, default = "hello") admin.site.register(trade) -
Django : Displaying ManyToManyField in admin page as a Table
I have the following two models. class Question(models.Model): id = models.AutoField(primary_key=True) question_body = models.TextField(blank=True) question_response = models.TextField(blank=True) def __str__(self): return self.question_body class SIGRound(models.Model): sig = models.CharField(max_length=9, choices=SIG_CHOICES) round_number = models.IntegerField(default=1) round_description = models.CharField(max_length=500) questions = models.ManyToManyField(Question) I want to use the SIGRound from the admin page and since it is a many to many field, many answers on StackOverflow suggested to use filter_horizontal or inline filter_horizontal does not give me what I want and with inline it looks like this: But I want to display this field as a table, similar to list_display in the normal admin page, how would I go about doing this? -
Connect mysql database with django
I am a begginer in django, i try to connect mysql database with django but when i write 'python manage.py migrate' in cmd i see this error: mysqlclient 1.3.13 or newer is required yo have 0.9.3 so i decide to upgrade mysql client using this command:pip install mysqlclient --upgrade and i get this output: [https://i.stack.imgur.com/bq7Jn.jpg][1] [https://i.stack.imgur.com/nYGSQ.jpg][2] [https://i.stack.imgur.com/u8wzN.jpg][3] How to fix it? -
Add multiple (but not all) tables to PostgreSQL publication if not added
I'm trying to set up publication on PostgreSQL 10 database for logical replication. The database is used for Django website and all tables are currently in one schema - public. I plan to keep database structure updated via Django migrations, so I need to exclude some tables from PostgreSQL publication, namely all that start with django. I can receive an entire list of tables that I need to replicate using query SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname='public' and tablename not like 'django%'; Tables are added to the publication using query ALTER PUBLICATION my_publication ADD TABLE table0, table1; How can I pipe output of my SELECT query to the above ALTER PUBLICATION query? It would also be great if tables that have already been added were skipped instead of breaking execution of the entire ALTER PUBLICATION query. At the moment I think I will have to use PL/pgSQL - SQL Procedural Language. But maybe there is a better/simpler way to edit publication with only queries? -
Datatable recommandation for django
I want to load millions of data from Django with search bars on each column to search all the database quickly on server-side. However, there is no datatable example for django with server-side and column search bar. I tried django-datatable-view and I can load the dataset with server-side. But I could not implement the column searchbar on the whole dataset. -
Django Rest Framework save multipart/form-data
I have the following model: class Exercise(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='roms') # ... other fields recording = models.ManyToManyField(Recording) The Recording model contains, among other fields, a field called zip_file, which is a FileField. Since this is the first time I'm using DRF and my work is mostly frontend, unrelated to Django in general, I'm having difficulties understanding how to save an instance of a model like this. This is the ExerciseSerializer: class ExerciseSerializer(serializers.ModelSerializer): recording = RecordingSerializer() class Meta: model = Exercise fields = ('duration', 'recording', ...) This is the Recording model: class Recording(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recordings') sensors = models.ManyToManyField(Sensor) category = models.CharField( max_length=4, choices=( ... ), default=(...) data = JSONField(null=True, blank=True) zip_file = models.FileField( upload_to=upload_location, storage=storage, null=True) and this is the RecordingSerializer: class RecordingSerializer(serializers.ModelSerializer): sensors = SensorSerializer(many=True) class Meta: model = Recording fields = ('sensors', 'category', 'data', 'zip_file') If I understood right, I need to update this RecordingSerializer in order to save the zip_file field properly. Is that correct? Or I need to change something in the ExerciseSerializer? -
Adding JavaScript variable to Django static url
I am attempting to add a custom Javascript variable to my Django static url. Unfortunately, the below code is failing. $(document).ready(function() { var randomNum = Math.floor((Math.random() * 12) + 1) var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg %}" document.getElementById("headerImage").style.backgroundImage = url(text) }); I receive the error: -- Error during template rendering Could not parse the remainder: ''5LW/images/slider/"' from ''5LW/images/slider/"' var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg %}" -- How would I go about fixing this? -
'NoneType' object has no attribute 'email'
I am using rest-social-auth for my project and it returns jwt token. Now if I am going to create a user profile in Django admin everything is ok I select author fill some fields etc and profile is ready and it returns user email which was taken from social network. But in Postman when I test my api it works with jwt token auth but I do not know which user has create the profile. models.py class Profile(TimeModel): user = models.OneToOneField('user_accounts.CustomUser', related_name='profiles', null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image = models.ImageField(upload_to='profile_images', null=True) def __str__(self): return self.user.email if I change __str__ method to return first_name it works but I do not know which user did it. But It returns email instead it gives me a error in admin like 'NoneType' object has no attribute 'email' serializers.py looks like this class ProfileSerializer(serializers.ModelSerializer): birthdate = serializers.DateTimeField(format='%Y-%m-%d') class Meta: model = Profile fields = ['first_name', 'last_name', 'birthdate', 'gender', 'image'] How can I solve this issue? pls any help would be appreciated -
Adding constraint on Django Models based on values of another field
I have a simple model with 1 primary key and 3 fields (simplified): passing score max score max attempt This model is created by inheriting from django.db.models. This is the minimal reproducible code: class QuestionSet(models.Model): passingscore = models.PositiveSmallIntegerField("passing score") maxscore = models.PositiveSmallIntegerField("passing score") maxattempt = models.PositiveSmallIntegerField("passing score") I would like to add a constraint such that passingscore should never be greater than maxscore in the database. I've used constraint that span across multiple fields such as unique_together, as per this thread on StackOverflow. But clearly this is a different use-case. I've also briefly considered to add constraint directly writing PostgreSQL code: ALTER TABLE tableB ADD CONSTRAINT score_policy_1 CHECK (maxscore >= passingscore) But this defeats the purpose of using an ORM and violate the "loosely coupled" philosophy, making it hard to migrate between different database backends. If this is at all possible, please point me to a more idiomatic way of writing this constraint in Django. -
How to populate a ManyToMany Field in Django using a .csv file?
I have 2 models Influencer and Category. Influencer has a many to many relationship with Category.The models look like this: class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name and class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=100) username = models.CharField('Username',max_length=100,unique=True) photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/',blank=True) location_city = models.CharField('Location City',max_length=100,null=True,blank=True) categories = models.ManyToManyField(Category) I have written a python script that parses a csv file and sends the data to a PostgreSQL database. In the csv file the column categories is present as an array, like the one given below ['Food', 'Bar', 'Bar', 'Student', 'Student', 'makeup', 'makeup', 'India', 'India'] When I print the type of column categories in python it shows it as a string. The function which I wrote to parse and send data to database is as follows.I have excluded the categories option from the function for now. ef write_to_db(file): with open(str(file),encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) next(csvreader,None) for row in csvreader: try: if not Influencer.objects.filter(username = row[1]).exists() and check_email(row[2]): _,created = Influencer.objects.get_or_create( full_name = row[0], username = row[1], email_id = clean_email(row[2]), external_url = row[8], ) except Exception as e: print(e) How should I write the code so that I can insert the categories in the many to many field with … -
NoReverseMatch for Class-based delete view
I am having trouble trying to implement a class-based delete view as I have been having a NoReverseMatch error and I am unsure what is causing the problem. This is my urls.py: path('post/lesson_delete/<int:pk>', LessonDeleteView.as_view(), name='lesson_delete'), This is my views.py for my DeleteView: class LessonDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Lesson success_url = '../' def test_func(self): lesson = self.get_object() # if self.post.request.user == lesson.post.author: return True # return False These are my Models: class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) def delete(self, *args, **kwargs): self.file.delete() self.title.delete() super().delete(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) This is my html template to render the delete view: {% extends "store/base.html" %} {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% … -
How to redirect to another page with context, after posting a form?
After posting my form, I want to redirect to another page and send some data to that page with context. I need to send a string and boolean value to the other page, depending if the post to the database was successful or not. With the view I have, the admin.html is rendered but the url is not updated (it still shows the form page). How can I achieve this I've tried to play around with the redirect. return redirect(reverse('app:view', kwargs={ 'bar': FooBar })) But no luck yet. def report_view(request): if request.method == 'POST': form = ReportForm(request.POST) if form.is_valid(): report_title = form.cleaned_data['report_title'] report_link = form.cleaned_data['report_link'] new_report = Report(title = report_title, link = report_link) new_report.save() return render(request, 'dashboard/admin.html', {'title': Admin Page, 'added':True}) -
I have a project in Python and i have to make a U.I (HTML PAGE) to present it .Please tell me how to do same
I have created a project of machine learning using python. The project is about text summarization using python libraries. Now our seniors have asked us to present it using an interface. I tried using django but failed. Need immediate assistance with the same ! -
Django test how to check if function was Not called
I want to write a test in order to check that a specific function was not called. Below is a pseudo example of my code: Code TestFunctionA(): if a > b: TestFunctionB() In order to check if it is called i do the following which is working with mock.patch('TestFunctionB') as mock_TestFunctionB: TestFunctionA() mock_TestFunctionB.assert_called_once_with() If i want to check if the function TestFunctionB was not called i tried the following but is not working with mock.patch('TestFunctionB') as mock_TestFunctionB: TestFunctionA() assert not mock_TestFunctionB.assert_called_once_with() -
NameError in Django Rest Framework, it's showing my model name is not defined
I am trying to serialize the data from the database so that I can access the data on the client side apps. I am new to the Django for just 1 month. Kindly help me out. What is the correct method to execute this problem? I just want it to be generated in the data in JASON format. And it's giving me an error. What am I doing wrong here? Is this not the way? I have tried this where Jobcard is my model name from jobcard_api.models import Jobcard ``` then this gives a new error of NameError of "name 'JobcardSerializer' is not defined" This is my models.py inside an app and the app is inside a project, there are three apps and all of them giving the same kind of error with different names ``` from django.db import models class Jobcard(models.Model): """Database model for the jobcard""" id = models.AutoField(primary_key=True) jobcard_number = models.CharField(max_length=30, unique=True, blank=False), ..., observation = models.TextField(blank=True) def get_jobcard_number(self): """Retrieve jobcard number""" return self.equipment_name ``` This is my serializers.py inside an app called jobcard_api. ``` from rest_framework import serializers from jobcard_api import models class JobcardSerializer(serializers.ModelSerializer): """Serializer for the jobcard object""" class Meta: model = models.Jobcard fields = ('id', … -
Input text box : unable to retrieve the data (Django)
I'm developing a web application with Django and I have a little problem I couldn't solve. I'm using input text box with a default value so the user knows what is currently in the database but they can change it by typing text and send the new information. Here is my html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> Annotate: {{video.title}}</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css"> {% load static %} <script type="text/javascript" src='{% static "annotationTool/jsScript/garnmentAnnotation.js" %}?v=00003'></script> </head> <body> <h1>{{video.title}}</h1> <div id = {{mannequin.mannequinID}} class = "mannequin"> <img class = "mannequinImg" src="/media/{{mannequin.frame}}"/> </div> <nav> <ul> {% for garnment in garnments %} <li><a href="#{{ forloop.counter }}">{{garnment.type}}</a></li> {% endfor %} </ul> </nav> <div hidden class="garnments"> {% for garnment in garnments %} <div class="garnment" id="garnment_{{ forloop.counter }}"> <img class = "garnmentImg" src="/media/{{garnment.frame}}"/> <form> <p>Model name:</p><input type="text" id="garnment_{{ forloop.counter }}_modelName" name="modelInput" value="{{garnment.mannequin}}"><br> <p>Brand:</p><input type="text" id="garnment_{{ forloop.counter }}_brand" name="brandInput" value="{{garnment.brand}}"><br> <p>Name of the product:</p><input type="text" id="garnment_{{ forloop.counter }}_productName" name="productNameInput" value="{{garnment.productName}}"><br> <p>Price:</p><input type="text" id="garnment_{{ forloop.counter }}_price" name="priceInput" value="{{garnment.price}}"><br> <p>URL:</p><input type="text" id="garnment_{{ forloop.counter }}_url" name="urlInput" value="{{garnment.url}}"><br> <input type="button" value="Validate" onclick="sendNewInfo({{mannequin.mannequinID}},{{garnment.pk}},{{ forloop.counter }})"> </form> </div> {% endfor %} </div> <div class="currentGarnment"> </div> </body> </html> So I want to retrieve like what the user putted in this box: … -
How to display all months dynamically in django template
Here i am trying to display the line chart of students added in every month of the particular year.But i got some little problem here.The problem is in the script.For example i only have students added in june(1 students) and july(6 students) and in other month the number of student is zero.But while displaying june and july students number is in jan and feb month.I think the one solution is making the labels in the script dynamic like this {{student.month|date:'F'}}, but i want to add all 12 months in the labels even if there is not any students in some month.How can i do it ? views.py def home(request): students_according_to_month = Student.objects.annotate(month=TruncMonth(F('joined_date'))).values('month') .annotate(total=Count('pk')) template <script> /* LINE CHART */ var ctx3 = document.getElementById('chartLine1'); var myChart3 = new Chart(ctx3, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','July','Aug','Sep','Oct','Nov','Dec'], datasets: [{ label: '# of Votes', data: [ {% for student in students_according_to_month %} {{student.total}}, {% endfor %} ], borderColor: '#dc3545', borderWidth: 1, fill: false }] }, options: { legend: { display: false, labels: { display: false } }, scales: { yAxes: [{ ticks: { beginAtZero:true, fontSize: 10, max: {{students|length}} } }], xAxes: [{ ticks: { beginAtZero:true, fontSize: 11 } … -
I can't makemigration appname in Django project
After completed, I pushed and rebase git master, database in my project is locked. I removed database and create new, but I don't see table for Model in models.py. How should I fix? Help me -
saving an object in django table
I am trying to save a django object in a table but it automatically gets converted in a string object which I am trying to save w = [<ItemBatch: Survey>] models.py items = ArrayField(models.CharField(max_length=300), default=default_thing) def default_thing(): return ['No Items Packed'] what I did: DispatchPlan.objects.create(items=w) but when I check the same in my table it is saved like this {Survey} I want to save it as an object itself, how do I do that? -
How to loop though users how object in django
I want to show the user all objects he made. Currently I can only show 1 object my_items.html (where i want it to show) {% extends 'base.html' %} {% block content%} <main role="main"> <div class="container"> <!-- Example row of columns --> <div class="row"> {% for item in item %} <!--{% if item.id == request.user.id %}--> <div class="col-md-4"> <div class="col-md-4"> <img style="max-width: 100px; max-height: 300px" src="{{ item.thumb.url }}"> </div> <h2><a href="{% url 'items:detail' slug=item.slug %}">{{ item.name }}</a></h2> <p>{{ item.snippet }}</p> <p>{{ item.date }}</p> <p><a class="btn btn-warning" href="#" role="button">Edit</button></a></p> <p><a class="btn btn-danger" href="#" role="button">Delete</a></p> </div> <!--{% endif %}--> {% endfor %} </div> <hr> </div> <!-- /container --> </main> {% endblock %} items views.py def item_myitems(request): item = Item.objects.all().order_by('date') return render(request, 'items/my_items.html', {'item': item}) i tried using filter() and get() on views.py