Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include foregin key attribute in Elastic Search Django?
I have two models Products and VendorProducts model as follows : class Product(models.Model): brand = models.ForeignKey(BrandName,related_name="brand_products", on_delete=models.CASCADE) item_name_title = models.CharField(max_length=10000) class VendorProducts(BaseModel): product = models.ForeignKey(Product , on_delete=models.PROTECT , null=True ,related_name="vendor_products") vendor_selling_price = models.FloatField(default=0, null=True, blank=True) Now I want to add this VendorProduct model in ElasticSearch. And I have done something like this @registry.register_document class ProductDocument(Document): product = fields.ObjectField(properties={ "item_name_title" : fields.TextField()}) class Index: name = "vendor_products" class Django: model = VendorProducts fields = [ "id", ] related_models = [Product] def get_queryset(self): """Not mandatory but to improve performance we can select related in one SQL request""" return super(ProductDocument, self).get_queryset().select_related( 'product' ) First, this is how we add the foreign key model in Elastic search. Now the issue is I am not able to get any of the results. Although I can see the results in elastic search when I tryto access it by port 9200 I can see the search results. But when querying I am getting empty responses. This code I am using s = ProductDocument.search().query("match", description=search) -
Why Post has no field 'publish' as the app cache isn't ready yet so if this is an auto-created field, it won't be ready yet?
I am new to Django. I am doing a blogsite project. I am creating a datebase for the blog. But when I run the command 'python manage.py makemigrations blog', I get this error. The error is "FieldDoesNotExist(django.core.exceptions.FieldDoesNotExist: Post has no field named 'publish'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.)". This is my blog.models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']),] def __str__(self): return self. Title I don't know the problem. Can someone help me? -
ERROR : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm learning Django but I keep getting this error when I type : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I Have a Creating Superuser But I'm facing some Error till superuser run on Server. So, Give me A Solution of This Error. My models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone = models.CharField(max_length=10) cpassword = models.CharField(max_length=10) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ("email",) objects = CustomUserManager() -
Add to cart functionality using Django and HTMX
Hi can you please help me with this problem. I have this code: models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) class Cart(models.Model): products = models.ManyToManyField(Product, through='CartItem') @property def total_price(self): return sum(item.product.price * item.quantity for item in self.cartitem_set.all()) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Product, Cart, CartItem def product_list(request): products = Product.objects.all() # Retrieve or create a cart ID in the session cart_id = request.session.get('cart_id') cart, created = Cart.objects.get_or_create(id=cart_id) # Pass the cart items to the template context cart_items = CartItem.objects.filter(cart=cart) total_items_in_cart = sum(item.quantity for item in cart_items) total_price = cart.total_price for item in cart_items: item.subtotal = item.product.price * item.quantity context = {'products': products, 'cart_items': cart_items, 'total_items_in_cart': total_items_in_cart, 'total_price': total_price} return render(request, 'product_list.html', context ) def add_to_cart(request, product_id): product = get_object_or_404(Product, id=product_id) cart_id = request.session.get('cart_id') cart, created = Cart.objects.get_or_create(id=cart_id) # Check if the product is already in the cart cart_item, item_created = CartItem.objects.get_or_create(product=product, cart=cart) if not item_created: # If the product is already in the cart, update the quantity cart_item.quantity += 1 cart_item.save() # Update session with cart ID request.session['cart_id'] = cart.id request.session.save() return render (request, 'cart_items_partial.html') … -
DRF-Spectacular with django-split-settings: AssertionError: Incompatible AutoSchema to generate Swagger
I am encountering an error when utilizing django-split-settings (version 1.3.0) and drf-spectacular (version 0.27.1) in my Django project. The error occurs when attempting to access the Swagger UI endpoint at api/schema/swagger-ui/. Here is the error message: AssertionError: Incompatible AutoSchema used on View <class 'drf_spectacular.views.SpectacularAPIView'>. Is DRF's DEFAULT_SCHEMA_CLASS pointing to "drf_spectacular.openapi.AutoSchema" or any other drf-spectacular compatible AutoSchema? To provide further context, here's a breakdown of my project structure: my_project | |_apps | |_settings | |---components | |------drf.py | |---environments | |---__init__.py The content of drf.py and init.py is as follows REST_FRAMEWORK = { ### some settings "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } init.py content:: from split_settings.tools import include from my_project.settings.components.env import Environment _base_settings = ( # Load environment settings "components/env.py", # Here we should have the order because of dependencies "components/paths.py", "components/security.py", "components/apps.py", "components/middleware.py", # Load all other settings "components/*.py", # Select the right env: f"environments/{Environment}.py", ) # Include settings: include(*_base_settings) It's important to note that this error doesn't occur when using a single, traditional settings file in my Django project. Here's the relevant portion of my urls.py file for reference (just same as the drf-spectacular package): from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ # YOUR PATTERNS path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional … -
Debugging Django AJAX Cart Deletion: Items Not Updating on Removal
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
Filtering nested models using generic foreign keys in django
class Complaint(models.Model): complaint_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) user_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='complaint_user') user_id = models.PositiveIntegerField() user_object = GenericForeignKey('user_type', 'user_id') complaint_date = models.DateTimeField(auto_now_add=True) complaint_time = models.TimeField(auto_now_add=True) complaint_message = models.CharField(max_length=1000, editable=True) type_of_complaint = models.CharField(editable=True, default='public') status = models.CharField(editable=True, default='pending') complaint_title = models.CharField(max_length=100, editable=True) # Should be able to assign to multiple models such as Counsellor, ClassTeacher, HOD content_type = models.ForeignKey(to=ContentType, on_delete=models.CASCADE, related_name='complaint_owner') object_id = models.PositiveIntegerField() assigned_to = GenericForeignKey('content_type', 'object_id') escalated_to = models.ForeignKey(to=EscalationStructure, on_delete=models.CASCADE) I am trying to access a field in the user_object model, the is nested as user_object.user.username. I am accessing the username in this search vector def search(request): query = request.GET.get('query', '') vector = SearchVector('complaint_title', 'complaint_message', 'status', 'complaint_time', 'complaint_date', 'counsellor_complaints', 'user_object__user__username') results = Complaint.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank') return render(request, 'complaint_administration/view_complaints.html', {'complaints': results}) It throws an error saying Field 'user_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I'm not accessing a reverserelation right. I am accessing through the complaint it self ?? -
RelatedObjectDoesNotExist at /profile/social/add ProfileSocialMedia has no profile
I'm trying to use the clean method of a model in my project, but I get the error: RelatedObjectDoesNotExist at /profile/social/add ProfileSocialMedia has no profile. I've tried a lot of different things, but I still can't figure out what I'm doing wrong Another detail is that it works correctly until it reaches the limit, when it reaches the limit I wanted it to generate a raise forms.ValidationError, but in fact it generates this error on the django yellow screen Below is my code class ProfileSocialMedia(models.Model): profile = models.ForeignKey(Profile, related_name="medias", on_delete=models.CASCADE) social_media = models.ForeignKey(SocialMedia, on_delete=models.CASCADE, blank=False) identification = models.CharField("Identification", max_length=3000) def __str__(self): return f"Profile Owner: {self.profile.user.first_name} / Social Media: {self.social_media.name}" class Meta: verbose_name = 'Profile Social Media' verbose_name_plural = 'Profile Social Medias' def clean_social_media(self): if self.social_media is None: raise ValidationError("Por favor, selecione uma rede social") print(self.profile) def clean_identification(self): if self.social_media.is_link == False: validate_number(self.identification) else: validate_url(self.identification) def clean_socials(self): limit = 6 socials = self.profile.medias.all() if socials.count() >= limit: raise ValidationError("Você atingiu o limite(6) de redes socias que podem ser adicionadas, altere ou exclua uma rede social existente.") def clean(self): self.clean_identification() self.clean_social_media() self.clean_socials() def save(self, *args, **kwargs): if self.social_media.is_link: if not re.match(r'^https?://', self.identification): self.identification = f'https://{self.identification}' self.full_clean() super().save(*args, **kwargs) class AddSocialMediaForm(forms.ModelForm): social_media = … -
Django session is never authenticated even when user is logged in
I'm using Django REST framework with Django for backend, React for front end. I'm trying to make a GET request from my front-end to the get_user endpoint. However, even when I called login_user and confirmed that user_is_authenticated = true with that function when I call the get_user endpoint it always return false and I get an AnonymousUser. In my front end axios call I set withCredentials to true so everything should be working on the front end afaik. views.py file from django.contrib.auth import authenticate, login, logout from django.contrib.auth.hashers import make_password from rest_framework import serializers, status, permissions, status from rest_framework.decorators import api_view, authentication_classes from rest_framework.response import Response from users.serializers import UserSerializer from django.contrib.auth.models import User @api_view(['GET']) def get_user(request): print(request.user.is_authenticated) return Response(status=status.HTTP_200_OK) @api_view(['POST']) def register_user(request): match_username = User.objects.all().filter( username=request.data['username']) match_email = User.objects.all().filter(email=request.data['email']) serializer = UserSerializer(data=request.data) if serializer.is_valid() and not match_username and not match_email: user = User.objects.create(username=serializer.data['username'], password=make_password( serializer.data['password']), email=serializer.data['email']) user.save() send_register_email( serializer.data['username'], serializer.data['email']) return Response(status=status.HTTP_201_CREATED, data=UserSerializer(user).data) else: if match_username: return Response(status=status.HTTP_400_BAD_REQUEST, data='Username already exists') elif match_email: return Response(status=status.HTTP_400_BAD_REQUEST, data='Email already exists') else: return Response(status=status.HTTP_400_BAD_REQUEST, data="Invalid email") @api_view(['POST']) def login_user(request): username = User.objects.all().filter(username=request.data['username']) if not username: return Response(status=status.HTTP_400_BAD_REQUEST, data='Username not found') user = authenticate( username=request.data['username'], password=request.data['password']) if user is not None: login(request, user) … -
Django: How to get data from html? How to make a value of int increases overtime? How to stop a button from working when that value matches 100?
im working on a project of a web game with Django. The main idea is that the player has a continuous increasing infection meter. He would need to scan mutiple qr code (representing a location, like the game city hunt), to decrease his infection. If it reaches 100, he would become a zombie and a button will be blocked or hide. -To acheive this, I'm having some ideas but i don't know know exactly how i should implement it. Here are the challenges: 1.How to get data from html to my database?(I uses SQLite) -I want to recieve data from the html (the qrcode will turn into points (a -ve value) and i need to add that to the player To decrease his infection rate) 2.How to make a value of int increases overtime? I want to add an dynamicinfection attribute to the player,so that it increase through time(like the Enlightenment meter in Don't starve if you know what i mean lol ) . Should i mainly be coding the timer and the value in html and java script or I should code in python (django)instead? Where should i build the timer thing? 3.How to stop a button from working … -
View returning user as None
So, I'm creating a user confirmation system where a code is created, stored in the session and send through email I made some prints inside the view that is used to confirm the code and active the user, the code is this one: def activeThroughCode(request,): form = VerificationForm() if request.method == 'POST': form = VerificationForm(request.POST) if form.is_valid: entered_code = request.POST.get('verification_code') stored_code = request.session.get('verification_code') print("Entered Code:", entered_code) print("Stored Code:", stored_code) username = User.objects.get('username') if entered_code == stored_code: print(username) try: user = User.objects.get(username=username) user.is_active = True user.save() messages.success(request, f'Your account is active with success.') return redirect('login') except User.DoesNotExist: messages.error(request, 'Incorrect verification code.') return redirect('login') else: messages.error(request, f"It wasn't possible to confirm your email") return render(request, 'activate.html',{'form': form}) When digiting the code in my form, I can confirm through terminal the entered code and stored code are the same, and everything is ok until here but, for validating my user, I need, obviously, request the user to active and save it, but the result for username = User.objects.get('username') if entered_code == stored_code: print(username) is None. I'm 99% sure it's the only error, because my Exception is being printed to me, so it means the code confirmation is actually working any idea of what … -
django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found
There is full error: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['recipe/like/(?P[0-9]+)\Z'] I suspect there is some issue with post_if but I'm unable to point out exactly whats wrong. i really dont know what to do, i think i tried everything(. views.py: def LikeView(request, pk): post = get_object_or_404(models.Recipe, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('recipe-detail', args=[str(pk)])) templates: {% block content %} <form action="{% url 'like_post' post.pk %}" method = "POST"> {% csrf_token %} <form action="{% url 'like_post' post.pk %}" method="POST"> {% csrf_token %} {% if user.is_authenticated %} {% if liked %} <button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-danger btn-sm">Unlike</button> {% else %} <button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-primary btn-sm">Like</button> {% endif %} {% else %} <small><a href="{% url 'login' %}">Login</a> to like</small> {% endif %} - {{ total_likes }} Likes </form> models.py: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ingredients = models.ManyToManyField(Ingredient) likes = models.ManyToManyField(User, related_name='blog_posts') def get_absolute_url(self): return reverse("recipes-detail", kwargs={"pk": self.pk}) def total_likes(self): return self.likes.count() def __str__(self): return self.title -
AssertionError: 404 != 200 in django testing
I have test code, but it displays error: self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 class TestViews(TestCase): def setUp(self): self.client = Client() self.list_url = reverse('home') self.about_url = reverse('about', args=[1]) def test_index(self): response = self.client.get(self.list_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'job_app/index.html') def test_about(self): response = self.client.get(self.about_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'job_app/about.html') my url: path('about/<int:pk>/', views.about.as_view(), name='about'), view: class about(DetailView): model = JobsModel template_name = 'job_app/about.html' context_object_name = 'job' i dont know what to do -
Is it okay to use render partial a lot?
I have a main page called home.html which contains some widgets(Latest comments, banner ads, most popular content and ...) Instead of putting all widgets in the main view. I have isolated each widget using render partial. Does it make sense? for examle: {% render_partial 'Home.Component.CategoryBox' %} {% render_partial 'Home.Component.recentPost' %} is it true? -
I want to connect my Android app to an django rest api
The api is already built and I made the app in Kotlin API 21 with AndroidStudio (its basicly an register and login for users app for now) The problem is i couldn't find any sources to follow, so if you can give any sources (yt video or an articale) or directly a source code or smth that would be really helpfull. https://www.youtube.com/watch?v=RpNqI7RtJGY&t=4s The only source that i could find. -
Utilizing Poppler and Django in Digital Ocean App
I am having issues with Poppler playing nice with the DigitalOcean Apps. I have a Django Web App that I have built and I have an automation script that I want to run. This script takes the text file reads the file and then puts the contents into a db field for a user text search function. It will work on my local machine, but it will not run. I get a PDFInfoNotInstalledError. In researching that error it states that Poppler is not installed and will need to be installed. Digital Ocean will not let you do an apt install from the console. I created an aptfile to install poppler. I was asked by DO support to add it in the requirement.txt file. I did that and added the path to the $PATH variables. Still was getting the same error. Unsure on what to do next can someone help me with this issue? I have tried to add poppler to the server, I have tried adding a python package for poppler. I was expecting for this to be recognized so that the OCR tool could work. -
How to manually add a datetime input element to a Django template without using forms
I want to manually add datetime input elements to an HTML where needed, but as the targets should be dynamic, I cannot use forms. Is there a way to achieve this with JS? Something like this (or ways to achieve similar results): $('#my-target-div').djangoDatetime() Or $('#my-anchor-button').djangoDatetime({target: '#my-input-element'}) I want to also have Django's field buttons (like calendar, date picker, ...) be included. I saw Django's built-in DateTimeShortcuts.js, but I can't achieve what I plan. -
celery and gunicorn conflict in vps deploy
i want to deploy a django project but when i enter this command: gunicorn project.wsgi, i get this error [2024-03-17 08:39:59 -0400] [12173] [INFO] Starting gunicorn 20.0.4 [2024-03-17 08:39:59 -0400] [12173] [INFO] Listening at: http://127.0.0.1:8000 (12173) [2024-03-17 08:39:59 -0400] [12173] [INFO] Using worker: sync [2024-03-17 08:39:59 -0400] [12176] [INFO] Booting worker with pid: 12176 [2024-03-17 08:39:59 -0400] [12176] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 953, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/root/reg_project/registration/project/init.py", line 2, in … -
Empty Table after making my CHOICES in the model
I have this django model for category : class CategoryModel(models.Model): CATEGORY_CHOICES = [ ('first','hardware'), ('second','software'), ('third','network') ] category = models.CharField(max_length=15,null=False,blank=False,choices=CATEGORY_CHOICES) class Meta: db_table = 'categories_table' On the data base it creates the table but its empty , and i want it to have three instances of each choice i defiend in the CATEGORY_CHOICES I wanted to have like auto filled , without i manually create the instances -
Logical use of render partial
I have a main page called home.html which contains some widgets(Latest comments, banner ads, most popular content and ...) Instead of putting all widgets in the main view. I have isolated each widget using render partial. Does it make sense? {% render_partial 'Home.Component.CategoryBox' %} {% render_partial 'Home.Component.recentPost' %} -
Django don't save choice field
I try save choice field but for no reason field never save. I try create modelform and even in admin panel this field don't save. I want to give user option to choose when he want to get email recomendations. Maybe someone have idea whats wrong. I see documentation of django and still don't get why this don't save. My model: class Profile(models.Model): DAILYDIGEST = 'DAILY' WEEKLYDIGEST = 'WEEKLY' NONERECOMMENDATION = 'NONEREC' EMAILDIGEST = [ (NONERECOMMENDATION, 'Nie wysyłaj mi rekomendacji'), (DAILYDIGEST, 'Dzienne rekomendacje'), (WEEKLYDIGEST, 'Cotygodniowe rekomendacje'), ] [...] user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, verbose_name='Użytkownik') [...] emailrecommendation = models.CharField( verbose_name='Wybierz jak często chcesz otrzymywać rekomendacje', max_length=20, choices = EMAILDIGEST, default = WEEKLYDIGEST, ) Model form: class EmailRecommendations(ModelForm): class Meta: model = Profile fields = ['emailrecommendation'] View: def emailrecsettings(request): if request.method == 'POST': form = EmailRecommendations(instance=request.user.profile, data=request.POST) if form.is_valid(): formsave = form.save() print(formsave) else: form = EmailRecommendations(instance=request.user.profile) return render(request, 'profile/emailrecommendations.html', {'form': form}) -
prevent access to home page for anyone unless has username and password
I have made a project and i have faced some issue about Permissions and Authorization the problem I am facing is anyone can access to any page in my project without login by just copy and past the Url he can access to any page I want to stop that an let only the people who has user name and password get the permission this is my url.py `from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.signin, name = "signin"), path('login', views.index, name="index"), path('logout', views.signout, name="signout"), path('registration', views.registration, name="registration"), path('book/<int:id>', views.get_book, name="book"), path('books', views.get_books, name="books"), path('category/<int:id>', views.get_book_category, name="category"), path('writer/<int:id>', views.get_writer, name = "writer"), ]` this is my view.py `from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from .models import Category, Writer, Book, Review, Slider from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .forms import RegistrationForm, ReviewForm from django.http import HttpResponse def index(request): newpublished = Book.objects.order_by('-created')[:15] slide = Slider.objects.order_by('-created')[:3] context = { "newbooks":newpublished, "slide": slide } return render(request, 'store/index.html', context) def signin(request): if request.user.is_authenticated: return redirect('store:index') else: if request.method == "POST": user = request.POST.get('user') password = request.POST.get('pass') auth = authenticate(request, username=user, password=password) if … -
Trouble Deleting Items from Cart Using AJAX In Django
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
Django project with a RESTful API for user registration and login using Google or Apple OAuth
which backend parameter to add Internal Server Error: /accounts/google/login/callback/ Traceback (most recent call last): File "/home/zaibe/Desktop/project2/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/zaibe/Desktop/project2/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: api_google_oauth2_callback() missing 1 required positional argument: 'backend' [17/Mar/2024 06:39:23] "GET /accounts/google/login/callback/?code=4%2F0AeaYSHADSCseU_Nkg2BMLc5P8UpfRRqCJUNRIAyHrcW_tX4uQDpPADdj5rTJRS8v6siZHw&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent HTTP/1.1" 500 65562 from django.http import JsonResponse from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_exempt from .forms import UserRegistrationForm from .models import Profile from django.shortcuts import redirect from social_django.utils import psa import json from social_django.views import auth from django.views.generic import RedirectView from django.shortcuts import render def default_callback(request): return render(request, 'default_callback.html') @psa() def api_google_oauth2_login(request): backend = 'social_core.backends.google.GoogleOAuth2' return redirect('social:begin', backend=backend) @psa() def api_google_oauth2_callback(request): backend = 'social_core.backends.google.GoogleOAuth2' return auth(request, backend=backend) @csrf_exempt def api_user_login(request): if request.method == 'POST': # Retrieve raw JSON data from the request body data = json.loads(request.body) # Extract username and password from the JSON data username = data.get('username') password = data.get('password') if username is None or password is None: return JsonResponse({'error': 'Missing credentials'}, status=400) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return JsonResponse({'message': 'Authenticated successfully'}, status=200) else: return JsonResponse({'error': 'Invalid login'}, status=401) else: return JsonResponse({'error': 'Invalid request method'}, status=405) @csrf_exempt def api_user_register(request): if request.method == 'POST': form … -
How to set BinaryField to primary key in django?
In this code i have: IDChuyenBien = models.BinaryField(primary_key=True, max_length=8) But when i makemigrations and migrate have an error: _mysql.connection.query(self, query) django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'IDChuyenBien' used in key specification without a key length") Although I used max_length as above, I am using Django 4.2.9 connect to Mysql I followed the docs as follows: https://docs.djangoproject.com/en/4.2/ref/models/fields/ I have also tried to think of a few other ways but still do not have a solution, because it is required that the data transmitted is binary and will be saved directly to the database, and before that when I did not use the primary key, in mysql when migrating it was also LONGBLOB. Meanwhile t only needs BINARY type with 8 bytes or 10 bytes