Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Coupon code not working for items in cart
I am trying to implement a coupon code feature in my Django e-commerce website. I have added the apply_coupon method to the Order model and a coupon field to the Order model, and I have also added a coupon_code parameter to the cart view function. However, when I test the coupon code by entering it in the cart page, nothing happens and the discount is not applied. I've included the relevant code snippets below. Can someone please help me understand why the coupon code is not working and how to fix it? views.py from django.shortcuts import render from django.http import JsonResponse from django.contrib import messages import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] coupon = Coupon(code='PERMANENT', discount=0.2, active=True, valid_until=None) coupon.save() # Kupon kodu işlevini ekleyin coupon_code = request.GET.get('coupon_code', None) if coupon_code: # Eğer bir sipariş nesnesi oluşturulmuşsa kupon uygulayın if hasattr(order, 'apply_coupon'): coupon_applied = order.apply_coupon(coupon_code) if not coupon_applied: messages.warning(request, 'Geçersiz veya etkin olmayan … -
Constructor can't set property value in Python class
I encounter strange behaviour in constructor of a python class: class MetricQuery(): query = None def __init__(self, query = None): self.query = query @classmethod def sum(self, field, response_field = None): self.es_query = basic_aggregation("sum", field, response_field) return self @classmethod def get(self): output = self.es_query if self.query != None: output["query"] = self.query["query"] return output Here's the test method for sum: def test_sum(): query = {"query": {"match": {"active": True}}} assert MetricQuery(query).sum("visits").get() == {"query": {"match": {"active": True}},"aggs": {"sum_visits_field": {"sum": {"field": "visits"}}}} Test fails, saying that right contains 1 more item, "query". It seems constructor can't set query value properly. What am I missing? -
Need support, Initially Django Search page is displaying all data, while i want to have only search text boxes and display data after user input
Views.py def advance_filter(request): user_list = SarnarLogs.objects.all() user_filter = UserFilter(request.GET) return render(request, 'advance_filter.html', {'filter': user_filter}) Template: Advance_filter.html <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.source.label_tag }} {% render_field filter.form.source class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.destination.label_tag }} {% render_field filter.form.destination class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.port.label_tag }} {% render_field filter.form.port class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.request_no.label_tag }} {% render_field filter.form.request_no class="searchfield" %} </div> </div> <button type="submit" class="btn btn-primary" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form><br> <div class="col-12"> <div class="card my-4"> <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2"> <div class="bg-gradient-primary shadow-primary border-radius-lg pt-4 pb-3"> <h6 class="text-white text-capitalize ps-3">HUB Requests</h6> </div> </div> <div class="card-body px-0 pb-2"> <div class="table-responsive p-0"> <table class="table align-items-center mb-0"> <thead> <tr> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">ID</th> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">SOURCE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">DESTINATION</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">PORT</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST TYPE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST_NO</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUESTER</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">START DATE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">EXPIRY DATE</th> <th class="text-center … -
How to 'check' a value in a radio button by default in Django?
I wrote a model form. I used widgets to make radio buttons and I want a particular radio button to be checked by default while rendering the form in my html file. Model: class Room(models.Model): class Meta: number = models.PositiveSmallIntegerField() CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.CharField(max_length=30) The following is my model form based on the above model. Form: class AddRoomForm(forms.ModelForm): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CATEGORIES), ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CAPACITY), ) class Meta: model = Room fields = ['number', 'category', 'capacity', 'advance'] Here is the views: def add_room(request): if request. Method == 'POST': form = AddRoomForm(request.POST) if form.is_valid(): room = Room(number=request.POST['number'], category=request.POST['category'], capacity=request.POST['capacity'], advance=request.POST['advance'], manager=request.user.username) room.save() # Implemented Post/Redirect/Get. return redirect('../rooms/') else: context = { 'form': form, 'username': request.user.username } return render(request, 'add_room.html', context) context = { 'form': AddRoomForm(), 'username': request.user.username } return render(request, 'add_room.html', context) I rendered the form like this in my … -
Deployment fails without prompting any errors on console on digitalocean app-engine django app
We have 2 apps that are running with similar settings, now we are trying to deploy another app but this time it's failing without telling any error in app engine. Python django app starts and then suddenly app engine stops deployment. How to find reason behind that? -
Django logging does not work inside views and viewsets
Can someone please help me understand why django does not print logging messages that I put inside views methods? When I call logger.debug() from outside views it works correctly my views.py import logging logger = logging.getLogger(__name__) logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS') class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated,) serializer_class = serializers.RequestGetResultSerializer queryset = Request.objects.all() def get_queryset(self):] logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') return self.queryset.filter(user=self.request.user.id) @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,)) def download(self, *args, **kwargs): logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') # working code here return response my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' , }, 'loggers': { 'django': { 'handlers': ['console'], }, } -
Hello everyone, help me write a test to Check if a post has been removed from the old group
You need to check that the post has disappeared from the old group page. You get our old band by its slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And you compare, что old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. You can check another new one, that there is 1 post there. Please help me write correctly) from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) I know what rubbish is written here (I'm just learning), this is what I was able to sketch)) -
Django: create_user_profile() missing 1 required positional argument: 'self'
I want to change the user's password. For this I use the following code user = User.objects.get(id=kwargs.get('user_id')) user.set_password(kwargs.get('password')) user.save() I get an error in response create_user_profile() missing 1 required positional argument: 'self' But I don't create a user. I checked, it finds the right user -
Styling prefilled Django radio input as buttons
I have a Django form field that is prefilled({form.clothingType}) and using widget gave it the attribute of class="closet-form-section form-clothing-type". The form is rendered out in html as <div id="id_clothingType" class="closet-form-section form-clothing-type"> <div> <label for="id_clothingType_0"><input type="radio" name="clothingType" value="11" class="closet-form-section form-clothing-type" required="" id="id_clothingType_0"> Accessory</label> </div> <div> <label for="id_clothingType_1"><input type="radio" name="clothingType" value="12" class="closet-form-section form-clothing-type" required="" id="id_clothingType_1"> Top</label> </div> <div> <label for="id_clothingType_2"><input type="radio" name="clothingType" value="13" class="closet-form-section form-clothing-type" required="" id="id_clothingType_2"> Outerwear</label> </div> <div> <label for="id_clothingType_3"><input type="radio" name="clothingType" value="14" class="closet-form-section form-clothing-type" required="" id="id_clothingType_3"> Bottom</label> </div> <div> <label for="id_clothingType_4"><input type="radio" name="clothingType" value="15" class="closet-form-section form-clothing-type" required="" id="id_clothingType_4" checked> Shoe</label> </div> </div> My question is how do I style the radio inputs as buttons such that it changes its background color when it is checked without changing the html (form template)? Is there an alternative solution via widget, views.py of even models.py? Thank you! The problem is that the input is within the labels, so I am unable use the conventional way of the input:checked + label to style the radio inputs. In this case the 5th radio button(Shoe) should have a different background color as the others. -
Docker/Django/Gunicorn/Nginx Websockets not connecting
Dockerized Django chat app using gunicorn, nginx for reverse proxy (static files). I managed to get stuck trying to get the websockets to work, but I can't connect to daphne: daphne -p 8001 project.asgi:application. The app only says, "Connection refusesed for upstream localhost:8001". I'm using django-channels and redis and on local everything is working fine. Am I missing something? Here are some files: nginx.conf upstream project { server web:8000; } upstream websocket { server localhost:8001; } server { listen 80; location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } } asgi.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack import scrumboard.routing application = ProtocolTypeRouter({ "http": django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py """ Django settings for project project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib … -
Script JS only working on HTML page , is there a way to make it work and include the path to HTML?
I have an issue where I have a html 'p' tags where it should applies a javascript function. It is an animated typing script , however it doesn't seems to be working. The script only works if I put it below the html 'P' tags. <link href="{% static 'js/animation.js' %}" rel="stylesheet"/> <!--test active type writing animation--> <div class="container-animation"> <p id="p_type">I'm <span class="typed-text"></span><span class="cursor">&nbsp;</span></p> </div> <!-- To check , how to implement the script in js file and why it isn't working and only working--> <script> const typedTextSpan = document.querySelector(".typed-text"); const cursorSpan = document.querySelector(".cursor"); const textArray = ["a Data Analyst", "a Developer", "Henry Dumont"]; const typingDelay = 100; const erasingDelay = 100; const newTextDelay = 2000; // Delay between current and next text let textArrayIndex = 0; let charIndex = 0; function type() { if (charIndex < textArray[textArrayIndex].length) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex); charIndex++; setTimeout(type, typingDelay); } else { cursorSpan.classList.remove("typing"); setTimeout(erase, newTextDelay); } } function erase() { if (charIndex > 0) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex-1); charIndex--; setTimeout(erase, erasingDelay); } else { cursorSpan.classList.remove("typing"); textArrayIndex++; if(textArrayIndex>=textArray.length) textArrayIndex=0; setTimeout(type, typingDelay + 1100); } } document.addEventListener("DOMContentLoaded", function() { // On DOM Load initiate the effect if(textArray.length) setTimeout(type, newTextDelay + 250); }); … -
Django rest framework - restricting user from granting himself permission
I have a django-program that has a few number of different permission levels. For example, I have a super-user, a doctor, an assistant and a patient. I have a class AssistantViewSet(ModelViewSet) which allows to change an assistant user. I just found out that an assistant might go directly to the link that corresponds to that ModelViewSet with method PUT (which is a resonable behavior as an assistant can change their own information), and change their permissions by sending a permission_list key with many permissions they shouldn't have. how can I make sure that an assistant will be able to change their information without having the ability to change their permissions? my code: class AssistantViewSet(ModelViewSet): serializer_class = AssistantSerializer queryset = Assistant.objects.all() permission_classes = [AssistantViewPerm, ] def get_queryset(self): assistants = Assistant.objects.filter(...) return assistants and the permission class: class AssistantViewPerm(BasePermission): def has_permission(self, request, view): action = view_action_map(request) try: if action == 'update': ... except: ... return checkBasicPerms(...) and checkViewPerm(...) -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one. Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py. Here is my Models.py for the chat application: from django.contrib.auth import get_user_model from django.conf import settings User = get_user_model() class TrackingModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal') users = models.ManyToManyField('users.User') objects = ThreadManager() def __str__(self) -> str: if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('users.User', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) def __str__(self) -> str: return f'From <Thread - {self.thread}>' And here is the Managers.py file: User = get_user_model() … -
Not use Django static files
I am quite new to Django, and I hope my question is not too silly. I am currently running my project locally, and each time I do an API call with the browser, I see the server log something similar: my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/css/default.css HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/jquery-3.5.1.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 404 179 There are a tons of static files that are served via the API. If I do the same with Postman or similar, here is the log: my_table | [08/Jan/2023 20:25:12] "GET /api/v1/category/ HTTP/1.1" 200 2 It looks like it only sends the response I wanted, via JSON or whatever. I was wandering if there is a way to prevent Django from serving static files at all, since I will only use the Rest Framework, or maybe gRPC in the future, but never static files. I tried to delete the static file constant from settings, and then nothing … -
Use node module in django
I'm trying to use nodejs modules (lodash) inside of my Django app but nothing happen. The architecture is as follow: - myproject - dist - myapp - templates - index.html - apps.py - views.py - ... - myproject - settings.py - urls.py - ... - nodes_module - static - js - script.js - manage.py - package.json I edited my settings.py so nodes_module/ is considered as static: STATIC_URL = "/static/" STATIC_ROOT = 'dist/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ('node_modules', os.path.join(BASE_DIR, 'node_modules/')), ) And here is the content of my index.html: hello <div id="result"></div> <script>console.log("yolo")</script> <!-- This should write "2 4 6 8 10" on console and page but doesn't --> {% load static %} <script src="{% static 'node_modules/lodash/lodash.js' %}"> import _ from 'lodash'; console.log("yolo2") const array = [1, 2, 3, 4, 5]; const doubled = _.map(array, function(n) {return n * 2;}); const resultElement = document.getElementById('result'); resultElement.innerHTML = doubled; console.log(doubled); </script> I got a lot of errors while trying but now, with this architecture and code, I don't have errors anymore but nothing appear on my page except the "hello". For some reasons, the first console.log("yolo") does appear on the console but not the second one console.log("yolo2"). It's like it never went … -
How can I add related models on the form at the same time?
I need your help with something. I'm new to the software field. I would like to consult you on an issue that I am stuck with. I don't know much about Django docs. My English is not very good. My problem is that I have two models, Boat model and Features model, I assigned a foreignkey to the features model and associated it with the boat model. I created two forms for these models. Features Model Boat Model BoatForm FeaturesForm I need to save the form at the same time in the views, but I can't assign the foreign key. In summary, while adding a new boat, I need to save its features at the same time. Sorry if the English pronunciations are wrong. -
How to check if a model is an intermediate model
Taking the example in the docs, I'm trying to check if a model is an intermediate model. from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) So a function like this, that takes a model as input and returns true if the model is an intermediate model and false otherwise. def is_intermediate(model): pass # is_intermediate(Person) -> False # is_intermediate(Group) -> False # is_intermediate(Membership) -> True I believe Django REST Framework has a way of doing this with the has_through_model attribute. Looking at that, I wrote this: def is_intermediate(model): for field in model._meta.get_fields(): if field.is_relation: for related_field in field.related_model._meta.get_fields(): through = getattr(related_field.remote_field, "through", None) if through and not through._meta.auto_created and through == model._meta.model: return True return False And it works. But to me, this sounds entirely inefficient. Is there a more performant way of finding if a model is intermediate? -
Django custom user profile image not saving properly
I've got a custom user model that when the image is updated it adds characters to the file path making django unable to find the new updated profile image. MODELS.PY from django.db import models from django.contrib.auth.models import AbstractUser from PIL import Image from django.conf import settings import os class CustomUser(AbstractUser): username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) email = models.EmailField(unique=True) # Add any additional fields you want to store about users, such as their profile picture, etc. image = models.ImageField(default='default.png', upload_to='profile_pics', null=True, blank=True) def save(self, *args, **kwargs): # Check if the image field has changed if self.pk: orig = CustomUser.objects.get(pk=self.pk) if orig.image != self.image: # Delete the previous image file if orig.image: orig.image.delete(save=False) # Create a thumbnail image if self.image: try: image = Image.open(self.image) except FileNotFoundError: print("Image file not found:", self.image.path) return image.thumbnail((200, 200), Image.ANTIALIAS) # Save the image to the correct path image_path = os.path.join( settings.MEDIA_ROOT, self.image.field.upload_to, self.image.name) image.save(image_path) super().save(*args, **kwargs) Views.py class UserPostListView(ListView): model = Post template_name = 'gorl/user_posts.html' context_object_name = 'posts' # paginate_by = 5 def get_queryset(self): user = get_object_or_404( CustomUser, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = get_object_or_404( CustomUser, username=self.kwargs.get('username')) context['user'] = user context['show_profile_settings'] = self.request.user.username == user.username context['comments'] = Comment.objects.all() total_likes … -
Ktor client - CSRF post request
I am doing a project where I am using django for server and ktor client for jetpack compose application to make request.However the CSRF protection reject my login request(An unsafe post request). As django has a built-in CSRF protection middleware, when I am testing the login post request with localhost, the server return Forbidden (CSRF cookie not set.): /user/login/ to the client and the login function cannot work. I tried to search for some documents and solutions to disable CSRF check (@csrf_exempt) but they are not working for me.I have added the CSRF_TRUSTED_ORIGINS in setting.py as the following(To be honest I don't know if these works or not): CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://*.127.0.0.1:*', 'http://10.0.2.2', 'http://127.0.0.1', 'https://127.0.0.1', 'https://127.0.0.1:*', 'https://127.0.0.1:', ] I have also tried to disable the middleware but not work. Is there any way that I can use ktor client to satisfy the CSRF thing from django?? Or what else should I do if that is not possible. Thank you for any answer. -
There is no cookie at all in my Next.Js frontend
I am super newbie on programming. I made Django Backend. and Next.js Frontend There is cookie which has _ga, csrftoken when I tested on local server 127.0.0.1 BUT, there is no cookie at all on my production. (production:which has different domain backend and frontend). I guessed that everything happened because I used different domain when production (just guess... I don't know it clear) here is some django settings.py i have ALLOWED_HOSTS = [ "127.0.0.1", "localhost", "BACKENDURL", "FRONTENDURL", "*.FRONTENDURL", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000", "http://localhost:3000", "https://*.frontendURL", "https://FRONTENDURL", ] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True I've searched all over the internet world. Please help me out from this hell... :-( -
Error "ImproperlyConfigured at /dj-rest-auth/login/" in use "dj_rest_auth"
I Want Use packeage 'dj_rest_auth' in django-rest-framework for login but get error: ImproperlyConfigured at /dj-rest-auth/login/ No default throttle rate set for 'dj_rest_auth' scope In setting.py File: INSTALLED_APPS = [ ... # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'dj_rest_auth', # local ... ] REST_USE_JWT = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':[ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.AllowAny' ], 'DEFAULT_RENDERER_CLASSES':[ 'rest_framework.renderers.JSONRenderer' ], 'DEFAULT_THROTTLE_CLASSES':[ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', ], 'DEFAULT_THROTTLE_RATES':{ 'anon':'50/hour', 'user':'200/hour', 'register':'5/hour', 'ref_token':'5/minute', 'create_article':'5/minute', } } And url.py: urlpatterns = [ ... path('dj-rest-auth/',include('dj_rest_auth.urls')), ] -
Django Taggit Filtering Invalid for Icontains
I have a model that contains a tags field using the Django Taggit library. I am currently trying to use a search bar to see if any items contains the same tag such as "Savoury" "Sweet" etc. However i am getting the error "Related Field got invalid lookup: icontains" and im not sure why. I have doubled checked the value in the post request from the search bar and it matches so the problem lies in the filtering using icontains. Here is my code: models.py `class Food(models.Model): name = models.CharField(max_length=100) tags = TaggableManager()` views.py class SearchFood(TemplateView): ... def post(self, request): result = request.POST['search_result'] if Food.objects.filter(tags__icontains=result): object = Food.objects.filter(tags__icontains=result) ... Im not sure why this doesnt work as i have tried searching for the food name using icontains and it works perfectly. However doing it with Django Taggit i get errors. Any help would be appreciated. -
NoReverseMatch at / Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I'm working on my Django blog. I was working on a registration form, everything it was working until I tested it and redirection was not working properly. Trying to fix errors, I got this message django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. blog/urls.py from . import views from django.urls import path app_name = 'my_blog' urlpatterns = [ path('', views.home, name='home'), path('post/<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), path('login/', views.login_request, name='login'), ] views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("my_blog:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("my_blog:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) In home.html I used "{{ post.get_absolute_url }}", and now this is error when I try to reload page, I have no idea why this is happening. … -
Django postgres "No migrations to apply" troubleshoot
I had to modify the table of my app so I dropped it from postgres database (using objectname.objects.all().delete() in django python shell and with postgres at PGAdmin). I deleted the appname migrations folder. When I run python manage.py makemigrations appname, the folder migrations gets created with a 0001_initial.py creating the tables. When I run python manage.py migrate appname, nothing happens and I cannot see the tables in postgres PGAdmin. (website) C:\Users\Folder>python manage.py makemigrations appname Migrations for 'appname': food\migrations\0001_initial.py - Create model Table1 - Create model Table2 - Create index Table2_search__7dd784_gin on field(s) search_vector of model Table2 (website) C:\Users\Folder>python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, appname, sessions Running migrations: No migrations to apply. When I deleted the folder migrations I can see the migrations are gone with python manage.py showmigrations. I also tried python manage.py migrate --run-syncdb but still no result. (website) C:\Users\Folder>python manage.py migrate --run-syncdb Operations to perform: Synchronize unmigrated apps: messages, postgres, staticfiles Apply all migrations: accounts, admin, auth, contenttypes, appname, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Any other idea on what may be happening and how to get the tables in postgres … -
How to change representation while keeping field editable in DRF?
I have two classes: class ClassA(models.Model): name = models.Charfield(...) tags = models.ManyToManyField("TagClass", blank=True) class TagClass(models.Model): tag_name = models.Charfield(...) def __str__(self): return f"{self.tag_name}" And then I serialize like so: # serializers.py class ClassASerializer(serializers.ModelSerializer): class Meta: model = ClassA fields = "__all__" class TagClassSerializer(serializers.ModelSerializer): class Meta: model = TagClass fields = "__all__" So when I create a tag say "red", it has ID=1, and I link it to a ClassA object, in the ClassA's object representation it shows this : { "id": 1, "name": "Some name", "tags": [ 1 ], } Instead I'd like it to display like so : { "id": 1, "name": "Some name", "tags": [ "red", ], } I've seen the StringRelatedField but it makes editing the tags field disabled (read-only). Is there a way to proceed to have the String repr but staying editable?