Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically delete logs in Django
Building a Django app, I am trying to figure out what would be the best way to automate log file deletion. My try so far is to build a admin command that delete old logs. From this I can setup a scheduler in python or at server's level but I am not very satisfied with this option because it makes more configuration steps to do during deployment. I was wondering if sub-classing log module to trigger a delete-log function on a log write would be a good idea. The pros would be that there is not setup to do a deployment, the cons would be to rely on log write to clean log directory could be useless if there is no log records for a long time. On the other hand it could be resource consuming if there is too many log records. So first of all, is a log-delete triggered by any action could be a good idea and what would be the best action to choose (a daily one)? If not, what would be the best option to perform this in a beautiful way? -
Django: How to filter model objects after passing through functions?
I have a model called Service, which has a field url of type str. I have a function f that returns the hostname of an url: def f(url): return urllib.parse.urlparse(url).hostname I want to get all the objects whose f(url) equals a value target. One way to achieve this would be by doing the following: [x for x in Service.objects.all() if(f(x.url) == target)] But in that case, I'll get a list, not a QuerySet. Is there a way to filter the objects and get a QuerySet satisfying the above criteria? -
Filtering a foreign key in Django
I'm trying to filter a foreign key, but it's not rendering any data, no matter the approach I use from examples.Here is the code class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer',primary_key=True) first_name = models.CharField(blank=True, max_length=150) last_name = models.CharField(blank=True, max_length=150) name = models.CharField(max_length=200, null=True) ' class Order(models.Model): Distributor = models.ManyToManyField(settings.AUTH_USER_MODEL,) Customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='customer_client') The Views def dashboard(request): orders = Order.objects.filter(Distributor=request.user) customers = orders.filter(Customer_id=1) i'm trying to filter the customers who have made the orders from a particular Distributor, kindly assist -
How to connect Django to remote MySQL database over ssh tunnel?
I have access to remote MySQL database using ssh tunnel with host, user, password. I can access to database in MySQL Workbench using ssh tunnel with SSH Hostname, SSH Username, SSH Password. Also I have access in Pycharm using ssh tunnel with Host, User name, Password. I'm trying to connect Django to a MySQL database. Is it possible to add SSH settings to these database settings in Django settings file and have access through Django? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' } } -
Having problems with Django Translation in italian
I was trying to create a django site in two languages, English and Italian. I have declared in the settings.py file all the properties necessary for it to work, following both the django doc and other guides on stackoverflow, but with no positive results. settings.py file: it/LC_MESSAGES/django.po file: index.html file: views.py file: result: commands used: -
NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused)
I am trying to build a simple django elastice search which can search cars. But when I am trying to rebuid the indexes, it gives me the error above. I am following this doc -> quickstart elasticsearch...full traceback is given below-> elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused) my models.py is simple Car model having name, color, description, type filds on which I add in document class Car(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=50) description = models.TextField() type = models.IntegerField(choices=[ (1, "Sedan"), (2, "Truck"), (4, "SUV"), ]) my documents.py file-> from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Car @registry.register_document class CarDocument(Document): class Index: name = 'cars' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Car fields = [ 'name', 'color', 'description', 'type', ] but when i am trying to rebuid the index, it gives the new connection error. The command I am using to rebuild the index is given below -> python manage.py search_index --rebuild -
django-taggit Error on calling names() on Custom Tag
I am trying to create a model with two types of tags associated with companies and topics and followed the documentation at django-taggit for making Custom Tags to facilitate having two Taggable Manager in one model. My models.py from django.db import models from taggit.managers import TaggableManager from taggit.models import GenericTaggedItemBase, TagBase # Create your models here. class TopicTag(TagBase): class Meta: verbose_name = "TopicTag" verbose_name_plural = "TopicTags" class CompanyTag(TagBase): class Meta: verbose_name = "CompanyTag" verbose_name_plural = "CompanyTags" class ThroughTopicTag(GenericTaggedItemBase): tag = models.ForeignKey(TopicTag, on_delete=models.CASCADE) class ThroughCompanyTag(GenericTaggedItemBase): tag = models.ForeignKey(CompanyTag, on_delete= models.CASCADE) class Questions(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=500) company_tags = TaggableManager(blank = True, through=ThroughCompanyTag, related_name="company_tags") topic_tags = TaggableManager(blank = True, through=ThroughTopicTag, related_name="topic_tags") Now, when I try to running the following commands in django shell from QuestionBank.models import Questions Questions.objects.first().company_tags.names() I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/utils.py", line 124, in inner return func(self, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/managers.py", line 248, in names return self.get_queryset().values_list("name", flat=True) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/managers.py", line 74, in get_queryset return self.through.tags_for(self.model, self.instance, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/models.py", line 155, in tags_for return cls.tag_model().objects.filter(**kwargs).distinct() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, … -
Employee matching query does not exist
Its my view function i have two db tables customer and employee when im deleting a row in employee table im getting this error (Employee matching query does not exist.). same issue in customer table also. def delete(request, user_id): delCust = Customer.objects.get(user_id = user_id) delEmp = Employee.objects.get(user_id = user_id) delEmp.delete() delCust.delete() return redirect("/admins") -
"ImportError: Traceback (most recent call last):" I don'y know how to fix this Error
I got an error while making a chat bot watching some video and I install python 3.6.5 and pip install nltk pip install numpy pip install tflearn pip install tensorflow and I wrote codes import nltk from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() import numpy import tflearn import tensorflow import random import json with open("intents.json") as file: data =json.load(file) print(data) and I run this codes Traceback (most recent call last): File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: 지정된 모듈을 찾을 수 없습니다. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "main.py", line 6, in <module> import tflearn File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tflearn\__init__.py", line 4, in <module> from . import config File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tflearn\config.py", line 3, in <module> import tensorflow as tf File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\__init__.py", line 41, in <module> from tensorflow.python.tools import module_util as _module_util File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\__init__.py", line 40, in <module> from tensorflow.python.eager import context File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\eager\context.py", line 35, in <module> from tensorflow.python import pywrap_tfe File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tfe.py", line 28, in <module> from tensorflow.python import pywrap_tensorflow File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 83, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load … -
Django-oscar attribute cannot be blank
I'm new to learning django-oscar. I recently installed a project and am trying to create my first directory. Now I have only 1 product class and 1 product attribute(I want to make it required). When I try to create a product I get the error color attribute cannot be blank.I filled in the fields with text and even filled in the time of adding, but I get this error. What could be the problem? -
Django - track down the code that generated slow queries in database
I'm using Django for a large app. When monitoring the DB (Postgres) I sometimes see a few slow queries log written. The problem is how to track down the code that generated these queries. optimally I want some stack trace for these logs, but wonder if there is some other best-practice, or maybe some other tool. It's in production so DEBUG is set to False, so Django itself doesn't track the speed of the queries. -
How can i load Vue on a Django project using Webpack-Loader?
I would like to add VueJS to my Django project, and since i don't want to go full SPA, i decided to use Webpack-Loader, so after making some research i cloned a very simple Django+Vue app from Github, to see how would that work, here is the full code. Now, on my local everything works fine. In order to run the project i do manage.py runserver and npm run serve. I'm trying, now, to run this same example project in production on a Digital Ocean vps using Gunicorn + Nginx, but the problem is that while the Django app works fine, none of the Vue frontend is being loaded. I only see a bunch of errors like: net::ERR_ABORTED 404 (Not Found). Can anyone help me find what's wrong? I thought that on production i would not need to use two servers since i'm using Webpack. The code is exactly the same i linked. Can anyone help me out on this? -
FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg'
While docker image was being created, I've got the below exception: FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg' Dockerfile: FROM python:3.6 # ... Packages: django==2.0.6 redis==3.5.3 django-redis-cache==2.0.0 django-redis-sessions Here is a full trace of the exception: Traceback (most recent call last): File "/usr/local/bin/pip", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/main.py", line 75, in main return command.main(cmd_args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 121, in main return self._main(args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 265, in _main self.handle_pip_version_check(options) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 152, in handle_pip_version_check timeout=min(5, options.timeout) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 97, in _build_session index_urls=self._get_index_urls(options), File "/usr/local/lib/python3.6/site-packages/pip/_internal/network/session.py", line 249, in __init__ self.headers["User-Agent"] = user_agent() File "/usr/local/lib/python3.6/site-packages/pip/_internal/network/session.py", line 159, in user_agent setuptools_version = get_installed_version("setuptools") File "/usr/local/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 665, in get_installed_version working_set = pkg_resources.WorkingSet() File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 567, in __init__ self.add_entry(entry) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 623, in add_entry for dist in find_distributions(entry, True): File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1983, in find_eggs_in_zip if metadata.has_metadata('PKG-INFO'): File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1414, in has_metadata return self._has(path) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1854, in _has return zip_path in self.zipinfo or zip_path in self._index() File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1731, in zipinfo return self._zip_manifests.load(self.loader.archive) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1688, in load mtime = os.stat(path).st_mtime FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg' Question: How can I overcome this issue? Any help would be … -
Django REST API - Joining multiple tables in a query
My goal is to get all EmployeeQuestions, such that employee has an employer with the given id (request.user.pk). More formally, I want to get all EmployeeQuestions where question has a course where employer_id is the given id. I hope this makes sense. Basically as an employer I want to retrieve all the question progress of all my employees. I thought I made the right query but it just returns all EmployeeQuestions: EmployeeQuestion.objects.filter(question__in=CourseQuestion.objects.filter(course__in=Course.objects.filter(employer_id=request.user.pk))) Any Django query geniuses here who can help me? :) View class EmployeeQuestionByEmployerId(viewsets.ModelViewSet): queryset = EmployeeQuestion.objects.all() serializer_class = EmployeeQuestionSerializer def list(self, request): queryset = EmployeeQuestion.objects.all() if request.query_params: queryset = EmployeeQuestion.objects.filter(question__in=CourseQuestion.objects.filter(course__in=Course.objects.filter(employer_id=request.user.pk))) serializer = EmployeeQuestionSerializer(queryset, many=True) return Response(serializer.data) Models class CustomUser(AbstractBaseUser): username = ... employer = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) class Course(models.Model): employer_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255, blank=False, null=False) class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, null=False) question = models.CharField(max_length=255, blank=False, null=False) question_type = models.CharField(max_length=255, blank=False, null=False) # mult/ord/open class EmployeeQuestion(models.Model): employee = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) question = models.ForeignKey(CourseQuestion, on_delete=models.CASCADE, null=False) passed = models.BooleanField(default=False) -
Django using URL dispatcher
I have a horoscope site, I want to make a blog, I created an HTML file called Bloglist.html where the pictures and names of the blogs are listed, then I made Blogdetail.html where there is already a definition of a specific block (body_Text, author ..). It's all I want to link to the URL dispatcher. but can not do it , can anyone help? url.py urlpatterns = [ path('',Home,name= "Home"), path("blog/<slug:slug>/",blog_list, name="blog_list"), ] Models.py class Blogmodel(models.Model): Title = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="media/image",null=True) body = models.TextField(blank=True, null=True) slug = models.TextField(blank=True, null=True) bloglist.html <div class="blog_box"> <a href="/blog/{{ article.slug }}" class="blog_img"><img src="/storage/blog/thumbs/251-.png"></a> <a href="/blog/{{ article.slug }}" class="blog_title">{{ article.Title }}</a> </div> views.py def blog_list(request,slug): article = Blogmodel.objects.get(Title=slug) args = {'article':article, 'slug':slug} return render(request,'blog.html',args) -
Ended up with Pylint-django issue while trying to modify single table postgreSQL database to One-to-Many relationship
I was trying to modify my single table db to 1-to-many relationship database with two tables, "proType" and "Work" respectively where one proType can have multiple work and vice versa. Initially I only had "Work" table. I added new model class "proType" added Foreignkey for the relationship as below. After creating the model I deleted everything from migration folder except init_.py file and I ran following code in cmd prompt python manage.py makemigrations (showed me the two new models/tables that needed migration) python manage.py migrate and got result as below, Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, works Running migrations: No migrations to apply. Now when I run my localhost for django I get rendering error coming from views.py with following error which asks me to fulfill necessary requirements for pylint. And when I try to install pylint I am getting following results, Is it suggesting me to use cpython instead of pylint because of my python version not being compatible to the package that I need. Or I don't need pylint in first place to accomplish my one-to-many db model? or if there's any other workaround to meet my goal? Please guide me through this issus. … -
how to make end_year choice value start from start_year input value : Django
I have start_year and end_year choice in model fields. How to make end_year field choice will start from start_year value that you user input. enter code here Models.py: YEAR_CHOICES = [] for r in range(2005, (datetime.datetime.now().year+5)): YEAR_CHOICES.append((r,r)) start_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) ENDYEAR_CHOICES = [] for r in range((start),(datetime.datetime.now().year+5)): ENDYEAR_CHOICES.append((r,r)) end_year = models.IntegerField(choices=ENDYEAR_CHOICES, default=datetime.datetime.now().year) -
how to save the html text in django database
I want to save the time(html text) to my django admin and this timer work well enter image description here html_file 00 This 00 part i want to save enter image description here views.py part enter image description here forms.py part enter image description here models.py part -
Import problem in pycharm with django tutorial
Yesterday I started learning django with this tutorial: https://www.youtube.com/watch?v=IMG4r03G6g8 But I am getting an Import Error here: file: django_1/src/dj30/urls.py from django.contrib import admin from django.urls import path from posts.views import post_list_view # ERROR LINE urlpatterns = [ path('admin/', admin.site.urls), path('posts/', post_list_view) ] This is my directory tree: I assume that the Import Error occurs because I am trying to import posts.views.post_list_view from posts/views.py into dj30/urls.py which is in another directory. How does the guy in the tutorial do it? I am positive that I followed the tutorial correctly (I did it twice). Maybe there is a problem with venv because I am using PyCharm (com) and he is not. Here are relevant files that were edited during the tutorial: django/src/dj30/settings.py: """ Django settings for dj30 project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s' # SECURITY WARNING: don't … -
How do I set my foreign key to the current user in my views
I am developing an app that needs users to login and create posts.The post model has an image and a caption(the user inputs) and a profile foreign key that should to automatically pick the logged in users profile. The app however isnt autopicking the profile.Can someone spot what am doing wrong? I feel like the particular issue is in this line of code in my views form.instance.profile = self.request.Image.profile Someone kindly help models from django.db import models from django.contrib.auth.models import User import PIL.Image from django.urls import reverse # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='images/') caption = models.TextField() profile = models.ForeignKey('Profile', default='1', on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True) created_on = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('vinsta-home') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to = 'photos/',default='default.jpg') bio = models.TextField(max_length=500, blank=True, default=f'I love vinstagram!') def __str__(self): return f'{self.user.username}' views from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import (ListView,CreateView,) from .models import Image def home(request): context = { 'posts': Image.objects.all() } return render(request, 'vinsta/home.html', context) class ImageListView(ListView): model = Image template_name = 'vinsta/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-created_on'] class ImageCreateView(LoginRequiredMixin, CreateView): model = Image fields = ['image', 'caption'] def form_valid(self, form): form.instance.profile = self.request.Image.profile … -
create multiple collapse when i use for loop in Django template
How to create multiple collapse when i use for loop in Django template I have created a django template which show lists of lessons and i want to create collapse for each lesson such that on click of it , it shows the video from my url . how i can do this html code : <div id="accordion"> {% for lesson in course_posts.lesson_set.all %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0 text-center"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{lesson.name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <iframe width="100%" height="400px" src="{{lesson.youtube_url}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </div> {% endfor %} </div> -
How to remove Byte Order Mark from utf-16 to utf-8 python3?
I going to cast UTF-16 to UTF-8 in django with python3, this is my request to django web app in the "settings.py" with DEFAULT_CHARSET = "utf-16": <QueryDict: {'mykey': ['\ufeff33992FFBDDB5209E523A77DF980FA578']}> We have a Byte Order Mark \ufeff, I was unable to cast to UTF-8, How to remove it? -
Celery task testcase refuses to complete
I have a celery task that iterates through a django queryset. For each iteration, my code interacts with an external api. When i run my testcase to test the task, for some unknown reasons test doesn't complete # celery task @shared_task def iterate_and_compute(): qs = Product.objects.all() for item in qs: iteract_with_external_api() # my testcase from django.test import TestCase from myapp.models import Product from myapp.tasks import iterate_and_compute class TaskTestCase(TestCase): def setUp(self): # do some setup, like creating some products def test_iterate_and_compute_is_successful(): task = iterate_and_compute.delay() res = task.get() self.assertEqual(task.status, 'SUCCESS') celery worker is started like so: celery -A myproject worker -l INFO -P solo my test is run like so: python manage.py test myapp.tests.test_tasks.TaskTestCase.test_iterate_and_compute_is_successful From celery worker i get this response, that task succeeded Task myapp.tasks.iterate_and_compute[71ab0ede-3a58-476b-a5cd-27e56552e9f1] succeeded in 0.07800000000861473s: None This is the response i get from my test console python manage.py test myapp.tests.test_tasks.TaskTestCase.test_iterate_and_compute_is_successful Creating test database for alias 'default'... System check identified no issues (0 silenced). That response remains like so for minutes. Do's & Dont's i'm not chaining / grouping task and no other task is called within iterate_and_compute task within my iterate_and_compute task i use time.sleep(25) which should only last for 25 seconds What i've tried I've tried starting … -
how to make api for comments on a blog detail view. I dont need replies to comments ( ie no children comment)
I want to show comments of a blog post detail. I am new to Django. I have to make an api for this. Here is what I have. class BlogPost(models.Model): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') description = models.CharField(max_length=255) content = RichTextUploadingField() # todo support for tags tags = models.CharField(max_length=255, default='#travel') #todo date_created = models.DateField() @property def html_stripped(self): from django.utils.html import strip_tags return strip_tags(self.content) class Comment(models.Model): blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, default=1) name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('created_at',) This is my serializers class CommentSerializer(serializers.ModelSerializer): blog = serializers.StringRelatedField() class Meta: model = Comment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = CommentSerializer(source='comments.content') class Meta: model = BlogPost fields = ['image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' Here is my view. class BlogPostDetailsListAPIView(ListAPIView): serializer_class = BlogPostSerializer def get_queryset(self): return BlogPost.objects.filter(pk=self.kwargs['pk']) Here my view is returning only the BLogpost objects, but not comments.How to return the comments along with the post detail view as well? Can we do without the contenttype? -
Owl Carousel not showing images in Django server
Well, as explained in the title, when I designed the site in plain css and html, it shows the images perfectly, here's the relevant code after calling the necessary files, and result IN PURE FRONTEND: <!-- ================= main slide ================= --> <div class="owl-init slider-main owl-carousel" data-items="1" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide"> <img src="img/banners/CDMX.jpg"> </div> <div class="item-slide"> <img src="img/banners/GDL.jpg"> </div> <div class="item-slide"> <img src="img/banners/MTY.png"> </div> </div> <!-- ============== main slidesow .end // ============= --> </div> <!-- col.// --> and the result: yet, here's the code in index.html after extending the base.html file and making sure all css an js files are correctly called: <!-- ================= ciudades slide ================= --> <div class="owl-init slider-main owl-carousel" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide owl-item"> <img src="{% static 'core/img/banners/MTY.png' %}"> </div> <div class="item-slide owl-item"> <img src="{% static 'core/img/banners/GDL.jpg' %} "> </div> <div class="item-slide owl-item "> <img src="{% static 'core/img/banners/CDMX.jpg' %}"> </div> </div> <!-- ============== main slidesow .end // ============= --> </div> <!-- col.// --> and this result: it shows the following result when analyzing the html result in the browser: <!-- ================= ciudades slide ================= --> <div class="owl-init slider-main owl-carousel" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide owl-item"> <img src="/static/core/img/banners/MTY.png"> </div> <div class="item-slide owl-item"> <img src="/static/core/img/banners/GDL.jpg "> </div> <div …