Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery ломает CSS стили
всем привет, сразу извиняюсь за возможно довольно глупый вопрос который скорее всего напрямую связан с моими кривыми руками, но, тем не менее есть проблема с тем что при подключении файлов JQuery в мой Django проект ломаются все стили на странице к которой подключаю, до подключения всё работает корректно. Я новичок и скорее всего просто чего-то не понимаю, и не могу уже какой день решить эту проблему, сразу скажу что я знаю про collect static и все те вещи которые нужно делать со статическими файлами, ибо стили работают нормально и в файле settings.py все пути указаны верно. код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. JQuery код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. $(document).ready(function() { // Менюшка и появляющиеся категории $('.nav_show_btn').click(function() { let display = $('.nav_show_links').css('display') if (display == 'none') { $('.nav_show_links').slideDown('100') } else { $('.nav_show_links').slideUp('100') } }) $('.category_btn').click(function() { let display = $('.categorys_container').css('display') if (display == 'none') { $('.categorys_container').slideDown('100') $('.category_btn').addClass('active') } else { $('.categorys_container').slideUp('100') $('.category_btn').removeClass('active') } }) // Профиль и его меню { let active; $('#main_inf_user').click(function() { if (active != 'off' | active == undefined) … -
Django model design for Shopping List. how to use ManytoMany relationship?
I am working on making django app to handle multiple shopping list. which should have ManytoMany field? Item model or List model? is this model optimal ? A list can have many items, many sublists, many associated store. And, except for List vs Sublist all the relationships are many to many. An item can be in many list, a store can be associated to many list. sublist is just putting the item in categories so I can also remove this model and add a category attribute to items. Item has m2m fields for List but should it also have m2m field for Sublist? a List need not have sublist so the item can be part of list or sublist in a list (like a folder/file structure) models.py: class List(models.Model): name = models.Charfield(max_length=125) date = models.DateField(default=django.utils.timezone.now) class Store(models.Model) : name = models.CharField(max_length=128) store = models.ManyToManyField(List) class Item(models.Model): item = models.CharField(max_length=128) price = models.FloatField(default=0.0) category = models.CharField(max_length=128, default=None) checked = models.BooleanField(default=None) store = models.ManyToManyField(List) class SubList(models.Model): name = models.Charfield(max_length=256) parent_list = models.ForeignKey(List) items = models.ManyToManyField(Item) -
UpdateView Doesn't Save Data, returns object field data in url
After a LOT, LOT, LOT of research, I COULD NOT FIND OUT why UpdateView in django wasn't saving form data upon being saved. Instead, it saved the data in a url when it redirected me back to an un-edited object detail view. I'm sharing the same template for CreateView and UpdateView Here's my Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.views import View from .models import Blog from .forms import BlogForm from django.views.generic import ( CreateView, ListView, DetailView, UpdateView, DeleteView ) class BlogListView(ListView): template_name = 'blogtemplates/blogs.html' queryset = Blog.objects.all() model = Blog paginate_by = 4 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context class BlogDetailView(DetailView): model = Blog template_name = 'blogview.html' queryset = Blog.objects.all() def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(Blog, id=id_) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context class BlogCreateView(CreateView): template_name = 'blogpost.html' form_class = BlogForm queryset = Blog.objects.all() def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context … -
matching query does not exist - how can I get an item from an API and save it to a user's profile?
I'm trying to add an item of a search result into a user's profile. The thing is, when I look for the items, they are not saved into my database unless the user saves them to their profile (that's my intention). My code is supposed to get the item by its id (which in my code was supposed to be the id it has on the API but that doesn't seem to work) but since the item is in the API and not in my database, it doesn't work. So how can I manage to get the item from the API and save it to the user's profile (and, that way, to my database)? These are the models: class Anime(models.Model): title = models.CharField('Title', max_length=150) episodes = models.IntegerField() image = models.ImageField() mal_id = models.IntegerField(null=True) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Anime, related_name='favorited_by', null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() These are the views: def search(request): animes = [] if request.method=='POST' and 'search' in request.POST : animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results … -
OpenCV can't capture frames on production server (Nginx + uWSGI)
I'm building a production server on Raspberry Pi 4. Web app is written in Django. I used uWSGI as an application server and Nginx as a reverse proxy. I followed many tips from Digital Ocean. One of the tasks is to stream frames from USB camera connected to RPi. My inspirations was post from PyImageSearch, but I wanted to do it in Django. Code looks as follows: # views.py from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() if not self.grabbed: print("Can't open camera") threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def camera_usb(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: print("Something went wrong") and then I use code of 'camera_usb' view in urls.py and in template. It works fine both on my laptop and on RPi 4, but only on development server. After running on production server I get following message from sudo systemctl status uwsgi: uwsgi.service - uWSGI Emperor service Loaded: … -
Why am I getting ValueError in my Django REST view?
I am trying to send a POST request to my view to create an object using DRF. The GET request in the same view works fine, but I can't seem to create the object. Here is my view: class ProjectsListCreateAPIView(generics.ListCreateAPIView): serializer_class = ProjectSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): owned_projects = Project.objects.filter(owner=self.request.user) assigned_projects = self.request.user.project_set.all() return sorted( chain(owned_projects, assigned_projects), key=attrgetter('created') ) Here is my serializer: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ['id', 'created', 'owner', 'title', 'slug'] Here is the error that I am getting: ValueError at /projects/ Cannot force both insert and updating in model saving. What am I doing wrong here? -
how to get json send from fetch in django view
I send value of an input field (one email or more seprated by ',')to an api view : var emails_list = document.getElementById('members_email').value; fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFtoken': csrftoken, }, body: JSON.stringify({ 'emails_list': emails_list }) }) .then(response => response.json()) .then(data => { console.log('Success:', data); send_prefered_times_to_time_api(data); }) and this the api view: @api_view(http_method_names=['POST']) def get_prefer_times(request): if request.method=='post': serializer = EmailsListSerializer(data=request.data) if serializer.is_valid(): invited_users_email = serializer['emails_list'].split(',') print(invited_users_email) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and this is serializer.py: class EmailsListSerializer(serializers.Serializer): emails_list = serializers.ListField(child=serializers.CharField()) but i get this error: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data -
Trying to retrieve the data having specific id value by applying joining select_related query using DJANGO ORM
I want to retrieve the specific subtopic id's questions along with its options and answer.(Eg i want to retrieve all questions and their choices,answer whose subtopic id is 2) but when i apply the query it provides me all the subtopics questions and answers that are present in DB. here is my models.py from django.db import models from django.db.models import Model # Create your models here. class Teacher_Signup(models.Model): username = models.CharField(max_length=122) email = models.EmailField(max_length=40) password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) def __str__(self): return self.username class Meta: db_table = 'Teacher_Signup' class Add_Grade(models.Model): grade = models.CharField(max_length=40) username = models.ForeignKey(Teacher_Signup,on_delete=models.CASCADE, default = 1) #teacher_name = models.CharField(max_length=40) def __int__(self): return id class Meta: db_table = 'Add_Grade' class Student_Signup(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) username = models.CharField(max_length=70) father_name = models.EmailField(max_length=70) #grade = models.PositiveIntegerField () age =models.PositiveIntegerField () phone_no =models.IntegerField () password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) def __str__(self): return self.username class Meta: db_table = 'Student_Signup' class Add_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.CharField(max_length=40) def __int__(self): return id class Meta: db_table = 'Add_Topics' class Sub_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics,on_delete=models.CASCADE, default = 1) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") subtopic = models.CharField(max_length=40, default = 1) def __str__(self): return self.subtopic … -
Set Dataframe index in jinja template
In a Django app, I have following template: detail.html: <select name="indexColumn" id="selectIndexOptions"> <option>Set Index</option> {% for k, v in data.items %} <option>{{ k }}</option> {% endfor %} </select> I want to give users options to set index of the dataframe. I don't know how to set index of a dataframe in jinja. -
Issue for user from an existing database to login in a Django website
There is my problem, so I need to create a Django app and I think I have to use an already existing database with users in. So I did some research and figured out some issues. So Django store the password with the salt and use it to check the password.But no one says that there will be salt + hashed type password in the database, but we can get read of this issue with the proper check function (related to the encryption function) I think, like this guy Django check_password() always returning False who used bcrypt.checkpw(password, hashedPassword) because in his database passwords are encrypted with bcrypt. The solution proposed was to create a custom authentification backend (even if I don't really see how we can do this I may be able to find out a tuto to do so) but the main issue is that how I can save a user password who register through the Django web site with the same type of hash that the one already existing in the database (with no salt). I'm a really sorry for not be able to give you more precision about how the password are stored in the database because … -
Django structure
I really need a way to print the structure of my Django app So I have an almost finished app and I need to print something like this: ~/projects/project_name/ docs/ # documentation scripts/ manage.py # installed to PATH via setup.py project_name/ # project dir (the one which django-admin.py creates) apps/ # project-specific applications accounts/ # most frequent app, with custom user model __init__.py ... settings/ # settings for different environments, see below __init__.py production.py development.py ... __init__.py # contains project version urls.py wsgi.py static/ # site-specific static files templates/ # site-specific templates tests/ # site-specific tests (mostly in-browser ones) tmp/ # excluded from git setup.py requirements.txt requirements_dev.txt pytest.ini Is this possible? I only can find a way to create an app based in other structure. I need the same but in the other way... Getting the structure of my app... Thanks!!!! -
Got an unexpected keyword argument 'my_id' (Dynamic URL Routing)
django 3.2.2 urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view urlpatterns = [ path('products/<int:my_id>/', dynamic_lookup_view, name='product'), path('', home_view, name='home'), path('about/', about_view), path('contact/', contact_view), path('create/', product_create_view), path('initial/', render_initial_data), path('product/', product_detail_view), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render, get_object_or_404 from .forms import ProductForm, RawProducForm from .models import Product # Create your views here. def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/product_detail.html", context) I want to see the products with the following link: http://127.0.0.1:8000/products/2/ this returns me: TypeError at / products / 2 / dynamic_lookup_view () got an unexpected keyword argument 'my_id' -
Django model class with multiple objects from other model class
I want to create a Django model schema to track yacht racing results. This is a highly simplified version, but want to only focus on the relationships and schema first; class Yacht(models.Model): name = models.CharField(max_length=50) class Event(models.Model): event_number = models.IntegerField() class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete = models.CASCADE) event_number = models.ForeignKey(Event, on_delete = models.CASCADE) result = models.IntegerField(default=0) Question: How would you approach this problem where I want to create an Event, and have it list all the yachts where I can enter their time? I'd like to be able to do this in the Admin 'all at once' instead of going to each yacht. Eventually, I want this to display as a form for a user. For example, if a user clicks on a race event, it loads a page with all the yachts and their time slot. Julien -
Inserting data from an array into a WORD document table
I have two arrays ['2021-04-30', '2021-05-02', '2021-05-04', '2021-05-06'] [1500, 450, 750, 900] There is a document template How do I insert data from the date array into {{ date }} and data from the price array into the {{ price }} variable?In this case, each new record in the table must start with a new cell doc = Document('Шаблон.docx') date = post_data.get('date', False) price = post_data.get('price', False) context = {'date': date, 'price': price} doc.render(context) doc.save('restyled.docx') This works when the data is not an array -
Django not detecting changes in app model
I have created an app called base and added a new model to it. However, whenever I run python3 manage.py makemigrations base It says no changes detected. I have already added my in installed apps INSTALLED_APPS = [ ... 'base.apps.BaseConfig', ... ] And it does have the migrations folder inside the app containing and __init__.py file. I was wondering what is causing this issue. This is my model: from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now=True) modified_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True And my settings contains 4 files: settings: --__init__.py -- dev.py -- prod.py -- staging.py -- common.py My __init__.py: import os from .common import * from decouple import config environment = config('DEV_ENV', cast=str) if environment == "dev": from .dev import * elif environment == "staging": from .staging import * elif environment == "prod": from .prod import * I have also already tried running python3 manage.py makemigration base --settings=project.settings.dev and it still says no changes detected -
Issues, the courses appear to everyone and not to the users who purchased the course
Issues, the courses appear to everyone and not to the users who purchased the course , the problem is any one can access to the course if he type the url for course views.py : def coursePage(request,slug): course = Course.objects.get(slug = slug) serial_number = request.GET.get('lecture') videos = course.video_set.all().order_by('serial_number') if serial_number is None: serial_number = 1 video = Video.objects.get(serial_number = serial_number , course = course) # print("priview", video.is_preview) # print(request.user.is_authenticated) # print(request.user) if (video.is_preview is False): if (request.user.is_authenticated is False): return redirect('login') else: user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) except: return redirect('checkout',slug = course.slug) data = { "course":course, "video":video, "videos":videos } return render(request,'courses\courses.html',data) how to fix this problem , i want user who purchased the course can see it not all also i want to ask how to store videos private in db and no body can access videos if he not purchased i mean like udemy -
Formset saving any decimal except 0 even though formset is saved and is_valid() passes
I have created a formset to let users log hours on a weekly basis. The issue I'm having is that I can't save "0" in the input fields - any decimal works but 0 (see gif at the end for illustration) TLDR: Formset saves any input except 0, see gif here for illustration: https://imgur.com/a/iCMexQk My Timesheet and TimesheetEntry models looks as following: class Timesheet(Model): year = PositiveIntegerField(validators=[MaxValueValidator(2500), MinValueValidator(1900)]) week = PositiveIntegerField() project = ForeignKey("projects.Project", on_delete=CASCADE) user = ForeignKey(User, on_delete=CASCADE) status = CharField( max_length=15, choices=STATUS_CHOICES, blank=True, default=STATUS_OPEN ) objects = TimesheetManager() class Meta: db_table = 'timesheet' ordering = ('id',) unique_together = (('year', 'week', 'user', 'project',),) def __getattr__(self, attr): allowed_days = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) if attr in allowed_days: day = int(attr[-1]) - 1 entry = self.timesheetentry_set.filter( date=Week(self.year, self.week).day(day) ).first() if entry: return entry.hours return None return super().__getattr__(attr) def total_duration(self): return self.timesheetentry_set.aggregate( total_duration=Coalesce(Sum('hours'), 0) ).get('total_duration') class TimesheetEntry(Model): timesheet = ForeignKey(Timesheet, on_delete=CASCADE) hours = DecimalField(max_digits=4, decimal_places=1, null=True, blank=True) date = DateField() class Meta: db_table = 'timesheet_entry' ordering = ('date',) And the forms.py looks as following: DAYS = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) class TimesheetModelForm(ModelForm): class Meta: model = Timesheet exclude = ("user", "status") class … -
How can i override, Django Rest Auth Registration?
I'm working on a small project using Django / Rest Auth, and I would like to know how can I override the registration, I would like to add some other fields in the registration, as I want to do some other things during the registration. PS: I checked already some questions here but I couldn't use them because each one explains a different approach that's why -
Django rest framework - serializer is not valid
Good day. I'm trying to create an entity by POST method. I have Serializer, and some javascript code - that sends me FormData , which I'm trying to serialize. This is my view: @api_view(['POST']) @parser_classes([MultiPartParser, FormParser]) def cocktail_create(request): """Создание коктейля""" pprint(request.data) serializer = CocktailCreateSerializer(data=request.data) pprint(serializer.fields) if serializer.is_valid(): serializer.create(serializer.validated_data) else: pprint(serializer.errors) request.data: {'author': '4', 'cocktail_tool': '[{"tool":"1","amount":"1"}, {"tool":"2","amount":"1"}]', 'csrfmiddlewaretoken': 'KFb9ZEBwWViF4Sm9pQxZn5KcfXpfu7t6OigeqsXZri9hoQQ1RPuS1lQDF3NJ3Aq5', 'description': 'asdasd', 'img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>, 'name': 'Danya', 'recipe': '[{"ingredient":"1","amount":"1"},{"ingredient":"2","amount":"1"}]', 'recipe_text': '{"1":"asdasd","2":"asdasd"}', 'small_img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>} serializer.fields : {'img': ImageField(allow_null=True, max_length=100, required=False), 'small_img': ImageField(allow_null=True, max_length=100, required=False), 'cocktail_tool': CocktailToolsForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) tool = PrimaryKeyRelatedField(queryset=BarTool.objects.all()), 'description': CharField(style={'base_template': 'textarea.html'}), 'name': CharField(max_length=255, validators=[<UniqueValidator(queryset=Cocktail.objects.all())>]), 'recipe': RecipeForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) ingredient = PrimaryKeyRelatedField(queryset=Ingredient.objects.all()), 'recipe_text': JSONField(decoder=None, encoder=None, style={'base_template': 'textarea.html'}), 'author': PrimaryKeyRelatedField(allow_null=True, queryset=BarbookUser.objects.all(), required=False)} serializer.errors: {'cocktail_tool': [ErrorDetail(string='This field is required.', code='required')], 'recipe': [ErrorDetail(string='This field is required.', code='required')]} my serializers : class CocktailToolsForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailTool fields = ("amount", "tool") class RecipeForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailRecipe fields = ("amount", "ingredient") class CocktailCreateSerializer(serializers.ModelSerializer): cocktail_tool = CocktailToolsForCocktailCreateSerializer(many=True) recipe = RecipeForCocktailCreateSerializer(many=True) class Meta: model = Cocktail fields = ("img", "small_img", "cocktail_tool", "description", "name", "recipe", "recipe_text", "author") my models: I have a cocktail model , ingredient model and bartool model, and many to many tables such as: class CocktailRecipe(models.Model): … -
refreshing audios makes them impossible to listen to
I want to make a whatsapp like message app but only with audios. I can get them in my vue app the by refreshing regularly the store, to see if new audios arrived: refresh() { this.$store.dispatch("audio/getAudios"); }, }, created() { setInterval(this.refresh, 1000); }, and I display them the following way in my vue app: <div class="audios" v-for="audio in audios" :key="audio"> <audio controls v-if="audio.rooms.split(',').includes(room)"> <source :src= "'http://localhost:8000'+audio.audiofile" type="audio/wav"> </audio> </div> </div> The problem is that by refreshing every second, all audios that are displayed are 're'-displayed and it makes impossible to listen to them. How can I use the v-for differently to avoid this trouble ? -
django not saving data to model
I am working on the cs50w commerce project. The page I am making should create an auction listing for an item the user wants to sell. After entering the info into the form and clicking the button the data is not saved to the model. going to the admin page shows that my listings model has 0 listings. I can not find the issue. I have been working on this portion of the code for 2 days. any help would be appreciated. HTML {% extends "auctions/layout.html" %} {% block body %} <h2>Create Listing</h2> <div class="text-left"> <form action="{% url 'createlisting' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="title" placeholder="Title"> </div> <div class="form-group"> <textarea class="form-control" name="description" rows="4" placeholder="Add a Description"></textarea> </div> <div class="form-group"> <select class="form-control" name="category" placeholder="Category" required> <option value="">Select a Category</option> <option value="books">Books</option> <option value="clothes">Clothes</option> <option value="electronics">Electronics</option> <option value="games">Games</option> <option value="movies">Movies</option> <option value="tools">Tools</option> <option value="toys">Toys</option> <option value="other">Other</option> </select> </div> <div class="form-group"> <input class="form-control" type="text" name="starting_price" placeholder="Starting Price"> </div> <div class="form-group"> <input class="form-control" type="text" name="image_link" placeholder="Link to Image"> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Create"> </div> </form> </div> </div> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), … -
Cannot use a Django's foreign key result in the template
I have two tables in Django models.py connected by Foreign Key. class Category(models.Model): name = models.CharField(max_length=254) src = models.CharField(max_length=254, null=True, blank=True) friendly_name = models.CharField(max_length=254, null=True, blank=True) class Videos(models.Model): category_id = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=254) content = models.URLField(max_length=1024) In a views.py I write the following code to use it in template def videos(request): videos = Videos.objects.all() categories = Category.objects.all() context = { 'videos' : videos, 'categories' : categories, } return render(request, 'videos/index.html', context) In the template I use the following jinja tags to output each category name followed by connected posts's titles. {% for category in categories %} <li class="nav-item mt-2"> <a class="nav-link ml-3 pl-0 pb-3 side-menu-section-name" href="#"> <img src="{{ category.src }}" width="45px" class="pr-2" alt="Video's Category's Icon">By {{ category.name }} </a> </li> {% for video in videos %} {% if video.category_id != None %} {% if video.category_id == category.name %} <!-- Here should be posts titles which are in current category --> {{ video.title }} {% endif %} {% endif %} {% endfor %} {% endfor %} So the problem is that the following comparison {% if video.category_id == category.name %} doesn't work. I print there's value separately and in print version booth's values are string with same … -
Create in Django objects linked list followed each to other
I'm trying to build in Django a kind of linked list of objects that will create objects by the user request. The main purpose is to build some kind of flowchart ob objects that will run some action. How to write the architecture by Django model/s? Thanks in advance. Daniel. -
Django logs not going to the expected log files
I have this LOGGING settings for my Django app. What I was expecting is that the views logs would go into their own separate folder when I have three different loggers in my views file. Logger in my view file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'views_error_file': { 'class': 'logging.FileHandler', 'filename': 'logs/errors/views.debug.log', }, 'views_info_file': { 'class': 'logging.FileHandler', 'filename': 'logs/infos/views.debug.log', }, 'views_debug_file': { 'class': 'logging.FileHandler', 'filename': 'logs/debugs/views.debug.log', } }, 'loggers': { 'py_folder.views': { 'handlers': ['views_error_file'], 'level': 'ERROR', }, 'py_folder.views': { 'handlers': ['views_info_file'], 'level': 'INFO', }, 'py_folder.views': { 'handlers': ['views_debug_file'], 'level': 'DEBUG', } } } The views.py file: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def sample_function(request): params_choices = ['param_1', 'param_2'] sample_param = request.POST.get('sample_param') # logger.debug should be logged at logs/debugs/views.debug.log logger.debug(sample_param) if sample_param in params_choices: if sample_param == 'param_1': # logger.info should be logged at logs/infos/views.debug.log logger.info("param_1 okay") return redirect("/param_1-req") else: # logger.error should be logged at logs/error/views.debug.log logger.error("param_2 okay") return redirect("/param_2-req") else: logger.error("param does not exist") return redirect("/param-invalid") But its only going in to the logs/debugs/views.debug.log. The logs/debugs/views.debug.log file: param_3 param does not exist I tried changing the logs/infos/views.debug.log to logs/infos/views.info.log and logs/error/views.error.log to logs/error/views.error.log but nothing changed. I don't know why … -
Check who is logged in Django admin panel
how to check whether the user is logged in or not from admin panel what are the changes i need to make in models.py and admin.py to achieve this from django.contrib.auth.models import User