Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
icontains and query with Umlaut
My Product database mostly consists of a number and a json field: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() The data attribute looks like: data = {"name": "Würfel", "price": 20, "name": "truffels", "price": 1.20, } Now the query: products = Product.objects.all() r = products.filter(Q(data__icontains = "ürf")) results in an empty query, while r = products.filter(Q(data__icontains = "fel")) gives back results - this happens for all Umlaute. How can I address this? -
Sort objects by the date they were added to the ManyToManyfield field - Django
I save the products in ManyToMany field that the user has favored in my web application. class LikedProductPackage(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) products = models.ManyToManyField(Product) I display my favorite products in the template user like this: {% for obj in liked_product_package_instance.products.all %} [...] {% endfor %} Is there any option to sort products by the date they were added to the LikedProductPackage.products field in the template or view without changing the of this function too much? -
Got AttributeError when attempting to get a value for field '' on serializer ''
I would like to be able to see the customers accounts. As you can see Accounts has foreign key to Customer. The idea is to be able to see the customer info with nested accounts objects, but it gives me a error Got AttributeError when attempting to get a value for field `accounts_items` on serializer `CustomerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Customer` instance. Original exception text was: 'Customer' object has no attribute 'Account'. so like this example where songs in the the artist object: ####MODELS#### class Account(models.Model): amount = models.FloatField(null=True) name = models.CharField(max_length=40) account_type = models.CharField(max_length=11, choices = ACCOUNT_TYPES) customer_id = models.ForeignKey(Customer, on_delete = models.CASCADE, default = None) bank_id = models.ForeignKey(Bank, on_delete = models.CASCADE, default = None) def __str__(self): return '{} {} {} {} {}'.format(self.amount, self.name, self.account_type, self.customer_id, self.bank_id) class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=40) phone = models.CharField(max_length=40) email = models.EmailField(max_length = 100) rank = models.CharField(max_length=11, choices = RANK_TYPES) bank_id = models.ForeignKey(Bank, on_delete = models.CASCADE, default = None) def __str__(self): return '{} {} {} {} {} {} {}'.format(self.id, self.first_name, self.last_name, self.phone, self.email, self.rank, self.bank_id) ###VIEW### class customer_page(generics.RetrieveUpdateDestroyAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer … -
/entrypoint.sh: line 8: syntax error: unexpected end of file
Docker project was created on Linux machine, I'm running windows and I can't get docker-compose up to work. I've read through Stackoverflow's answers and so far I've tried the following (none have worked): Using Visual Studio Code I saved as "LF" instead of CRLF Deleted the file entirely, created a new one using Visual Studio Code, typed the words Cut the entire file, pasted it in Notepad so that formatting gets cleared, copied and pasted back Added various forms of #!/bin/bash to the start of the entrypoint.sh At this point I'm not sure what else to try. Any ideas? -
Django Query Foreign Key and Many to many field
Struggling with Django query, need some help. So I would like to get data for 5 different variables, accounts_data = (only username), user_account_data = (name), country_data = (iso_code), category_data = (choice), permisisons_data = (permissions). All data of the models is connected with UserAccount table, so need to get data from other tables only for existing user_accounts Example of models: class Account(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=50) status = models.CharField(max_length=60) class UserAccount(models.Model): name= models.CharField(max_length=100) surname = models.CharField(max_length=100) category= models.ManyToManyField(Category) account = models.ForeignKey(Account) country = models.ForeignKey(Country) permissions = models.ForeignKey(Permissions) class Country(models.Model): iso_code = models.CharField(max_length=6) zip_code = models.CharField(max_length=10) class Category(models.Model): choice = models.CharField(max_length=12) connected_category = models.CharField(max_length=12) class Permissions(models.Model): permission = models.CharField(max_length=50) restriction = models.CharField(max_length=30) -
how to use javascript to make an animation on hover
Hey so I have a div which I want to animate when its being hovered over. at the moment it says 'logged in as username' but I want to make it so that when I hover over it (im using animate.style) the text fades to the right and a button saying sign out comes in its location where the person can click to sign out but if they hover out of the div for things to go back to the way they were with the same animation. but I get lots of bugs like, the text constantly changing and bugging out when moving mouse close to it. function loggedInHover() { let signin = document.getElementById("signin"); signin.classList.add("animate__animated", "animate__fadeOutRight"); setTimeout(function() { signin.style.display = "none"; signin.innerHTML = "Sign Out"; signin.style.display = "block"; signin.classList.remove("animate__fadeOutRight"); signin.classList.add("animate__animated", "animate__fadeInLeft"); }, 1000); } function loggedInOut() { let signin = document.getElementById("signin"); signin.classList.add("animate__animated", "animate__fadeOutRight"); signin.style.display = "none"; signin.innerHTML = "logged in as <strong class=\"h3\">{{ user.username }}</strong>"; signin.style.display = "block"; signin.classList.remove("animate__fadeOutRight"); signin.classList.add("animate__animated", "animate__fadeInLeft"); } -
Django - User model is not presented in Django AUTHENTICATION AND AUTHORIZATION, only Groups are presented
I have created ACCOUNTS app with 2 models in there. In admin.py i wrote @admin.register(Profile) class AccountsAdmin(admin.ModelAdmin): def username(self, obj): return obj.user.username @admin.register(User) class CategoryAdmin(admin.ModelAdmin): list_display = ('username', 'is_staff', 'is_superuser') def username(self, obj): return obj.user.username When i visit http://127.0.0.1:8000/admin/ i see ACCOUNTS with Profile and Users and AUTHENTICATION AND AUTHORIZATION where only Groups is presented. The real problem is that i cannot assign groups/permissions to my USERS Could you please help me to move my USER from ACCOUNTS administration to AUTHENTICATION AND AUTHORIZATION I expect to be able to assign groups and permissions to my users. When i create a Group it is assigned to ALL users in my DataBase. When i open a single user i see all User Permissions but i cannot assign anything to it. Thank you in advance. -
How to rename submitted file before upload to S3
I'm trying to create a website with Django where people can create recipes with a picture upload field. I have set the pictures to be uploaded to my S3 Bucket upon submission of the recipe creation form. However, right now, the picture gets uploaded to AWS with the its original file name. I want it to be renamed in the format recipe_id.extension before it is uploaded to AWS. I have a function in models.py (see below) that does the renaming operation for me. I just dont know how to process the filename through that function before uploading. In Models.py class Recipe(models.Model): # fields def rename_file(self, filename): upload_to = 'media/' ext = filename.split('.')[-1] if self.pk: filename = '{}.{}'.format(self.pk, ext) return os.path.join(upload_to, filename) def get_pk(self): return self.pk recipe_title = models.CharField(max_length=200) likes = models.PositiveIntegerField(default=0) pub_date = models.DateTimeField('date published') instructions = models.TextField(blank=True) author = models.CharField(max_length=200) picture = models.FileField(rename_file) in Views.py def new_recipe(request): r = Recipe(recipe_title=request.POST['title'], likes=0, pub_date=timezone.now(), instructions=request.POST['instructions'], author=request.user.username, picture=request.FILES['filename']) r.save() return render(request, 'wordofmouth/new_recipe.html', {'recipe': r}) in recipe creation template: {% load socialaccount %} <html> <body> {% include "navbar.html" %} <div style="text-align:center; margin-top: 8%;"> {% if user.is_authenticated %} <h1>Welcome Back <span style="color: #73bcf8">{{ user.username }}</span>!</h1> <p>The is the experiments page</p> <p>{{ "Submit a new … -
Translate Django group name
I am creating a Django application where users will have different possible groups to manage their permissions. I would like this application to be translatable in the future, but the group names are not translatable by default. How can I make this possible? I have thought about a few possible solutions, but I can't decide which one is best. Replace the template where the groups are displayed and translate the group names. Replace the group templates and change the __str__ method. Can you think of another solution? Which one do you think is the best? -
django-crontab works manually but not automatically
I hope i could get some help I have installed the django-crontab and created a cron task like the following inside of my cron.py inside my_django_app in django: import redis def hello(): redis.set("hello", "world") the above code works perfectly when I run python manage.py crontab run (cron hash)* and the key set successfully inside redis but the task doesn't run automatically have you had any similar experience? Note: I am using linux and python version 3.9 and django 3.2.3 -
NameError: name 'p' is not defined Python(Django)
I want to put the parameters from the database into a formula and it shows me an error like this. I want to solve it without global variables. Is this possible? How can I combine a parameter entered in the above function into the following function? BOT.PY ... ...; float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def p_first(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() p = Message.param1 print('Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Ajoyib, perimetr qabul qilindi!") msg = bot.send_message(message.chat.id, "<b>2. "Now secondside: "</b>", parse_mode="html") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Nice!") bot.register_next_step_handler(msg, p_first) def height(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param2=message.text ).save() h = Message.param2 print('Parameter (h) from:', chat_id) bot.send_message(message.chat.id, "Nice!" +f'{eval(str(p * h))} + ' is answer' else: msg = bot.send_message(message.chat.id, "Only number") bot.register_next_step_handler(msg, height) As a result: :( NameError: name 'p' is not defined MODELS.PY from django.db import models class Profile(models.Model): external_id = models.PositiveIntegerField( verbose_name='User ID', unique=True, ) name = models.TextField( verbose_name='User name', null=True, ) def str(self): return f'ID: {self.external_id} | Username: {self.name}' class Meta: verbose_name = … -
Moving object id parameter to consumers.py Django-Channels
I have a problem. The point is that I am making application with Django backend and React frontend. I wanted to make a websocket which allows to write in live-chat rooms. The problem is that I have no idea how to load dynamic a Room id. Ill try to explain. The point is that connect method from ChatConsumer class will load messages realted to room and send it by json to frontend. Ths is how it looks. class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) messages = Message.objects.filter(room=[HERE I NEED TO PUT ID OF ROOM]) data_ready_for_json =list( messages.values('room','body','user')) self.accept() self.send(text_data=json.dumps({ 'type':'chat', 'message': data_ready_for_json })) Iam trying to send this id from my views, where I have RoomRetrieveView built by generics.RetrieveAPIView. Here it is: class RoomRetrieveView(generics.RetrieveAPIView): queryset = Room.objects.all() permission_classes = (AllowAny,) serializer_class = RoomSerializer def get_serializer_context(self): context = super(RoomRetrieveView,self).get_serializer_context() context.update({'id' : self.get_object().id}) roomId = context['id'] return roomId I was trying to move this roomId variable from get_serializer_context to my consumers.py file but it wants me to put "self" attribute but I have no idea how to figure it out. I also tried to use get_object method but it also not working. I have no idea. I also … -
There is a way to manipulate queryset from model after fetching from data base?
I’m a new in Python Django and I’m trying to encrypt and decrypt specific data before inserting to database and after fetching. My motivation is to do this blind, Meaning that I want to do that automatically. My tables include foreign key. class person(BaseModel): bank_account = models.ForeignKey(BankAccount) For insert to database i override save method in BaseModel: class BaseModel(Model): def save(self, *args, **kwargs): if self.__name__ is "BankAccount": encrypt_model(self, encrypt) # save the model super(BaseModel, self).save(*args, **kwargs) and this is work fine. this save method call for each model inside the Person Model, i mean that if inside BankAcount model there is another Model with ForeignKey and this model should be also encrypted and i save Person model "save" method will call for each model inside so i can check if this modle should be encrypted. my problem is in the fetching data from data base, i tried to create Manager and override get_queryset method: class newManager(PolymorphicManager): def get_queryset(self): queryset = super().get_queryset() if self.__name__ is "BankAccount": decrypt_data(queryset) return queryset the problem with this approach is that this method "get_queryset" called only one time for model, for example: Peson.newManager.filter(id=6) get_queryset called only one time and self.__name__ not equal to BankAcount. i can … -
Force django page refresh coming from a react page
I impleted a "complex" form using django (which is one of the reasons why I couldn't do it with react, see thereafter). To access it the user first has to go through an index page written with react (to explain the purpose of the form filling). To go from the react to the django page I have the following button: <NavBtnLink to="/form_app/">Take the survey</NavBtnLink> with: import { Link as LinkR } from 'react-router-dom' export const NavBtnLink = styled(LinkR)` border-radius: 50px; background: #06beb6; ... ` So when I click on the button it redirect to the proper address. The problem is that the page remains blank. For the form to display, I need to refresh manually the page (using F5 or by cliking). I red different topics about similar issues but None of the solutions I found worked (eg: location.reload(true); or setting a dummy component={DummyComponent} in NavBtnLink...). Also all the topics were refering to the same issue from one plain react page to another (and not to a plain django page as mine). Would you have any ideas of what I could try as I am running out of idea. I just want a button on my react page to redirect … -
Visual Studio Code - Python Interpreter path does not work for me
as i already tried for hours by myself, i could not find out, what i am doing wrong. I am doing the Tutorial of Django on Youtube, which can be found on the following URL: https://www.youtube.com/watch?v=rHux0gMZ3Eg After craeting a virtual environment and starting a project in Virtual Studio Code, he tries to add the python path into the VSCode. In the video he is then able to use Python from the terminal inside the VSCode. However, around minute 19 you can find that in the video. If i do it by myself, nothing is happenning and i am also not able to use Python on the VSCode then. I did not figure out, what i am doing wrong, since i am exactly doing it like in the video. Does anyone have an idea, what i am doing wrong here? Thanks to anyone having an idea. Here are screenshots of what i have done for adding the path. enter image description here enter image description here enter image description here -
NOT NULL constraint failed: products_product.vendor_id django
so i recently changed my project user form to abstract base user and well my users can not add products or view their profile i know its problem in views.py and forms.py but whatever i change it too still has some probelm beside the error views.py rom django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserChangeForm from django.utils.text import slugify from django.shortcuts import render, redirect from .models import NewUser from products.models import Product from .forms import ProductForm from .forms import UserCreationForm # Create your views here. def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = NewUser.objects.create(user_name=user.first_name) return redirect('home') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required def vendor_admin(request): context = { 'user':request.user } vendor = request.user.user_name return render(request,'vendor/vendor_admin.html',{'vendor': vendor ,'context':context}) @login_required def add_house(request): if request.method == 'POST': form = ProductForm (request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) NewUser.user_name = request.user.user_name product.slug = slugify(product.عنوان) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request,'vendor/add_house.html',{'form': form}) class UserEditView(generic.UpdateView): models = NewUser form_class = UserChangeForm template_name = 'vendor/edit_profile.html' seccess_url = reverse_lazy('vendor_admin') def get_object(self): return self.request.user forms.py rom django.forms import ModelForm from products.models import Product from django import forms from django.contrib.auth.models import … -
Django: why does my custom filter not find an existing item in the array?
I am a beginner in Django. Right now i am working on my first project: reservation of sits for cinema event. The html map of sits is based on the array of cols and rows, provided from the Hall model. There is also an Invoice model, which stores the information about reserved places, based on this event. Based on this, i am trying to disable the html-map checkboxes of the sit places, which are already reserved. Here is my code: views.py def event_map(request, slug, event_id): selected_event = Event.objects.get(pk=event_id) movie = selected_event.film hall = selected_event.hall time = selected_event.get_time_slot_display() date_event = selected_event.get_week_day_display() sits = list(range(0, hall.hall_sits)) cols = list(range(0, hall.hall_cols)) hall_information = generate_hall_information(hall.hall_name) reserved_places = list() invoices = Invoice.objects.all().filter(event=selected_event) for invoice in invoices: reserved_places += invoice.invoice_details.split(',') reservation_form = Reservation() if request.method == 'POST': print(request.POST) form = Reservation(request.POST) if form.is_valid(): post = form.save(commit=False) post.invoice = request.user post.event = selected_event post.save() return render(request, 'pages/event_map.html', { 'movie_name': movie.name, 'hall': hall, 'time': time, 'date': date_event, 'sits': sits, 'cols': cols, 'hall_information': hall_information, 'reservation_form': reservation_form, 'reserved_places': reserved_places, 'test': reserved_places }) event-map.html <div class="theatre-map event-map-grid hall-{{ hall }}" id="theatre-map-target"> {% for sit in sits %} {% if sit|if_in_list:reserved_places %} <label class="res" id="{{ sit }}" disabled=""></label> {% else %} <label … -
Django - My list coming from a form collapses to a string when i call it
when i print the full request body its a list but when i reference it turns into a string with just the first value in the list def create_quiz_post(request): if request.method == 'POST': quiz = Quiz.objects.create(name=request.POST['name'], creator=request.user) Quiz.objects.get(id=quiz.id).topic.add(request.POST['topic_id']) print(request.POST) print(request.POST['question']) return redirect('/') OUTPUT 1 <QueryDict: {'name': ['2'], 'question': ['2', '2'], 'option1': ['', ''], 'option2': ['', ''], 'option3': ['', ''], 'option4': ['', ''], 'topic_id': ['1']}> OUTPUT 2 2 -
Celery in docker container first works for a while, then starts to timeout
Deploying the project, everything works. After an indefinite time, celery stops responding. Getting a gunicorn error: sys.exit(1) Tried run task.deploy() inside the django container and nothing happens in the celery container. There are no errors in the logs either in django container or in celery container. If I restart the Celery container, then everything works again for a while, then it starts timeout again. Docker containers: - django - celery - celerybeat django settings celery settings: CELERY_BROKER_URL = REDIS_URL CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py in django project: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YoungAI.settings') app = celery.Celery('YoungAI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() docker-compose: version: '3' services: redis: container_name: redis image: redis:4.0.2 restart: always networks: - youngai youngai-nginx: container_name: youngai-nginx image: youngai-nginx build: conf/nginx/ restart: always networks: - youngai - third_party_backend youngai-backend: container_name: youngai-backend image: $CONTAINER_BUILD_IMAGE restart: always env_file: /opt/.env-youngai build: . command: ./docker-entrypoint.sh volumes: networks: - youngai - third_party_backend youngai-celery: container_name: youngai-celery image: $CONTAINER_BUILD_IMAGE restart: always … -
Django - Href not redirecting user but being loaded locally
I am creating a simple application in django. I have an element, and when the user clicks on it, I want to be able to redirect them to a new page (classes.html). I used href="{% url 'classes' %}", but when the user clicks on it, nothing happens. However, I can see that the url has been loaded because the tag at the bottom screen loads the URL. Additionally, when I go to inspect the , I see that the URL has been loaded and when I click on it, it takes me to the classes URL. Can someone please help me so that when the user clicks on the , it redirects them to the classes screen? I have tried conducting a hard reload, re doing my URLS and views, and setting up a virtual enviorment, but nothing seems to work. -
django How do I solve a: NOT NULL constraint failed: accounts_user.group error?
Hi all I'm struggling to diagnose this error. I have looked through similar questions, however their's seem to be specific to ID's names etc. Im trying to create a new user when they fill out a register form. However when the form is submitted I get the following: " NOT NULL constraint failed: accounts_user.group " My code and the exact error i get is below, any help will be appreciated Form.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from .models import EmailActivation, GuestEmail, User User = get_user_model() class RegisterForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name','email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals if commit: user.save() return user Models.py from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.db … -
Django profile not being updated
Enabling my users to update their profile information. However, when I send new profile information, Django sends my back the profile information I had prior to updating. Simply put I would to receive updated profile information when I update a user profile along with a new access_token (I use the information to populate my profile). This is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() return instance urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), and my views.py: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['PUT']) def perform_update(self, serializer, pk=None): serializer.save(user=self.request.user.id) -
PAGINATION using class APIView in Django Rest Framework
I have try to paginate my data.. but this is not work , I'm still getting all data from DataBase this is views.py : class User_apiView(APIView): pagination_class=PageNumberPagination def get(self, request): user = User.objects.all() # pagination_class=PageNumberPagination serializer = TripSerializer(user, many = True) return Response(serializer.data) this is settings.py : REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } this the data I recieve in this url http://127.0.0.1:8000/api/users/?PAGE=4&PAGE_SIZE=1 HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, { "id": 115, "is_normaluser": null, "is_agency": null, "last_login": "2022-02-11T20:28:13.506519Z", "is_superuser": true, "first_name": "qaz", }, ] -
How i can ouput categiries in django on dpopdown in navbar?
Views, functions from categories def get_categories(request, cat_id): product = Product.objects.filter(cat_id=cat_id) cats = Category.objects.all() if len(product) == 0: raise Http404() context = { 'product': product, 'cats': cats, 'menu': menu, 'title': 'Отображение по категориям', 'cat_selected': cat_id, } return render(request, 'task1/get_category.html', context=context) Models with get_absolute_url class Category(models.Model): name = models.CharField(max_length=255, verbose_name='Категории') slug = models.SlugField(max_length=255, unique=True, verbose_name='URL', db_index=True) class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('сategory', kwargs={'cat_id': self.pk}) Urls.py path('category/', get_categories, name='category'), This is piece of code from base.html. Dpodown from navbar. <div class="collapse navbar-collapse" id="navbarNavDarkDropdown"> {% for c in cats %} <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Категории </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink"> <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> {% else %} <li><a class="dropdown-item" href="#">{{ c.name }}</a></li> </ul> {% endif %} </li> </ul> {% endfor %} </div> I'm really idk what to do, help me please I've tried, but i get mistake Navbar looks like, i have 4 categories and i get 4 columns in navbar -
How to make Whitelisted IPs won't be blocked and other IPs should be blocked if crosses the certain time in django rate limited?
@method_decorator(ratelimit(key='ip', rate='10/m', block=True), name="process_request") Class SomeMiddleware (object): def process_request(request): Pass I have ALLOWED_IPS = ["SOME IP"] in settings.py and i imported here. If any IPs matching with this list, they won't be blocked under this condition otherwise it does. How can I achieve this?