Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to post data in django rest framework using ajax
I have an app that looks like a social network and I want to provide an option to post something in the user profile, but when I try to add a new post using ajax and django rest framework I always get a POST http://127.0.0.1:8000/api/post-list 500 (Internal Server Error) error. I have not found a solution to my problem in internet, please help. models.py class GreenLeafUserProfile(models.Model): id = models.PositiveIntegerField(primary_key=True, unique=True) profile_picture = models.ImageField(default='/pictures/default.png', upload_to='pictures') user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=63, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.user) + ' profile' class PostProfile(models.Model): author = models.ForeignKey(GreenLeafUserProfile, on_delete=models.CASCADE) post_text = models.TextField(max_length=5000) publication_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.author) + ' post owner ' + str(self.publication_date) + ' publication date' serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = PostProfile fields = '__all__' views.py class PostList(APIView): def get(self, request): posts = PostProfile.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) script for button in html file $('.add-new-post').on('click', function () { let postTextarea = $('#newPostText'); alert('clicked'); $.ajax({ type: "POST", url: "../api/post-list", data: JSON.stringify({ post_text: postTextarea.val(), id: postTextarea.attr('userId'), }), dataType: "json", beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, … -
What is a better approach, less code and more ForeignKeys or more code and columns?
I'm writing my first commercial Django app and I'm looking for some help as I'm stuck with changing and optimizing the models for quite some time. Right now I'm considering what is the better approach to creating models. Let's say I have few models that all have few fields in common (like name, city, address, post code). Can you tell me what is the better approach, repeat those few fields (columns) in every model (table) or just go for foreignkeys everywhere it fits and create an Address model even though those addresses will be of completely different things (people, institutions etc.) and I won't need them in one table. I understand the more foreignkeys I make the more queries the app will make every time it needs some info from those other tables? Is it even worth considering? The advantages I see are: less code not repeating myself and disadvantages: more queries for the same information? little bit more complicated to implement later bigger possibility of duplicated rows Thank you for you help. -
Use the current value of a textfield before submitting the django-form
Is there a way to use the value of a textfield related to the answer attribute from my yet unsubmitted form declared in a template as {{ form|crispy }} ? I want to, after clicking on a button, pass my form as a parameter to a method run I call inside the same template with {{ object|run:form }}. The problem is that the form is passed at the rendering of my template, and I can't send an updated version of my form after I have filled the textfield. @register.filter def run(self, form): print(form) I (obviously) get an empty text area, because the method was called before I click on the button: <tr> <th></th> <td> <textarea name="answer" cols="40" rows="10" class="textarea form-control" required id="id_answer"></textarea> </td> </tr> I want to invoke run(form) only after I click on the button with the updated form -
Django Localization: languages and models connection
The main idea of my project with localisation is show different content on all languages. I'm trying to use Django Internationalization and localization. Everything worked, except for one problem: If I post question (QA project) on polish language, my url is - site.com/pl/questions/question_123/ And same question is available on all others locales: Spanish - site.com/es/questions/question_123/ Norwegian - site.com/no/questions/question_123/ Is it possible to make question available only in the language in which it was posted? Models: class Language(models.Model): name = models.CharField(max_length=100, unique=True) code = models.CharField(max_length=20, unique=True) def __str__(self): return f'{self.name} ({self.code})' class Question(models.Model): """Main class for all questions""" is_active = models.BooleanField(default=False) language = models.ForeignKey(Language, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500) slug = models.SlugField(max_length=600, unique=True, blank=True) body = models.TextField(max_length=1000, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='question_category' ) tags = models.ManyToManyField(Tag, related_name='question_tags', blank=True) date_published = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) vote = models.ManyToManyField( Profile, blank=True, related_name='question_vote' ) user = models.ForeignKey( Profile, on_delete=models.CASCADE, blank=True, null=True ) class Meta: verbose_name = 'question' verbose_name_plural = 'questions' def get_absolute_url(self): return reverse('questions:detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.title) super().save(*args, **kwargs) @property def num_votes(self): return self.vote.all().count() def __str__(self): return self.title Views class QuestionDetailView(DetailView): model = Question def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['tags'] = … -
Passing data to the client who is not the one calling the post method
My question is mainly concerned with web programming(API) over HTTP methods. So, please consider sharing your knowledge regardless of your programming language —- even abstract answers could work for me. However, I am using django rest framework. The situation is that I wrote a post method in an APIview for the bank to redirect users after their payments(call_back_url) with some data for me to validate if the payment was successful. After validating I want to pass some data about this payment to the front-end client to show the user the receipt. I cannot pass json as Response to this request since the request is from the bank but I want to pass the json to the client. The only solution I could come up with is to redirect the user to another url with the data passed as query parameters in the url for the front-end client to read from. I really don’t like this approach and I want to pass the data as the body of request. Is there any other way? All in all, my question is: How can I pass processed data to another user within the same endpoint? -
Best idea to filter entry by distance
I have made a django model which stores longitude and latitude of a place. How do I filter out the entries which are within 10km of a given coordinates. I have a function which takes in 2 set of coordinates and gives distance. -
Django: How to dsplay quantity increment decrement widget forms using django existing form library
I have a file called "forms.py" in my django ecommerce project using this file I can display a below widget form for the users to select quantity. quantity1 But I want to display the widget form as given below in the image, so that i can increment or decrement the quantity rather than selecting the quantity from choice field. Please note i want to use the existing django form field for displaying the widget as given below. I do not want to use html here to design the widget quantity2 My code for the "forms.py" is given below. from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,coerce=int) update = forms.BooleanField(required=False,initial=False,widget=forms.HiddenInput) I am stuck here, any help would be really highly appreciated. -
SSL problem when sending email (_ssl.c:1108)
I want to send e-mails trough my own server (not gmail), and I set up everything according to a gmail-sample, but I always getting the same error: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1108) What could be the problem? And how can I fix this? I searched everywhere, but found just smtp.gmail examples... I tested them, and they worked. -
How can i make page for import CSV in django admin site without using model?
I need to make a page on the Django admin site to upload a CSV file. This file is not tied to one specific model. Data for several models will be taken from the file. Is there a clean way to do this? I've tried using "admin.AdminSite". But I couldn't find a way to register my view with the existing admin site. -
Django : Can't auto insert user ID into other form
I am trying to get user/customer info and copy it automatically to new model via custom form once requested but keep getting error. General overview as below. (error : ValueError at /create_request/ Cannot assign "<SimpleLazyObject: <User: kambing>>": "OrderRequest.user" must be a "Customer" instance.) model relationship between customer model and request model my views.py as below: from django.shortcuts import render, redirect from .models import * from accounts.models import * from .forms import CreateRequestForm from django.contrib.auth.decorators import login_required from accounts.models import * @login_required(login_url='login') def createRequest(request): form = CreateRequestForm() if request.method =='POST': form = CreateRequestForm(request.POST) if form.is_valid(): order = form.save(commit=False) order.user = request.user order.save() return redirect('/') context = {'form':form} return render(request, 'commerce_autoparts/request_form.html', context) I tried many solutions from stackoverflow but could not get it right. I am sorry if this not challenging question but I am stuck with this issue for some weeks. Some sort of guidance or reference available would be helpful. I hope shared info is enough for your references. Thank you -
MakeMigration Error on Django - ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models'
I got the following error after adding a new model field and running the makemigrations command: ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models' (/usr/local/lib/python3.7/site-packages/django/db/models/init.py) this is what my models.py looks like: import uuid from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) cover = models.ImageField(upload_to='covers/', blank=True) # New Field def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) class Review(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews') review = models.CharField(max_length=255) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.review This is the current state of my migrations files, I have two. 0001_initial.py # Generated by Django 3.0.8 on 2020-08-01 13:11 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('title', models.CharField(max_length=200)), ('author', models.CharField(max_length=200)), ('price', models.DecimalField(decimal_places=2, max_digits=6)), ], ), ] 0002_review.py # Generated by Django 3.0.8 on 2020-08-06 11:21 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('books', '0001_initial'), ] operations = [ migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('review', … -
Is there a way to test an application deployed with Zappa?
I have created a Django application which is deployed to AWS using Zappa in a CI/CD pipeline using the following commands: - zappa update $ENVIRONMENT - zappa manage $ENVIRONMENT "collectstatic --noinput" - zappa manage $ENVIRONMENT "migrate" However I want to add a test step to the CI/CD pipeline that would test the application much like in a way that I would test the application locally using the Django command: python manage.py test Is there a way to issue a zappa command to make run the "python manage.py test"? Do you have any suggestion? -
Django dynamic forms - validating Select field
I am using Django 2.2 I am creating a form dynamically, by reading a JSON definition file; the configuration file specifies the types of widgets, permitted values etc. I have come a bit unstuck with the Select widget however, because I prepend a '--' to the list of permitted values in the list (so that I will know when a user has not selected an item). This is the code snippet where the Select widget is created: class myForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ... elif widget_type_id == WIDGET_TYPE_DROPDOWN: CHOICES.insert(0,('-', INVALID_SELECTION)) form_field = CharField(label=the_label, widget=Select(choices=CHOICES),required=is_required) My problem is that when the is_valid() method is invoked on my form, any rendered Select widgets are are accepted as valid regardless of the selection. I want to implement code that has this logic (pseudocode below): def is_valid(self): for field_name, field in self.fields.items(): if isinstance(field.type, Select): if not field.required: continue else: if INVALID_SELECTION in field.selected_values: return False else: continue else: continue return super().is_valid() What would be the correct way to implement this functionality? For instance, how would I even get the selected values for the field (in the form code)? -
Django Docs Generator
I have a strange problem with Django Docs. I installed docutils, added all the required settings. Here is a docstring for a model in models.py: class Book(models.Model): """ Represents a book written by a :model:`Lib.Author`. """ This reference (:model:) works fine, so I can click on that link and navigate to the Author model which belongs to the Lib app. However, that kind of linking doesn't work in my views (in views.py): class AuthorListView(ListView): """ Displays a list of authors represented by :model:`Lib.Author`. """ Is there some kind of a silly restriction that such referencing won't work in views? That would sound strange to me. -
ModelForm Fields are not pre-populated with existing data during updating in Django
I want to update the User and Lab model. I am able to see the form but it is not pre-populated with existing database information even after setting the instance parameter. If I submit a blank form then all fields are reset to blank values in the database. I have tried several solutions available online but nothing works. My queries - How do I pre-populate my form with existing data? If the user doesnt fill out a particular field, I want the previous information to be stored as it is and not as a blank value. How do I achieve this? I have the following models.py class Lab(models.Model): uid = models.OneToOneField(User, on_delete=models.CASCADE) company=models.CharField(max_length=200,blank=True) @receiver(post_save, sender=User) def create_lab_profile(sender, instance, created, **kwargs): if created: Lab.objects.create(uid=instance) @receiver(post_save, sender=User) def save_lab_profile(sender, instance, **kwargs): instance.lab.save() Forms.py class UserForm(forms.ModelForm): email=forms.EmailField(max_length=300) class Meta: model = User fields = ('first_name', 'last_name', 'email',) class LabForm(forms.ModelForm): class Meta: model = Lab fields = ('company',) views.py @login_required def update_user_details(request,pk): if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) lab_form = LabForm(request.POST,instance=request.user.lab) if user_form.is_valid() and lab_form.is_valid(): user_form.save() lab_form.save() messages.success(request,'Your profile was successfully updated!') return redirect('user_details') else: messages.error(request,('Please correct the error below.')) else: user_form = UserForm(instance=request.user) lab_form = LabForm(instance=request.user.lab) return render(request, 'update_user_details.html', {'user_form': user_form,'lab_form': lab_form}) … -
AttributeError at collections.OrderedDict object has no attribute 'groups'
I've created an Agent Model that extends from the default Django User. The Agent model has an attribute Company. Now, at the moment of creating a new Agent, the company should be completed automatically if the user trying to add an Agent is in the Administrator's group. I've written some code but i keep getting the same error and i don't understand why. Here's the code: models.py class Agent(models.Model): class Meta: db_table = 'itw_agent' verbose_name = 'agent' verbose_name_plural = 'agents' user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) phone = models.IntegerField() deleted = models.BooleanField(default=False) company = models.ForeignKey(Company, related_name='agents', on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.deleted: self.user.is_active = False self.user.save() return super().save() serializers.py class AgentSerializer(ModelSerializer): user = UserSerializer() company_name = SerializerMethodField() class Meta: model = Agent fields = ['user_id', 'user', 'phone', 'company', 'company_name'] @staticmethod def get_company_name(obj): return obj.company.name def create(self, validated_data): # gr = Group.objects.get(name=AGENT) # users = User.objects.all() # for user in users: # user.groups.add(gr) user = validated_data.pop('user') new_user = User.objects.create(**user) new_user.set_password(user['password']) request_user = self.context['request'].user if ADMINISTRATOR in user.groups.all().values_list('name', flat=True): agent = Agent.objects.create(user=new_user, company=request_user.company, phone=validated_data['phone']) return agent else: return Response({'error'}, status=status.HTTP_401_UNAUTHORIZED) If i remove the condition to check if the user is in the Administrator's group or not, when i try to create … -
In Django {% if user.is_autenticated %} is not working
I made in Django a login system and it's not working the {% if user.is_autenticated %} method in html files. It always work as "not logged in", also when I'm logged in, I dont understand the problem. Can someone help me pease? Thanks for any help support This is my code: Views.py # Form Post class EditView(ListView): model = Article form_class = ArticleForm template_name = 'blog/form_post/index.html' ordering = ['-data'] class AddPostView (CreateView): # Create new Post model = Article form_class = ArticleForm template_name = 'blog/form_post/add_post.html' class EditPostView(UpdateView): # Edit a post model = Article form_class = ArticleForm template_name = 'blog/form_post/edit_post.html' class DeletePostView(DeleteView): model = Article template_name = 'blog/form_post/delete.html' success_url = reverse_lazy('EditHome') # Login def Slogin(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('EditHome') else: messages.info(request, 'Error') context = {} return render(request,'blog/form_post/Slogin.html' ) ... Html login File {% extends 'blog/form_post/layout.html' %} {% block title %} LogIn{% endblock title %} {% block content %} <form method="POST" action="" class=" form__group"> <h3 id="form-title" class="m-3 violet ">LOGIN</h3> {% csrf_token %} <input type="text" name="username" placeholder="Username..." class="w-75 m-3 border-top-0 border-left-0 border-right-0 bg-white"> <input type="password" name="password" placeholder="Password..." class="w-75 … -
How can i use 1 to 20 number inside [] " json()[' inside this '] "
here is my views.py from django.shortcuts import render import requests def home(request): data = True result = None globrep = None countries = None res = None ind = None city = None city1 = None while (data): try: result = requests.get("https://api.covid19api.com/summary") globrep = result.json()['Global'] countries = result.json()['Countries'] res = requests.get("https://api.covid19india.org/data.json") ind = res.json()['statewise'] city = requests.get("https://api.covidindiatracker.com/state_data.json").json()[0:20]['state'] city1 = requests.get("https://api.covidindiatracker.com/state_data.json").json()[0:20]['districtData'] data = False except: data = True return render(request, 'covid_app/home.html', {'globrep': globrep, 'countries': countries, 'ind': ind, 'city': city, 'city1': city1}) In this code i use json()[0:20)]['state'] but it is not working please suggest some way to use first o to 20 data of that API. and there is not index out of bound. This is my home.html , {% extends 'base.html' %} {% block content %} {{ city }}<br> <br> {% for i in city1 %} {{ i.name }}<br> {{ i.confirmed }}<br><br> {% endfor %} {% endblock content %} please suggest me how to get first 20 data from api using json() method ..... -
Filter datetime field python
Json receiving python: { "str_ini": "2020-06-05", "fnsh_date": "2020-06-20", } I use str_ini and fnsh_date as a parameter to build my query. OrderModel.py: fservice = models.DateTimeField(db_column='FService') # (In DB this field is datetime) ffinishservice = models.DateTimeField(db_column='FFinishService') # (In DB this field is datetime) Views.py: pedidoparams = request.data start_date = pedidoparams.get("str_ini") finish_date = pedidoparams.get("fnsh_date") order = ( OrderModel.objects.values("zone__zone") .filter(fservice__gte=fecha_inicio) .filter(ffinishservice__lte=fecha_final) .annotate(order_activate=Count("cctt__id")) ) print("query: ", str(pedidos.query)) And python print this query: query: SELECT `zone`.`Zone` AS `Zone`, COUNT(`order`.`cctt_id`) AS `order_activate` FROM `order` INNER JOIN `zone` ON (`order`.`Zone_Id` = `zone`.`Id`) WHERE (`order`.`fservice` >= 2020-06-05 00:00:00 AND `order`.`ffinishservice` <= 2020-06-20 00:00:00) GROUP BY `zone`.`Zone` My question is: why do you add hours, minutes and seconds to the query? In case of receiving only the dates, would it be possible that in the query it was: ... Where (`order`.`fservice` >= 2020-06-05 00:00:00 AND `order`.`ffinishservice` <= 2020-06-20 23:59:59) -
want to find duration of video and average rating per course in same as models page
how to find the average rating of the course and length of the video, wanna done in same model page class Course(DateTimeModel): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos') rating = models.FloatField(blank=True) def course_rating(self): rate = self.rating.aggregate(Avg('rating')) return rate['rating__avg'] -
Django has a built in recent activity in admin panal can we bring that recent activity in frontend?? If so how can we do it?
I was wondering to add this on my collage projects so. enter image description here -
Send email with private hosted email using Django
I'm using this email setting in settings.py EMAIL_BACKEND ="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "host45.axxesslocal.co.za" EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_HOST_USER = "admin_accinfo@thespecco.com" EMAIL_HOST_PASSWORD = "***********" hosted Email settings from the hosting provider. image view to send email @login_required def receive_message(request): if request.method == "POST": user = request.user message = request.POST.get("message") html_message = render_to_string('email_message.html',{"user":user,"email":user.email,"message":message}) full_message = strip_tags(html_message) send_mail("Message",full_message,EMAIL_HOST_USER,["manindermatharu63@gmail.com"],fail_silently=False,html_message=html_message) #messages.success(request,"Message has Sent") return HttpResponse("Success") else: return redirect("send_message") when I try to send an email this error occurs smtplib.SMTPAuthenticationError: (535, b'5.7.8 Error: authentication failed: UGFzc3dvcmQ6') But email and password are right. can anyone help what's the problem -
Django not saving files when uploaded
I'm trying to make a user upload a post where the user can upload Caption(NULL=False), an image(NULL=True) and a video file(NULL=True). When I'm trying to upload an image or a video, the django saves it to the database but not in the media folder that I made for the media files. It doesn't give me any error but when I visit the django admin panel and if I check my media file's URL. It gives me a 404, here's are the screenshots: Models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) caption = models.CharField(max_length=1000) image = models.FileField(upload_to='images/',null=True , blank=True) video = models.FileField(upload_to='videos/',null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.caption views.py: @login_required def savepost(request): user = request.user Post = post(user=user, caption=request.GET.get("usercaption"), image=request.GET.get("fileimg"), video=request.GET.get("filevid")) Post.save() return redirect('usersfeed') HTML Form: <form action="/savepost/" method="GET"> <input type="text" name="usercaption" placeholder="Write Something..." required> <div class="attach"> <input type="file" name="fileimg" id="fileimg" accept="image/*" class="inputfile"> <label for="fileimg"><i class="fal fa-image"></i> Image</label> <input type="file" name="filevid" id="filevid" accept="video/*" class="inputfile"> <label for="filevid"><i class="fal fa-video"></i> Video</label> <input type="file" name="file" class="inputfile"> <label for="file"><i class="fal fa-smile-beam"></i> Mood</label> <button type="submit">Upload</button> </div> </form> -
how to join two tables in Django raw query?
if request.method == 'GET': query = 'SELECT Fileds_name..... FROM table1 inner join table2 on table1.id = table2.id where table1.id =' product = models.objects.raw(query+str(pk)+';') data = {"products": list(product.values())} response = JsonResponse(data) return response Here i am getting error I am passing single models output is coming, But for joining two table more errors is coming, anyone have any idea how to use django models and join two tables and show the output in Json format. -
How to change value, name and placeholder of an input tag when an anchor tag is clicked using Javascript?
<div class="filter_search"> <button class="fas fa-filter circle-icon"></button> <ul> <li><a href="#">Events</a></li> <li><a href="#">Users</a></li> </ul> </div> The above code opens a drop down menu. When I click on Users, I want to change the following input tag's placeholder value to 'Search Users' and 'Search Events' when Events is clicked. Also I want to change the name and value also. Input form: <form method="GET"> <input id="searchBar" class="form-control" type="text" placeholder="Search Events" name="q_posts" value="{{ request.GET.q_posts }}"> <input type="submit" value="Search"> </form> CSS for opening the drop down menu: .filter_search ul{ position: absolute; color: #FFFFFF; background: #FFFFFF; box-shadow: 4px 4px 20px rgba(26, 60, 68, 0.09); border-radius: 10px; margin-top: 2px; padding: 6px; width: 120px; height: 65px; display: flex; justify-content: space-around; align-items: center; flex-direction: column; list-style: none; opacity: 0; pointer-events: none; transition: .1s ease; transform: translateY(10px); } .filter_search button:focus + ul{ opacity: 1; pointer-events: all; } Is it possible to do so?