Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid block tag on line 4: 'endfor'. Did you forget to register or load this tag?
Error during template rendering. Invalid block tag on line 4: 'endfor'. Did you forget to register or load this tag? views.py def Courses(request): ac= Allcourses.object.all() template = loader.get_template('/projectname/resources.html') context = { 'ac':ac,} return HttpResponse(template.render(context, request))` recources.html <ol> {% for x in ac %) <li> <a href="/projectname/{{ course.id }}/"> {{ x.coursename }} </a></li> {% endfor %} urls.py urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('resources',views.Resources.as_view(),name= 'resources'), path('resources/<int:course_id>/',views.detail, name = 'detail'), ] -
how to prompt user to save a generated pdf (already existing on my local server) using django 3.0?
I am new to Django and my project requires me to create a pdf when a user clicks on a link. But instead of generating the pdf (using ReportLab), I was thinking if I can use the pdf already on my local machine and prompt the user to download it to his machine. Is there any way to do that? Thanks -
NoReverseMatch at /cart/ Reverse for '' not found. '' is not a valid view function or pattern name
Fellows I have an issue with this code, I'm trying to build a shopping cart but is not working, this is the error NoReverseMatch at /cart/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.0.7 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: C:\Users\user\Desktop\playzone\Playzoneshop\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\user\Desktop\playzone\Playzoneshop\env\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\user\\Desktop\\playzone\\Playzoneshop\\playzoneb', 'C:\\Users\\user\\Desktop\\playzone\\Playzoneshop\\env\\Scripts\\python37.zip', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\DLLs', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37', 'C:\\Users\\user\\Desktop\\playzone\\Playzoneshop\\env', 'C:\\Users\\user\\Desktop\\playzone\\Playzoneshop\\env\\lib\\site-packages'] Server time: Vie, 3 Jul 2020 02:28:59 +0000 Error during template rendering In template C:\Users\user\Desktop\playzone\Playzoneshop\playzoneb\templates\base.html, error at line 32 Reverse for '' not found. '' is not a valid view function or pattern name. 22 <li class="nav-item"> 23 <a class="nav-link" href="{% url 'home:login' %}">Ingresar</a> 24 </li> 25 <li class="nav-item"> 26 <a class="nav-link" href="{% url 'home:logout' %}">Salir</a> 27 </li> 28 <li class="nav-item"> 29 <a class="nav-link" href="{% url 'home:registro' %}">Registrarse</a> 30 </li> 31 <li class="nav-item"> 32 <a class="nav-link" href="{% url 'carts:cart' %}">Carrito <span class="fas fa-shopping-car"></span></a> 33 </li> 34 35 </ul> 36 <form class="form-inline my-2 my-lg-0"> 37 <input class="form-control mr-sm-2" type="search" placeholder="Buscar" aria-label="Search"> 38 <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button> 39 … -
Create URL dynamically according to models in Django
I'm trying to write URL paths according to data inside Django database (models). Below, my URL.py file: from . import views from django.urls import path from .models import Seller sellers = Seller.objects.all app_name = 'root' urlpatterns = [ path('', views.index, name='index'), for seller in sellers: path(seller.name, views.seller, name='sellers'), ] I know the 'for-loop' inside the urlpatterns list is completely wrong. Any idea? -
Logout reverse url doesn't work with next page
In my view, I'm checking if the user who owns a specific email address is the authenticated user. If not, I want to redirect to logout and then to login with the same URL. Here is my view: class VerifyUserEmailAddressView(LoginRequiredMixin, SingleObjectMixin, generic.View): model = UserEmailAddress success_url = reverse_lazy('accounts:edit_profile_emails') def get(self, request, *args, **kwargs): email_address = self.get_object() if (not (email_address.user == self.request.user)): return redirect(to='accounts:logout', **{'next_page': self.request.get_full_path()}) # This is the line who causes the exception. assert (email_address.user == self.request.user) ... This is my logout view: class LogoutView(django_auth_views.LogoutView): template_name = 'accounts/logged_out.html' But the problem is, I get an exception: django.urls.exceptions.NoReverseMatch: Reverse for 'logout' with keyword arguments '{'next_page': '/edit-profile/emails/95209103364882328130/verify/64435189922652686051/'}' not found. 1 pattern(s) tried: ['logout\\/$'] How can I fix this problem? -
Django queryset filter by multi percentage wildcard
I know that Django queryset has contains, startswith and endswith to perform LIKE operation like %word%, %word and word%. Is there any way to perform like operation %w%o%r%d%? -
How to get the total items in Context to reflect in Template in Django List View
I am working on an E-commerce project and I got lost in the middle to generate some kind of a report to get the total no. of a sold item after payment is made. When the order is paid ordered = models.BooleanField(default=False) become True I have tried to add the context with the total sold but it didn't work so I kept it in the code below but commented it. Here is the Item models.py class Item(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title Here is the OrderItemmodels.py class OrderItem(models.Model): ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) Here is the Order class Order(models.Model): items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) Here is the views.py class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') def get_context_data(self, **kwargs): comments = Comment.objects.all() # total_sold = Order.objects.all() context = super().get_context_data(**kwargs) context["total_comments"] = comments.count() # context["total_sold"] = total_sold.count() return context Here is the template {% for item in items %} <tr> <td>No. of Sold:</td> <td>{{ item.total_sold.all.count }}</td> </tr> {% endfor %} -
Display a django-from from JS
so here is the thing i have a block of html code that needs to be replaced when a button is clicked. Its no big deal using $('div.myCustomReplacer').replaceWith(newHTML); but i also need to render a django-form {{ form }} in the new HTML when i simply use <div class="NewDiv"> {{ form }} </div? the html is rendered as "{{ form }}" because of those quotes the form is not rendered. So how i do remove those ? sorry just new to JavaScript. -
Django select from table with multiple column values "or"
I have a Books table where I want to retrieve all records based on different column values e.g Select * from Books where bookid = 2 || bookid = 3 || bookid = 4; The book ids I get is from a Rent table: rents =Rents.objects.filter(user=request.user) So I have a queryset of rents object that contains a property bookid. How do I get Books based on all the values of the rents? -
can inheriting from custom user model cause problems in Django?
I am developing simple user and its worker related django model. I have my custom user model and its contents as follows. class UserManager(BaseUserManager): """User Manager class for custom user""" def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError("User must have a phone number") user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, phone_number, password=None, **extra_fields): user = self.create_user(phone_number, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model: phone number is unique field""" phone_number = models.CharField(max_length=20, unique=True) firstname = models.CharField(max_length=200) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'phone_number' class Meta: ordering = ('-id', ) def __str__(self): return f'{self.firstname}: {self.phone_number}' I needed to add wokers who has its type and employer. I have developed a new model but inherited from user model that I wrote above. Below contents of Employee models. class Employee(User): TYPE = ( ('EDITOR', 'editor'), ('ACCOUNTANT', 'accountant'), ('MANAGER', 'manager'), ) employer = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='workers') type = models.CharField(max_length=50, choices=TYPE) Now if I create a new employee it is being created as a user as well. I checked for data consistency and it is passed. Data is being update on both side if one … -
Why my json.dumps return a string not an array?
I'm trying to test out how to send a data from backend to django tempalte Here is my views.py: def index(req): labels = ['hello', 'wassup'] values = [] def chart_label(labels): labels1 = [] for i in labels: labels1.append(i) return labels1 test = chart_label(labels) chart_data = { 'y': json.dumps(test), } return render(req, 'index.html', chart_data) here is my template index.html: <script type="text/javascript"> var y = `{{ y | safe }}` console.log(y.length) </script> I should give me the length is 2 but this is give me 19. Which is every single character in my array? -
why does my webpage show html code instead of rendering
Hello I made a code to query brands to show up in the HTML using templates. but i have been getting the actual HTML to show up instead def index(request): form = Search(request.GET or None) if form.is_valid(): form.save() content = { 'form' : form } brand = Brand.objects.all() brand_listing = { 'brand' : brand } return render(request, 'homepage/columntemplate.html', content, brand_listing) My HTML tag is {{brand}} placed in the static folder. Also is it possible to pass a form and a variable? -
Keep getting the error: ModuleNotFoundError: No module named 'allauth'. I tried all the steps in the similar question, but to no avail
I installed allauth through pip install django-allauth and I keep getting an error. I uninstalled it and installed it again with pip install django-rest-auth[with_social]. Still getting the same error. Here's traceback: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/lib/python3/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' -
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf. Views.py from django.shortcuts import render from django.views.generic import ListView,DetailView from testApp.models import Book class BookListView(ListView): model=Book class BookDetailView(DetailView): model=Book urls.py from django.urls import path from testApp import views urlpatterns = [ path('', views.BookListView.as_view()), path('details/<int:id>', views.BookDetailView.as_view()), ] Book_list.html <!DOCTYPE html> {% extends 'testApp/base.html' %} {%block body_block%} <h1>Books Information with default way!!</h1><hr> <h2>Books Information</h2><hr> {% for book in book_list %} <h2> <a href="/testApp/details/{{book.id}}">{{book.title}}</a> </h2> {%endfor%} {%endblock%} -
Why my json.dumps not return value to my browser?
I'm trying to send my data from backend to django template here is my views.py: def labels_chart(values): for i in sorted_by_size[:5]: values.append(i['forks']) return values print(labels_chart(values)) Here is my templates index.html: <script> var x = "{{y}}" console.log(x) </script> When I print(labels_chart(values)) it appear data : [1, 0, 0, 0, 0] in my terminal but it now showing the console.log in my browser. -
Django DetailView update on one page not working - NoReverseMatch error
I have a problem with update of my DetailView, so once i try to submit the updated values I am receiving an error NoReverseMatch at /task/164/. Could you please give me a hint what is wrong? Thx! urls: path('excel_upload', ex_views.ExcelUploadView.as_view(), name='excel-upload'), path('user_list', ex_views.UsersListView.as_view(), name = "user-list"), path('excel_table', ex_views.ExcelTableView.as_view(), name = "excel-table"), path("task/add", ex_views.TaskAddView.as_view(), name="task-add"), path("task/<int:pk>/", ex_views.TaskDetailView.as_view(), name="task-detail"), forms.py class AddEditTaskForm(forms.ModelForm): class Meta: model = Task exclude = ['created_by'] widgets = { "due_date": forms.DateInput(attrs={'type':'date'}), "completed_date": forms.DateInput(attrs={'type': 'date'}), "name":forms.TextInput(), "note": forms.Textarea(), } views.py class TaskDetailView(DetailView): model = Task template_name = "hana/task_detail.html" # Add POST method def post(self, request, pk): task = get_object_or_404(Task, pk=pk) form = AddEditTaskForm(request.POST, instance=task) if "add_edit_task" in request.POST: if form.is_valid(): form.save() messages.success(request, "The task has been edited.") return redirect('excel-table') return render(request, 'hana/task_detail.html', {'form': form}) error: NoReverseMatch at /task/164/ Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$'] Request Method: POST Request URL: http://127.0.0.1:8000/task/164/ Django Version: 3.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$'] Exception Location: /home/lukasz/envtest2/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 -
Getting a base64 Image string , converting to a image and storing in django models DB
I am working on a Django project where i am getting base64 string on my back-end using AJAX. How do i convert it to a Image and store in my models.[Image Field] -
DRY in nested for loops
I am simplifying code that repeats itself and notice a loop being used in several places. What ways can this loop be written so that call upon the loop when needed? for group in groups: receiver_list = list(Employee.objects.filter(role=group)) for receiver in receiver_list: stuff_to_do() # this can be different tasks but the loop is always the same -
attempt to write a readonly database (Django/Apache)
After updating my models.py file with a single attribute, I had to delete my migrations and db.sqlite3 file and then 'makemigrations' and 'migrate' to update the database with a new column. However, after doing so, I ran into the above error: "attempt to write a readonly database". I looked at the other answers on here, and one of them suggested that I delete the db.sqlite3 file as well as the other migration files (other than init.py). I did so, going through every migrations folder, deleting both the migrations as well as 'pycache', and then used the 'makemigrations' and 'migrate' commands, but still received the same error. Another answer suggested that I use the command 'chmod 755 db.sqlite3', which I did, but still ended up with the same error. Are there any other possibilities? The code that I changed in my models.py file is as follows: id = models.CharField('id', max_length=150, unique=True, default='') -
can any genius help Django: no model named
i accidentally moved the reading1 app in inspectationsprofiles wich issss in .idea folder then when i moved it back to my project folder , it shows this error when i run the server: '''' ModuleNotFoundError: No module named 'reading1' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 599, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 584, in start_django reloader.run(django_main_thread) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 299, in run self.run_loop() File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 305, in run_loop next(ticker) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 345, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 361, in snapshot_files for file in self.watched_files(): File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 260, in watched_files yield from iter_all_python_module_files() File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\yasmine\Envs\pro\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "c:\users\yasmine\appdata\local\programs\python\python37-32\lib\pathlib.py", line 1144, in resolve s = … -
Showing SQLite entry in HTML using Django
I want to show my text entry in SQLite database. however it is not showing up. My page loads file but it doesn't show my text db entry. I am getting an error saying could not parse {{% text %}} i hav gone into my django admin page and added in some text into my db text portion of the db. i dont know why it isn't showing up on my webpage. MODELS.PY from django.db import models class Datadata(models.Model): text = models.TextField() VIEWS.PY def index(request): return render(request, "index.html", {}) INDEX.HTML {% load static %} <h1>{{% text %}}</h1> -
Django dPage not found (404) when try to save a new post
i'm new in django development, and my application work perfectly in local machine but fter deployment of the project i get this error when try to save a new post (maysite.com/admin/myclasse/myobject/add) just for forms with file using : models.ImageField. models.py class Judge(models.Model): picture = models.ImageField( verbose_name=_('Picture'), upload_to='judge_pics', null=True, blank=True) urls.py urlpatterns = [ path('judges/',judgeallView, name='all') ] seting of static and media file STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to filter objects from a QuerySet in list
I am trying to use the django-friendship package in order to get the Friend requests to my user. When I use: Friend.objects.requests(user=request.user) it returns a list of id's of users who sent a request to request.user in a form such as: [<FriendshipRequest: 14>, <FriendshipRequest: 15>, <FriendshipRequest: 16>, <FriendshipRequest: 18>] which is a list of the quesryset of FriendshipRequest objects to request.user I plan on using id__in in order to retrieve users who sent a friend request to my user, however, I cannot use that because I get the following error: TypeError: Field 'id' expected a number but got <FriendshipRequest: 14>. This is my complete code: pending_requests = Friend.objects.sent_requests(user=request.user) friend_requests = Profile.objects.filter(id__in=requests) How can I achieve this? Thanks in advance! -
AJAX function not working in a Django template
I am trying to reload a div with id=inbox every few seconds. However, the div is not reloading. I get no errors in the console. Any suggestion about a different ajax function to reload the div would be good also. Its part of a django project. My script: <script> setInterval(refresh_logs(), 2000); function refresh_logs() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("inbox").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "{% url 'messages' %}", true); xmlhttp.send(); } </script> -
NoReverseMatch: Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls\\/\\<int\\:question_id\\/\\>$']
I am following along Traversy Media's Django tutorial for the poll app and when I ran my code near the end I got the error stated in the title all of the sudden: why is detail not found? views.py from django.shortcuts import render from .models import Question, Choice # Get questions and display them def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) #Show specific question and choices def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/results.html', { 'question': question }) # Get questions and display results def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', { 'question': question }) urls.py(polls) from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id/>', views.detail, name='detail'), path('<int:question_id/results/>', views.results, name='results'), ] urls.py(pollster) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] index.html {% extends 'base.html' %} {% block content %} <h1 class="text-center mb-3">Poll Questions</h1> {% if latest_question_list %} {% for question in latest_question_list %} <div class="card mb-3"> <div class="card-body"> <p class="lead">{{ question.question_text }}</p> <a href="{% url 'polls:detail' question.id %}" class="btn btn-primary btn-sm">Vote Now</a> <a href="{% …