Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ask for audio input directly in website without recording audio , then downloading it and then uploading it in django
I am trying to create a website , which converts speech to text (Python). I need to use that program in a website(html,css,js) but I am not able to figure out how to ask for audio input directly from microphone instead of first recording it , then uploading it -
Django file not found error when the file is there
I am working on a social media app. i have a signal that resizes the post image after upload. signals.py @receiver(post_save, sender=Post) def create_uuid(sender, instance, created, **kwargs): if created: img_dir = instance.media.url img_dir_list = img_dir.split("/") img_ext = img_dir_list[-1].split(".")[0] im = Image.open(img_dir) new_width = 0 for x in range(0, 3): new_width += 200 new_height = int(new_width/image.width * image.height) image = im.resize((new_width, new_height)) image.save(f"{settings.MEDIA_URL}posts/{img}{new_width}x{new_height}.{img_ext}") instance.save() models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) media = models.ImageField(null=False, blank=False, upload_to="posts")) caption = models.CharField(max_length=100, default="", null=True, blank=True) date = models.DateTimeField(default=timezone.now, null=True, blank=True) when i add a post and run the signal. it gives me FileNotFoundError but i can see the file in my media folder. how can i fix this? -
Django for loop in template
I have two datasets: ButikPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=True, IsActive=1, URL=shop_page_slug) SubPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=False, URL=shop_page_slug) In my Template I try to filter these two lists that if one ButikPages Query has SubPages it should a drop down menu if not a link menu. <ul class="navbar-nav"> {% for page in ButikPages %} {% for parentpage in SubPages %} {% if page.IsActive == 1 and parentpage.Parent_id != page.ID %} <li class="nav-item"><a class="nav-link" href="/{{ page.Slug }}/">{{ page.PageTitle }}</a></li> {% else %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">{{ page.PageTitle }}</a> {% if parentpage.Parent_id == page.ID and parentpage.IsActive == 1 %} <ul class="dropdown-menu"> <li><a class="dropdown-item" href="/{{ parentpage.Slug }}/">{{ parentpage.PageTitle }}</a></li> </ul> </li> {% endif %} {% endif %} {% endfor %} {% endfor %} </ul> That works if a Menu just has one entry, but if I have two SubPages it appears two time, which is what I understand because the two for loops. But how can I access the SubPages without the second loop? regards. -
Django bootstrap dropdown button in navbar not working
I've tried other questions with similar topic with many different links to bootstrap but it was not working for me, none of them. Any clues why my dropdown button does not roll down when clicked (also does not when hovered either as this was the case for some people). Thanks for any help. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> </head> <body> <header> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> <li class="nav-item "><a class="nav-link" href="{% url 'milk_app:about' %}">About</a></li> <!-- If the user is logged in, either as HOST or TENANT he gets these buttons available --> {% if user.is_authenticated %} … -
Can not save form with CreateView (Django, Python)
I am trying to save form to database but it doesn't work. These are my codes. Views.py class HotelAdCreate(AuthorsAccessMixin,CreateView): model = HotelBookingAd form_class = HotelBookingAdForm template_name = "account/article-create-update.html" def form_valid(self,form): form.save() return super(HotelAdCreate).form_valid(form) Forms.py class HotelBookingAdForm(forms.ModelForm): class Meta: model = HotelBookingAd fields = '__all__' def clean_sales_price(self): sales_price = self.cleaned_data["sales_price"] purchase_price = self.cleaned_data["purchase_price"] if sales_price > purchase_price: raise forms.ValidationError("error.") print("error") return sales_price I've tried different options, but I don't have enough skills to handle this problem. Can anyone help me? -
Is it possible to work with Django on Windows and Reactjs on WSL on the same computer at the same time?
I have set up an environment for Django on my windows machine and I have React and Nodejs on Windows-subsytem-for-Linux. I want to build a pet project using Django for backend and React for front end. Is it possible on develop with these settings or should I install both of them on the same environment before starting? -
How to display data from selected option in django
I have a Django project that display data for Baseball players. I added a Select option on each html page. I would like to display individual player information based on the selection from dropdown. Ex: If i select "John Doe" from drop down, i would like to see only "John Doe's" information. How can i code this. Thanks. -
'CustomEmailBackend' object has no attribute 'request'
I'm attempting to subclass the smtp backend for django and I'd like to get access to self.request or request, I'm getting the following error: 'CustomEmailBackend' object has no attribute 'request' Here is my subclass of EmailBackend from django.core.mail.backends.smtp import EmailBackend class CustomEmailBackend(EmailBackend): def send_messages(self, email_messages): if not email_messages: return 0 with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: return 0 num_sent = 0 for message in email_messages: #set default for this message deliverable = True #get list of recipients on message recipients = message.recipients() for recipient in recipients: emailvalidation = email_validation(recipient) if emailvalidation.result == "Safe to Send": pass else: deliverable = False if deliverable == True: sent = self._send(message) if sent: num_sent += 1 else: messages.error(self.request, 'Email address invalid. Email was not sent.') if new_conn_created: self.close() return num_sent -
MultiValueDictKeyError at /api/users/ - Django
So I'm trying to create a backend API using django and django rest framework, I'm trying to implement a login system using custom tokens, So I'm trying to make it so that when you put your login information in get request then it is supposed to take that information and return you a token but I'm running into some errors, When I first load up the page by typing http://localhost:8000/api/users/?username=admin?password=12345 I get MultiValueDictKeyError at /api/users/ error. Here is my code: class UserTokenHandler(APIView): def get(self, request, format=None): username = request.GET['username'] password = request.GET['password'] user = User.objects.filter(username=username) if user.exists(): if user.password == password: chosen_token = '' for i in range(20): lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] random_choice = random.randint(1,3) if random_choice == 1: chosen_token += lower_case[random.randint(0, len(list) -1)] elif random_choice == 2: chosen_token += numbers[random.randint(0, len(list) -1)] elif random_choice == … -
mibian library version check in python
I am developing django project How can I check mibian version in run time of code import mibian print mibian.__version__ the bug result AttributeError: module 'mibian' has no attribute '__version__' -
include looged used in utils.py django
I have created an HTML calendar in the utils.py, where it created the events I would like to make it so that it uses the events of the user logged. There is a session created with the username. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event from myProject.helper import get_current_user class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal Does anyone have a solution on how I can achive that? -
Favicon not appearing
For some reason my favicon is not appearing on chrome. I am using django. And I have a file named favicon.ico in my static folder. {% load static %} <link rel="icon" href="{% static 'favicon.ico' %}"/> -
How do i get rid of value error, the view xxx didn't return an HttpResponse Object. It returned none instead
so im doing cs50x web development and the assignment is creating a wikipedia page. I created a views function where I can click on edit page to edit the content. However I keep running into this problem.enter image description here This is my code from views.py class EditForm(forms.Form): body = forms.CharField(label= "Body") def edit_page(request): title = request.POST.get("edit") body = util.get_entry(title) form = EditForm(initial={'body': body}) if request.method == "POST": form = EditForm(request.POST) if form.is_valid(): content = form.cleaned_data["body"] util.save_entry(title, content) return render(request, "encyclopedia/title.html", { "title": title, "content": util.get_entry(title) }) else: return render(request, "encyclopedia/edit.html", { "form": EditForm() }) urls.py: urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.title, name="title"), path("search", views.search, name="search"), path("new_page", views.new_page, name="new_page"), path("random", views.randomizer, name="random"), path("edit", views.edit_page, name="edit") ] title.html: <form action= "{% url 'edit' %}", method= "POST"> {% csrf_token %} <button type="submit" name="edit" value="{{title}}" id="edit">Edit Page</button> </form> and finally edit.html <form action="{% url 'edit' %}" method="POST"> {% csrf_token %} {{form}} <input type="submit"> </form> Someone please help me to solve this issue thanks! -
how to install proj4 in ubuntu , make: *** No targets specified and no makefile found. Stop. geodjango
i'm following the geodjango docs proj4 section , i have installed proj-7.0.1.tar.gz and proj-datumgrid-1.8.tar.gz , and untar them as in the docs mentioned , but when i try to run make command after directory ./configure it returns make: *** No targets specified and no makefile found. Stop. it there something i have missed ! or maybe i have used a wrong version thank you -
Django: Iterate through static files in HTML
I followed this answer. Iterate through a static image folder in django So I have {% with 'images/'|file as image_static %} <img src="{% static image_static %}" alt=""> <a class="gallery-one__link img-popup" href="{% static image_static %}"><i class="tripo-icon-plus-symbol"></i></a> {% endwith %} I did pass the context dict correctly in views, I think, because I saw this in my traceback: context_dict = {} files = os.listdir(os.path.join(settings.STATIC_ROOT, "blog/images/gallery")) context_dict['files'] = files But I'm not sure why it's giving me the following error django.template.exceptions.TemplateSyntaxError: Invalid filter: 'file' I also tried {% load crispy_forms_filters %} at the start of the HTML but it's not making a difference. I'm quite new to this, so I'm probably doing something stupid, and I cannot find any docs referring to this specific instance -
Django Rest Framework append object to many to many field without deleting the previous one
I am new to DRF and could not figure it out how to append an object to the many to many field without deleting the previous one. I am using PATCH to update the field MONITORS however the previous value gets substituted by the actual one. I want to append it. API GET is: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 3 ] } ''' after PATCH {"monitors":[11]} I get: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 11 ] } ''' I want the final GET API to be "monitors": [3 , 11] models.py ''' class Company(TimeStampedModel): companies_house_id = models.CharField(max_length=8, blank=True) name = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) date_founded = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='companies_created' ) monitors = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='companies_monitored', help_text='Users who want to be notified of updates to this company' ) def __unicode__(self): return u'{0}'.format(self.name) ''' serializers.py ''' from rest_framework import serializers from .models import Company from django.contrib.auth import get_user_model class CompanySerializer(serializers.ModelSerializer): class Meta: model = … -
Why is custom user password not getting set and authenticated?
I thought it would be a breeze to swap the User model's username with its email. So I am using a CustomUser. from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class CustomUser(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() Since CustomUser is inherited from AbstractUser model, I thought I was done, but I guess I am still far from it. Here's my django shell interaction: >> from django.contrib.auth import get_user_model >> User = get_user_model() >> User.objects.get(email='dave@gmail.com').password '123' # wutt? why is this plaintext? >> User.objects.get(email='dave@gmail.com').set_password('abc') >> User.objects.get(email='dave@gmail.com').password '123' # still same! So functionally, this is completely useless. Since django.contrib.auth.authenticate for the users always returns None. What am I doing wrong? How can I achieve the minimal functionality that my CustomUser is only different from default django User model in that my CustomUser should use email as the username? I have already checked out the SO hits: Django User password not getting hashed for custom users django custom user model password is not being hashed EDIT: I'm using the following as my UserManager from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): … -
Hi there !, I'm learning django as my first framework for backend, i face this error and not yet find way to fix it? hope someone will help me
File "C:\Users\tumatijr\Desktop\portfolio-project\portfolio\urls.py", line 24, in Path('/', views.home, name='home'), NameError: name 'Path' is not defined and this is the urls from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), Path('', jobs.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity'
i am beginner I don't know what to do sorry please help me Traceback Traceback (most recent call last): File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /cart/add/ Exception Value: add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity' urls.py from django.urls import path from .views import ( cart_home, add_to_cart, remove_from_cart, checkout_home, checkout_done_view ) app_name = 'carts' urlpatterns = [ path('', cart_home, name='home'), path('checkout/success', checkout_done_view, name='success'), path('checkout/', checkout_home, name='checkout'), path('add/', add_to_cart, name='add-item'), path('remove/<product_id>/', add_to_cart, name='remove-item'), ] views.py def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) cart.add(product, product.unit_price, quantity) def remove_from_cart(request, product_id): product = Product.objects.get(id=product_id) cart = Cart(request) cart.remove(product) def cart_home(request): cart = Cart(request) return render(request, 'carts/home.html', {"cart":cart}) -
django wsgi with apache2 configuration gives page not found 404
For assumption here testsite.com which is my php application and testsite.com/project is python-django application I have following settings in my apache site config file /etc/apache2/sites-available/site.conf <VirtualHost *:443> ServerAdmin webmaster@testsite.com ServerName testsite.com DocumentRoot /var/www/html WSGIDaemonProcess test python-path=/var/www/html/projectenv/test-project python-home=/var/www/html/projectenv WSGIProcessGroup test WSGIScriptAlias /project /var/www/html/projectenv/test-project/test-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> NOTE: I have to keep WSGIScriptAlias as /project since only for this url my django project should work. But when I hit testsite.com/project its giving following error Page not found (404) Using the URLconf defined in test-project.urls, Django tried these URL patterns, in this order: admin/ project/ The empty path didn't match any of these. Here is my project url structure urlpatterns = [ path('admin/', admin.site.urls), path('', include('projectapp.urls')) ] projectapp/urls.py from django.urls import path from . import views urlpatterns = [ path('project/', views.home, name='project'), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'projectapp', ] Please suggest solution that when I hit this url testsite.com/project it should go through my defined django app and render the page which is linked to this view, Its observed that wsgi is not able to pass through the django project structure and due to which its not identifying the url given in app. … -
How to use the file path of a .csv file in Django project(Web app)
I have a Django project that can get the .csv file from the user. Now I want to do analyze the .csv file on my Django project. How can I get the path of the file from my Django project to do this? Here is my Django settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') I would like to analyze the data saved in the media and then try to show the result like a table in the web application. If you any sample code that helps me in that case please share it. I hope you understand the problem. Thanks in advance -
Can you add html meta-description to django blog post model?
I'm wondering if it's possible/google allows to add a meta_description CharField to Post model to dynamically change meta description on html page? My current meta description is <meta name="description" content="{{ post.title }} blog post from the {{ post.category }} category."> Which obviously isn't ideal as it doesn't give a great description of the individual blog post. Then I got to thinking of whether I can just add a field to set in the same manor. This way I would be able to set the CharField to max length so I know all meta descriptions are proper length, and I would be able to set a proper description for each blog post. class Post(models.Model): title = models.CharField(max_length =250) body = RichTextField(blank=True, null=True) meta_description = models.CharField(max_length=150) <meta name="description" content="{{ post.meta_description }}" Does anyone see any issues with this before I attempt to implement it? Does anyone know if this is allowed by Google? Thanks in advance. I would have attempted this first to see if it would work but I'm still quite new, and last time I attempted to add a field to an existing model with existing objects I screwed it up and all existing objects would cause an error, so … -
Replacing Bootstap svg placeholder image
https://getbootstrap.com/docs/4.0/examples/carousel/ I'm following along with this and implementing this in Django. HTML: <!DOCTYPE html> {% load static %} <!-- saved from url=(0052)https://getbootstrap.com/docs/5.0/examples/carousel/ --> <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.82.0"> <title>Carousel Template · Bootstrap v5.0</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/carousel/"> <!-- Bootstrap core CSS --> <link href="{% static 'home/css/bootstrap.min.css' %}" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png"> <link rel="manifest" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/manifest.json"> <link rel="mask-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon.ico"> <meta name="theme-color" content="#7952b3"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --><link href="{% static 'home/css/carousel.css' %}" rel="stylesheet"> <script data-dapp-detection="">!function(){let e=!1;function n(){if(!e){const n=document.createElement("meta");n.name="dapp-detected",document.head.appendChild(n),e=!0}}if(window.hasOwnProperty("ethereum")){if(window.__disableDappDetectionInsertion=!0,void 0===window.ethereum)return;n()}else{var t=window.ethereum;Object.defineProperty(window,"ethereum",{configurable:!0,enumerable:!1,set:function(e){window.__disableDappDetectionInsertion||n(),t=e},get:function(){if(!window.__disableDappDetectionInsertion){const e=arguments.callee;e&&e.caller&&e.caller.toString&&-1!==e.caller.toString().indexOf("getOwnPropertyNames")||n()}return t}})}}();</script></head> <body data-new-gr-c-s-check-loaded="14.1002.0" data-gr-ext-installed=""> <header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Carousel</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" … -
ManyToManyField value is None
Im trying to use ManytoManyField for my Book , but it is showing None in web page and administration.Here is my code class Category (models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=40) author = models.CharField(max_length=30) description = models.TextField() category = models.ManyToManyField(Category) publish_year = models.CharField(max_length=5) language = LanguageField(max_length=40, default=False) age_group = models.CharField(max_length=5, choices=GROUP_CHOICES) downloaded_times = models.IntegerField() rate = models.FloatField() rate_times = models.IntegerField() rate_total = models.FloatField() book_image = models.ImageField(upload_to='book_cover_image', default="image.png") pdf_file = models.FileField(default=True, upload_to='media') def __str__(self): return f"{self.title}|-|{self.category}|-|{self.author}" In views.py I have def get_queryset(self): query = self.request.GET.get('q') object_list = Book.objects.filter( Q(title__icontains=query) ) print(Book.category) return object_list The Category looks like this: -
Post matching query does not exist. - Django error while trying to access URL of other pages
Everything was okay till I created a blog app in my Django projects, now when I try to access the other apps(pages) on the website, it gives me this error. I can't access the URLs under the other apps, I can only access the URLs under the blog blog/views.py from django.shortcuts import render, redirect from .models import Post from .forms import commentform def blog(request): posts = Post.objects.all(pk=id) return render(request, 'blog.html', {'posts': posts}) def howtouse(request): return render(request, 'howtouse.html') def full_post(request, slug): post = Post.objects.get(slug=slug) if request.method == 'POST': form = commentform(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('full_post', slug=post.slug) else: form = commentform() return render(request, 'full_post.html', {'post': post, 'form': form}) blog/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() intro = models.TextField() body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_added'] class Comments(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['date_added']