Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot turn PIL.Image.Image to tensor using tochvision transforms.ToTensor in Django
I'm doing a AI service using django app served by uWSGI in docker which setup from my senior. And it's always 504 time-out when reach img_tensor = transforms.ToTensor()(img_resized) This is views.py from django.apps import apps from rest_framework import status from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response import os, shutil import gc import uuid from PIL import Image from multiprocessing import Pool import torch from fairseq import utils from torch.utils.data import DataLoader from torchvision import transforms from HTR.serializers import HTRSerializer from HTR.Backend.main import generate_text class HTRViewSet(APIView): permission_classes = [permissions.AllowAny] config = apps.get_app_config('HTR') def post(self, request, format=None): serializer = HTRSerializer(data=request.data) if serializer.is_valid(): # input_text haven't use now image = serializer.validated_data['image'] input_text =serializer.validated_data['text'] unique_id = str(uuid.uuid4()) directory_path = os.path.join(os.getcwd(), 'HTR', 'Backend', 'image', unique_id) doc_list = generate_text(image, directory_path, self.config.TrOCR, self.config.device) gc.collect() doc = '\n'.join(doc_list) corrected = None full_doc = doc.replace('\n', '<br>') return Response({'document': full_doc, 'corrected': corrected}, status=status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) main.py for running AI model from fairseq.data import Dictionary from fairseq import utils from torch.utils.data import DataLoader import torch import os, shutil try: from .bpe import GPT2BPE from .dataset import STRDataset from .Preprocess.main import processing except ImportError: from bpe import GPT2BPE from dataset import STRDataset from Preprocess.main import processing … -
How to Post Video source from react native camera component to Django server
How can i post video source(Which formate) from react native to Django server after processing video then return to react native Component In my Camera Component try { const response = await axios.post('http://localhost:8000/my-post-view/', {videoSource}); setApivideo(response.data); } catch (error) { console.error('Error:', error); } In My Django View def my_post_view(request): if request.method == 'POST': video_uri = request.data.get('videoUri') //Im Processing video Here actually its not reading video_uri - cap = cv2.VideoCapture(video_path) //After processing the video return HttpResponse({'processedData': cap}) I tried above Using Post method but im confused about how to post video source and get Processed video return back to my react native component -
Python import modules in a script is not working
import json import os import django import openai import sys # Ensure the DJANGO_SETTINGS_MODULE is set to your project's settings module. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tastify_backend.settings") django.setup() from recipe.models import Ingredient, IngredientCategory, MeasuringUnit, Recipe print(Ingredient.objects.all().select_related('ingredient_category').filter(ingredient_category=1)) The import of the model does not work, there is the following: Here is the error traceback, so that you can check what I am missing. Traceback (most recent call last): File "/Users/patrickvogele/Desktop/tastify_backend/recipe/scripts/generate_ingredients.py", line 9, in <module> django.setup() File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tastify_backend' Why is that? -
Why does it give an error when trying to do django logging writing its handlers?
settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'database': { 'level': 'DEBUG', 'class': 'megabot.log.DatabaseHandler', }, }, 'loggers': { 'main': { 'handlers': ['database'], 'level': 'DEBUG', 'propogate':True } }, } log.py import logging from .models import Log class DatabaseHandler(logging.Handler): def emit(self, record): log = self.format(record) level = record.levelname message = record.getMessage() Log.objects.create(level=level, message=message) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = DatabaseHandler() formatter = logging.Formatter('%(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) models.py class Log(models.Model): level = models.CharField(max_length=50) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I'm trying to set up recording errors directly to my application Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/log.py", line 76, in configure_logging logging_config_func(logging_settings) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 809, in dictConfig dictConfigClass(config).configure() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 571, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'database' -
how to log the user in Directus from a different domain and login form then authenticate him in the Directus admin page
now I have created a Directus application, and am using it as a back-end .. and am letting the user log in from another external domain and form Django app and sending post request to be able to login .. how to stop Derictus from asking him to log in again after i redirect him to the Directus admin panel link after login success ? here are some of the codes I have used for the whole process : docekr-compose.yaml for the Directus part : version: "3" services: db: image: ${DB_IMAGE} container_name: ${DB_CONTAINER_NAME} volumes: - ${DB_VOLUME} ports: - '${DB_PORT}:5432' restart: always environment: - POSTGRES_DB=${DB_DATABASE} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} # - PGDATA=/tmp directus: image: directus/directus:10.7.1 container_name: ${WEB_CONTAINER_NAME} ports: - ${APP_PORT}:8055 restart: always volumes: - ./uploads:/directus/uploads environment: KEY: ${KEY} SECRET: ${SECRET} ADMIN_EMAIL: ${ADMIN_EMAIL} ADMIN_PASSWORD: ${ADMIN_PASSWORD} DB_CLIENT: ${DB_CLIENT} DB_FILENAME: ${DB_FILENAME} DB_HOST: ${DB_HOST} DB_PORT: 5432 DB_DATABASE: ${DB_DATABASE} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} WEBSOCKETS_ENABLED: true depends_on: - db and my Django logic : def authenticate_user(request): print("function called") if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') # Create a JSON payload data = { "email": email, "password": password } # Send a POST request to the external API url = "http://<my_domain>:<port>/auth/login" headers = {'Content-Type': 'application/json'} … -
Djnago Admin : Country/State/City Dropdown
I'm trying to do a chained dropdown of Country/State/City in Django Admin I know there is lot of post about this, And this is very basic problem. Is there any good solution or builtin solution that Im missing, Can anyone tell, How to solve it or guide in proper direction? -
Sending emails with Django, not receiving email
I am trying to implement a contact form in Django. It works locally in the terminal if i change EMAIL_BACKEND to console rather than smtp. I have set up 2FA in Gmail and using this as the password, I am also deploying to Heroku where I have set up the correct config vars. Can anyone see why this might not be working? setting.py file # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER') SERVER_EMAIL = os.environ.get('EMAIL_HOST_USER') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = False EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASS = os.environ.get('EMAIL_HOST_PASS') views.py from django.shortcuts import render, redirect from django.core.mail import EmailMessage, get_connection from django.conf import settings # Create your views here. # https://opensource.com/article/22/12/django-send-emails-smtp def send_email(request): if request.method == "POST": with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASS, use_tls=settings.EMAIL_USE_TLS ) as connection: name = request.POST.get("name") email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST.get("email"), ] message = request.POST.get("message") EmailMessage(name, message, email_from, recipient_list, connection=connection).send() return render(request, 'contact.html') contact.html <section class="container"> <div class="row justify-content-md-center"> <div class="col-sm-6 center-form"> <h1>Contact Us:</h1> <form method="POST" action="{% url 'mail' %}" id="contact-form"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Name" required> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" name="email" id="email" placeholder="Email" required> </div> … -
Add multiple category for one post (drf+React)
I have a blog website built with Django and React. I'm currently working on adding a new blog post feature, and I want to allow users to select one or multiple categories for their blog post. Here's what I have done so far: Fetched all the categories from the database and displayed them in a dropdown/select field. Users can select one or multiple categories from the dropdown. Now, I need help with the next steps. How can I send the selected categories to the database and save them for the new blog post? Any guidance or code examples would be greatly appreciated. import React, { useEffect, useState } from 'react'; import Dashboard from './Dashboard'; import useAxios from '../../utils/useAxios'; function AuthorCreateBlogs() { const baseurl = "http://127.0.0.1:8000/api/posts/v1"; const [selectedCategories, setSelectedCategories] = useState([]); const api = useAxios(); const [categoriesData, setCategoriesData] = useState([]); const [blogData, setBlogData] = useState({ "title": "", "slug": "", "body": "", "tags": "", "categories": [], "img": "", }) const handelInputChange = (event) => { const { name, value } = event.target; setBlogData((blogData) => ({ ...blogData, [name]: value })); }; const handleFileChange = (event) => { setBlogData((blogData) => ({ ...blogData, ['img']: event.target.files[0] // Match the key used in FormData })); }; const … -
Sitemaps in Django
I'm trying to get the dynamic sitemap generator working in my Django blog. I've followed the directions given here, I even went so far as to create a new "recipes" project and worked through the tutorial. I got the sitemap to work in the tutorial, but I can't get it to work in my blog. Can anyone help? Here's the project-level urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import TemplateView from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap from blog.models import Post # from blog.sitemaps import BlogSitemap info_dict = { "queryset": Post.objects.all(), "date_field": "date_posted", } urlpatterns = [ path('admin/', admin.site.urls), # path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetView.as_view( template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('blog.urls')), path('summernote/', include('django_summernote.urls')), # Robots.txt path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), # Sitemap # path('sitemap.xml', sitemap, {'sitemaps': {'blog': BlogSitemap}},), path("sitemap.xml", sitemap, {"sitemaps": {"blog": GenericSitemap(info_dict)}},), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's the blog app's urls.py: from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, … -
"Origin checking failed - null does not match any trusted origins"
I run two servers with two different PORTs on localhost. (localhost:3000 and localhost:4000) I have a post form in localhost:3000 and want to send to localhost:4000 <form action = "http://localhost:4000/print" method = POST> {% csrf_token %} <input type="file" id="myFile" name="filename"> <input type="submit"> </form> in my views.py of localhost:4000 if request.method == "POST": data = request.POST file = data.get("filename") return render(request,"print_success.html",{"form":file}) Error occurs: Origin checking failed - null does not match any trusted origins I don't know why there is origin:null Already tried cors-headers set up -
Django : IsAuthenticated and TokenAuthentication decorated views getting accessed without any Authentication Token
I have used simple-jwt for JWT authentication in a simple To-Do app. For OTP based authentication i have created a custom user model and also overridden the TokenObtainPairSerializer from simple-jwt. My token urls are working fine but my get-todos view getting accessed without any authentication. Github Repo: https://github.com/ShouravAhmed/django-react-practice-code/tree/main/Django/djtodo following is my code snippets. //urls path('get-todos/', get_todos, name='get_todos'), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), //views.py @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) @api_view(['GET']) def get_todos(request): resp = {'status': 200, 'message': 'success'} try: todos = Todo.objects.all() serializer = TodoSerializer(todos, many=True) resp['count'] = len(serializer.data) resp['data'] = serializer.data except Exception as e: resp['status'] = 400 resp['message'] = 'Exception Occered' resp['exception'] = str(e) return Response(resp) // models.py class User(AbstractUser): id = models.CharField(max_length=15, default="") phone_number = models.CharField( max_length=15, unique=True, primary_key=True) full_name = models.CharField(max_length=73, blank=True, null=True) address = models.TextField(blank=True, null=True) total_purchase = models.IntegerField(default=0) points = models.IntegerField(default=0) visit_count = models.IntegerField(default=0) staff_level = models.IntegerField( choices=StaffLevel.choices, default=StaffLevel.USER) created_at = models.DateField(auto_now_add=True, editable=False) updated_at = models.DateField(auto_now=True, editable=False) is_phone_verified = models.BooleanField(default=False) username = models.CharField(max_length=30, null=True, blank=True) def save(self, *args, **kwargs): self.id = self.phone_number super(User, self).save(*args, **kwargs) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['full_name', 'email'] objects = UserManager() // manager.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('phone number is required') user = … -
Django first() for every item
Suppose I have a model EventParticipant, which stores participant data for a given Event. Now I want to retrieve the next event participance for a list of users. The following: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start) would give me all event participances for all users in userlist that start in the future. However, I only want the first one for each user. In Postgres, this could be achieved (I think) by this: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start).distinct('user'). However, this does not work for sqlite or mysql. Obviously, as shown here, this would work, but I suppose it'd be very slow: next_occurrence_ids = [] for user in userlist: id = EventParticipant.objects.filter(user=user, .....).order_by(start).values('id').first() next_occurrence_ids.append(id) return EventParticipant.objects.filter(id__in=next_occurrence_ids Is there any other strategy I could employ? -
ValueError in django python [closed]
ValueError: not enough values to unpack (expected 2, got 1) I'm getting this value error. Even i tried running server/make migrations by removing models also im getting same value error. Anyone help me to solve this error. -
Recover Bulk Deleted items in django framework
Is it possible to recover multiple deleted files in one go using django framework. If so, what are the ways? I tried latest file recovery, it worked. but not sure on multiple files recovery . I am using IDE as pycharm and django admin view. -
Timezone conversion failed due to winter hour change pytz
in my code I am trying to convert a date with pytz timezone, but due to the change to winter hour at 3 am, my code crash. I have two questions : one, why does changing hours makes the timezone conversion crash ? Two, how to avoid this bug ? Here is my code : purchase_date = make_aware( datetime.strptime( sale.findtext('n:purchasedate', namespaces={'n': ns}), '%d/%m/%Y-%H:%M' ), timezone('Europe/Paris') ) Error returned : Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ purchase_date = make_aware( ^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/timezone.py", line 287, in make_aware return timezone.localize(value, is_dst=is_dst) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pytz/tzinfo.py", line 366, in localize raise AmbiguousTimeError(dt) pytz.exceptions.AmbiguousTimeError: 2023-10-29 02:08:00 Knowing that my code was executed at 3:02 am and the change of hour happened at 3:00 am. Thanks in advance for any response ! -
Assert when ObjectDoesNotExitst is raise
I have this function which raises the ObjectDoesNotExist def is_user_login(self,id): try: u = m.CustomUser.objects.get(id=id) except ObjectDoesNotExist as e: raise e Now I am writing the test script. try: CommonFunc.is_user_login(4) except Exception as e: print(e) self.assertEqual(ObjectDoesNotExist,e) It doesn't work. It shows error like this below , AssertionError: <class 'django.core.exceptions.ObjectDoesNotExist'> != DoesNotExist('CustomUser matching query does not exist.') How can I assert for ObjectDoesNotEqual? -
Django models: have foreign keys in a class return different things
I have following in my django models file : class Category(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/cats', null=True, blank=True) def __str__(self): return self.name and I want to have foreign key to its name and its image separately like this : class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) category_image = models.ForeignKey(Category.image, on_delete=models.CASCADE, blank=True, null=True) how should I achieve this ? -
unable to access object's property despite it being present
My serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" def create(self, validated_data): try: print(validated_data) print(validated_data.author) task = Task.objects.create(**validated_data) return task except BaseException as e: print(e) raise HTTP_400_BAD_REQUEST my view: class TaskCreateApiView(generics.CreateAPIView): serializer_class = TaskSerializer my model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): content = models.CharField( default="", max_length=255, ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, ) category = models.CharField( default="", max_length=255, ) def __str__(self): return str(self.id) + self.content My log from serializer: {'content': 'test2', 'category': 'test', 'author': <User: zaq1>} 'dict' object has no attribute 'author' print(validated_data.author) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'author' How can I access author? I see it exists as <User:zaq1> but can't seem to access it -
Modifying DJANGO_SETTINGS_MODULE in environment variables
I've come across a very dumb yet irritating problem when running my Django server. When running the server it says: ModuleNotFoundError: No module named 'apolo_client.setting' I don't know where in hell I've set this variable to apolo_client.setting. Obviously it's supposed to be "settings" with as s at the end. I tried manually setting the variable in windows and even in python itself, but it doesn't work. I tried retrieving the variable in init.py file in django's conf folder and it says apolo_client.setting! However running os.environ anywhere else in windows gives the current output. Is there a way I could reset the value or maybe search for the bit where it's being set the wrong valule? -
Failure to display the output despite entering the codes
Despite entering the codes, no output is displayed in this field. What is the reason? in views.py: def category(request, category_id): category = get_object_or_404(Category, pk=category_id) products = category.product_set.all() return render(request, 'category.html', {'category': category, 'products': products}) in urls.py: path("category<int:category_id>", views.category, name="category") in category.html: {% extends "auctions/layout.html" %} {% block body %} <h2>{{ category.name }}</h2> <ul> {% for product in products %} <li>{{ product.category }}</li> {% endfor %} </ul> {% endblock %} in layout.html: <li class="nav-item"> {% for category in categories %} <a class="nav-link" href="{% url 'category' category.id %}">Category</a> {% endfor %} </li> -
Failure to register comments without login
Comments are registered on the desired page, and for people who aren't logged in, if they want to leave a comment, it says to enter the site first, but later the comments are registered under the name AnonymousUser. I don't want this registration to happen. Which part and how should be edited? in views.py: comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: author = request.user content = request.POST.get('content') comment = Comment(product=product, author=author, content=content) comment.save() context = { 'comments': comments, } return render(request, 'auctions/product_detail.html', context) in product_detail.html: <h3 id="h3">Comments</h3> {% if user.is_authenticated %} <ul> {% for comment in comments %} <li><a>{{ comment.author }} : {{comment.content}}</a></li> {% endfor %} </ul> {% else %} Not signed in. {% endif %} ` Thanks in advance for your help -
how to store checkboxes in database?
i want to make a website which can save the seats of the plane for a user but i am facing trouble storing these checkboxes in database and have no idea how to make it so that the checkboxes remain when i revisit the webpage with logged used this is my models.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my views.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my plane.html(shortened version) <!DOCTYPE html> <html> <head> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .a, .b { transform: scale(2.5); } .b { margin-left: 200px; /* Add margin between the two divs */ } /* Additional CSS to adjust the layout */ .a, .b { display: inline-block; } #sub { margin-bottom: -200px; } </style> </head> <body> <div class="container"> <form method="POST" action=""> {% csrf_token %} <div class="a"> <table> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> </tr> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> … -
How to get the "overall" counter of an object in a group in a Django template?
I'm using Django's regroup template tag to group a series of objects. Let's say these are the objects: cities = [ {"name": "Mumbai", "population": "19,000,000", "country": "India"}, {"name": "Calcutta", "population": "15,000,000", "country": "India"}, {"name": "New York", "population": "20,000,000", "country": "USA"}, {"name": "Chicago", "population": "7,000,000", "country": "USA"}, {"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, ] In my template, I'm grouping them like this: {% regroup cities by country as country_list %} <ul> {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for city in country.list %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> Which results in India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 I would like to show an "overall" index for each object, so that it looks like this: India 1: Mumbai: 19,000,000 2: Calcutta: 15,000,000 USA 3: New York: 20,000,000 4: Chicago: 7,000,000 Japan 5: Tokyo: 33,000,000 I'm not asking for an HTML solution; my use case is a series of grouped questions and I would like to add a question counter. Is there a way to do this in the template, or should I write the necessary code in my view? -
IntegrityError at /todo NOT NULL constraint failed: todo_todo.name i don't have a Foreign key only a name charfield
models.py from django.db import models # Create your models here. class ToDo(models.Model): name = models.CharField(max_length=200, default=" ") views.py from django.shortcuts import render, HttpResponse from .models import ToDo # Create your views here. def home(request): # temp = ToDo.objects.all() # context = {'temp':temp} data = request.POST.get('name') print(data) context = {'data':data} return render(request, "todo/home.html", context) def todo(request): # temp = ToDo.objects.all() # context = {'temp':temp} name = request.POST.get('name') todo = ToDo(name=name) todo.save() context = {'names' : todo} return render(request, "todo/todo.html", context) todo.html <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <h1>TO DO LIST</h1> <form method="post" action="/todo"> {% csrf_token %} <label for="name"> </label> <input type="text" name="name" id="name"> <br> <button type="submit">Add Task</button> </form> {% for x in names %} <h4>{{ x.name }}</h4> {% endfor %} </body> </html> I have tried changing name's and id's everything that was there in youtube but no solution I don't know where the error is occuring in the error page it shows todo.save() has the error but i don't know where the error is occuring at please help :( -
Django ORM, How to join a dropped table, with multiple conditions
class Post(Common): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() class Comment(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() class Test(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) tester = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category) class Category(Common): pass I want to find a query (Inner JOIN test ON Test.post _id = Comment.post _id AND Test.tester_id = Comment.author_id) to specify two conditions for the join syntax when executing the query based on the following Comment table, but I leave a question because it is hard to find.