Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
payment status last page displaying -Django
working on payments to my web application and i m facing problem in displaying in the last page after the transaction happens i m able to re-direct to my local page (after transaction) but i m trying to display some of the response in the last page like his/her name, transaction status,and transaction id,and orderid but i couldn't retrieve data from views.py in "postdict"(list of items) below is my source code plz i need some suggestions what i need to do i have tried jinja code etc but couldn't get the data in the final page transaction {"status": 1, "url": "http://localhost:8000/response/", "data": {"name_on_card": "NA", "bank_ref_num": "499.0", "udf3": "", "hash": "8a6277714805380124ddd954797e009fb579be9a5900c645ce015ea61c3acd0acae0c22e37357e823b3f272b5eeb2563e1d253f34d57afe516cfa45a52918361", "firstname": "sai", "net_amount_debit": "499.0", "payment_source": "Easebuzz", "surl": "http://localhost:8000/response/", "error_Message": "PGS10001-Success", "issuing_bank": "NA", "cardCategory": "NA", "phone": "1234567890", "easepayid": "TFJ9DQGI15", "cardnum": "NA", "key": "TOXNUO0ICS", "udf8": "", "unmappedstatus": "NA", "PG_TYPE": "NA", "addedon": "2019-11-26 05:12:59", "cash_back_percentage": "50.0", "status": "success", "udf1": "", "merchant_logo": "NA", "udf6": "", "udf10": "", "txnid": "6b2058x9a", "productinfo": "web integration", "furl": "http://localhost:8000/response/", "card_type": "INR", "amount": "499.0", "udf2": "", "udf5": "", "mode": "NA", "udf7": "", "error": "NA", "udf9": "", "bankcode": "NA", "deduction_percentage": "2.00", "email": "sai2@gmail.com", "udf4": ""}} name: views.py -
Django: Extract not working with DateTimeField
The Extract function of Django ORM returns None after annotation if I use DateTimeField. Why?? models.py class SimpleModel(models.Model): date = models.DateField() datetime = models.DateTimeField() settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdb', 'USER': 'root', 'PASSWORD': 'password', } } Django shell output [connected to MYSQL] In [5]: from django.db.models.functions import Extract In [6]: annotate_kwargs = dict(month_from_datetime_field=Extract('datetime','month'),month_from_date_field=Extract('date','month')) In [7]: SimpleModel.objects.annotate(**annotate_kwargs)[0].__dict__ Out[7]: {'_state': <django.db.models.base.ModelState at 0x7fbb8ffb3eb8>, 'id': 1, 'date': datetime.date(2019, 11, 26), 'datetime': datetime.datetime(2019, 11, 26, 6, 9, 14, tzinfo=<UTC>), 'month_from_datetime_field': None, 'month_from_date_field': 11} -
django core.mail.send_mail works fine but EmailMessage.send fails
Trying to send email with a 'reply-to' option as below. msg = EmailMessage( subject='title/subject', body='<h1>h1 text</h1><h2>h2 text</h2>', from_email='FROM-ADDR', to=['TO-ADDRESS',], reply_to=['RE-TO-ADDR',], ) msg.content_subtype='html' msg.send() It gives SMTPDataError at /send_mail (550, b'Request failed; Mailbox unavailable') However, if I just use django.core.mail.send_mail, it works fine as below. to = ['TO-ADDRESS',] from_email = 'FROM-ADDR' subject= 'subject' text = 'SOME TEXT' html_message = '<h1>abc</h1>' mail.send_mail(subject, text, from_email, to, html_message=html_message) -
can I generate a circular qr-code like a messenger or a kik code in python
can i generate QR-code in circular shape on python like Facebook messenger or kik code used.i am visit many site but i am didn't get that type of Qr-code. -
Pass URL parameter to form value Django
I'm trying to set the value of a form input to the url, then redirecting to another page with another form using the information in the url parameter and passing another value of another input to the url. Let's say that my url is page1/value1/page2/value2 Where value1 comes from the first form and value2 from the second form in the second page. Using this code I can get the first value in the url, but somehow I can't save the form information to the database and set the other value in the url. class Acceso(FormView): template_name = 'codigo_zona.html' form_class = AccesoForm def form_valid(self, form): zona_code = form.cleaned_data.get('codigo_acceso') return redirect('registro', zona_code) class AccesoDetails(View): def get(self, request, zona_code): zona = Zona.objects.filter(codigo_acceso=zona_code).first() if request.method == 'POST': zona_id = zona.pk range_start = 10 ** (6 - 1) range_end = (10 ** 6) - 1 access_code = randint(range_start, range_end) form = RegistroResidenteForm(request.POST) if form.is_valid(): registro_residente = form.save(commit=False) registro_residente.zona_residencial.pk = zona_id registro_residente.codigo_acceso = access_code registro_residente.status_activacion = False registro_residente.save() else: form = RegistroResidenteForm() context = { 'zona': zona, 'form': form } return render(request, 'registro_residentes.html', context) I get the error Method not allowed (Post): HTTP/1.1 405 0 when submiting the second form, so I never see the second … -
'workon' is not recognized as an internal or external command, operable program or batch file
I had created a virtual environment named test on cmd and then tried to call it on vscode terminal then it is showing: 'workon' is not recognized as an internal or external command, operable program or batch file. What should I do? Thanks in advance -
How to support STRING_AGG in django queryset for sql server 2017
I tried to return the queryset with one field which is the list string in django, for example, like this: Name Ids Chicken Wing 2529,2695,10829,10995,12129,12295 I only know how to get the queryset by GROUP_CONCAT which support mysql database, when I migrated to sql server 2017 database. It doesn't work, I checked SQL SERVER 2017 support STRING_AGG, but I don't know how to use it in django.(I am using django rest framework) Anyone can help me? Thanks -
Django ORM - Fetch Multiple select_related having OneToOneField
My models structure is similar to this. class Block(models.Model): TYPE_CHOICES = ( ('text', "TEXT"), ('image', "IMAGE"), ) // I have around 10 types type = models.CharField(max_length=8, choices=) class User(models.Model): current_block = models.ForeignKey(Block, on_delete=models.CASCADE) class TextBlock(models.Model): block = models.OneToOneField(Block, on_delete=models.CASCADE, related_name='text', primary_key=True) class ImageBlock(models.Model): block = models.OneToOneField(Block, on_delete=models.CASCADE, related_name='image', primary_key=True) So, if I wanted to get the current_block of customer in a select related phrase, I use Customer.objects.select_related('block', 'block__text', 'block__image'). I have 10 block types similar to text and image, so my select_related clause is pretty big. Is there any way to get all the blocks? -
Django redirect user after successful registration not working
I am new to django and building a registration system. When user registers successfully, it redirects to thesame registration page instead of home. views.py def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') saved_user = form.save() saved_user.set_password(password) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("home") else: for msg in form.error_messages: print(form.error_messages[msg]) return render(request=request, template_name="registration/register.html", context={"form": form}) form = UserCreationForm return render(request=request, template_name="registration/register.html", context={"form": form}) register.html {% extends 'base.html' %} {% block title %}Register{% endblock %} {% block content %} <div style="text-align:center"><h2>Register</h2></div> <div style="text-align:center"> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Register"> </form> <p> If you already have an account <a href="/login" target="blank"><strong>login</strong></a> </p> </div> {% endblock %} urls.py urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('register', views.register, name='register'), ] -
How to deploy my python image recognition project to a cloud web server?
Hello stack overflow i am a bit new to cloud based webapps, my apologies if this question is very noobish. I have built a facial recognition in python Using Open CV and for UI i used tinkler. I know for web apps i need to use any framework like Django,but i I would like to know if i would be able to deploy this app directly into any cloud server like Microsoft Azure or AWS or Google Cloud and access my webapp from the browser. If yes then please let me know briefly how can i achieve that. Thanks in advance. -
What is the correct way of generating authorization token in django?
I'm trying to generate auth token in my django project.When i inspect source code of django-rest framework, they seem to generate auth_token using:- binascii.hexlify(os.urandom(20)).decode() but auth_token should be unique so that i can find corresponding user from auth_token.What is the best possible way of generating auth token, uuid or same as that of drf framework? -
Gunicorn fails to start after installing Memcached on Django project
I've had a django project working perfectly for several months, and then I decided to install memcached so I could store store my session information in there, and now everything is broken... what I did... sudo apt install memcached ... pipenv install python-memcached ... settings.py ... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' ... I've since removed these from my settings.py sudo systemctl restart gunicorn.myproj memcached and after that. I started getting a 502 Bad Gateway I tried a reboot, no luck. Tried removing the changes to settings.py no luck nginx.error ubuntu@ip-xxx-xx-x-xxx:/var/log/nginx$ tail error.log 2019/11/26 02:43:11 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET /album/random/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/album/random/", host: "www.myproj.com", referrer: "https://www.myproj.com/album/upload/" 2019/11/26 02:43:12 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/", host: "www.myproj.com" 2019/11/26 02:43:13 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/", host: "www.myproj.com" 2019/11/26 02:43:13 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while … -
Django control looping
How do I control the loop? for example if the user choose the "13" in Number Of Grades, it will show 13 search result , just like in the picture below and if the user choose for example, "2" Number of grades it will show like this and if the user choose "3" Number Of Grades it will show like this this is my views.py def gradescales(request): grade = gradeScalesSetting.objects.all() return render(request, 'Homepage/gradescale.html',{"gradeScalesSetting":grade}) def gradescaleview(request): id = request.GET.get('gradescale') grade = gradescale.objects.all().filter(Grade_Scales_Setting__id=id) return render(request, 'Homepage/gradescaleview.html', {'gradescale': grade}) this is my models.py class gradeScalesSetting(models.Model): Configuration = models.CharField(max_length=500, null=True) NumberOfGrades = models.IntegerField(blank=True, null=True) Rounding = models.CharField(max_length=500, null=True) Precision = models.FloatField() class gradescale(models.Model): Grade_Scales_Setting = models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE, null=True) Display_Sequence = models.IntegerField() Symbol = models.CharField(max_length=500, null=True) LowerLimit = models.FloatField() GPAValue = models.FloatField() Description = models.CharField(max_length=500, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) please help me, tomorrow is the deadline for this assignment. -
I have two data to render
Now I have two data to render: one is in 'base.html', and the other is in 'index.html'.I tried the following two methods, but none of them worked. views.py def everyday_cs(request): r = Content.objects.filter(is_check=True) everyday_cs = random.choice(r) return render(request, 'base.html', locals()) def index(request): everyday_cs(request) articles = LifeArticle.objects.all() return render(request, 'index.html', locals()) url.py urlpatterns = [ url(r'^$', views.index,), ] and testurl.py urlpatterns = [ url(r'^$', views.index,), url(r'^$', views.everyday_cs,), ] base.html {{everyday_cs}} index.html {% extends "base.html" %} {% if articles %} {% for article in articles %} {{article.title}} {% endfor %} {% endif %} I want to run the 'everyday_cs' function first when I run 'index' and 'url.py' write two 'url(r'^$', )' to run them, but they don't work. -
My Django Nginx Gunicorn Supervisor Only Serve 1 Request At A Time
I publish my django website using gunicorn nginx and supervisor. as i read everywhere, this was the best setup for publishing django. everything is working fine. but then in my website i have this long requested script where it takes around 10 secs to finish. i noticed that while this script is loading, another request either its from the same computer or another computer, a simple html page of my website wont load until that other 10 secs request finish. is it just me or this setup was suppose to serve multipe request as my webserver became busy. My Computer Specs: CPU(s) : 4 Core(s) Per Socket : 4 CPU max MHz: 1512.0000 Socket(s): 1 Gunicorn Service: NAME="web" # Name of the application DJANGODIR=/home/webserver/django/ # Django project directory SOCKFILE=localhost:8000 # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=15 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=web.settings # which settings file should Django use DJANGO_WSGI_MODULE=web.wsgi # WSGI module name TIMEOUT=30 Nginx Service: location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_connect_timeout 300s; proxy_read_timeout 300s; # Try to serve static files from nginx, no … -
Docker-compose django nginx doesnt find static files
I'm trying to dockerize my application and i'm almost done. The only issue I have is that nginx doesn't find my static files. I've searched all over the web, but I havent found a solution yet. I made a volume that's shared between the Django application and the Nginx server, and in my settings.py I pointed the settings to that, but no luck. I'm not sure how many of the files you need to inspect, so I uploaded the whole project to Github. https://github.com/temp3020102/django_project When the image has been built and you navigate to the admin page one can see that the CSS is missing. I'm aware that posting the secret_key and such to the internet is not a good idea, and i'm of course changing that once I have a fix for the issue. It's just there for the sake of your convenience. -
Save removed FileField image from existing object in S3
I accidentally removed images from my FileField but I use s3 using django-storage and these media files are still in the bucket. How can I save these images as FileField? I have path to the image from the backup. for example: i = Item.objects.get(pk=1) i.image = '/home/project/media/images/2019/11/09/IMG.JPG' i.save() but how to save here image from s3? On s3 there is media/images/2019/11/09/IMG.JPG folder with file -
Objects with the lowest value 0 at the end
The 0 in my query set represent 'unknown' values, but when ordered, they start the list and I want them at the end. table.objects.filter(object=pk).order_by('decimal_coln') This is what I'm getting Object decimal_coln Object_kdlsdl 0 Object_nksljj 0 Object_njsdlk 0 Object_jdnskl 1 Object_ldskll 1 Object_nlsdkl 12 Object_sjslkl 15 This is what I want (ordered, but zeros at the end): Object decimal_coln Object_jdnskl 1 Object_ldskll 1 Object_nlsdkl 12 Object_sjslkl 15 Object_kdlsdl 0 Object_nksljj 0 Object_njsdlk 0 -
cannot import name 'HTMLField' from 'tinymce'
I am getting below error message at the time of makemigrations. Can anybody please suggest. from tinymce import HTMLField ImportError: cannot import name 'HTMLField' from 'tinymce' (F:\Blog\bootstrap-blog-1-2-1\distribution\env\lib\site-packages\tinymce__init__.py)] -
Changing from CharField to IntegerField - Postgres Column data type hasn't changed Django
So I switched from sqlite to postgresql for production of my django reviews website- but due to psql being strongly typed, I'm having errors with my code LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So I figured I could change the type by changing my CharFields to IntegerFields to change the type to int... like so move_in_condition = models.CharField(max_length=5,choices=RATING_CHOICES, blank=False, default='5') treatment = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") response_speed = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") maintenance_quality = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") to move_in_condition = models.IntegerField(choices=RATING_CHOICES, blank=False, default=5) treatment = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) response_speed = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) maintenance_quality = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) with choices: class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) But then i read somewhere that sql doesn't directly support changing a string column to an int column....So i'm still getting the same error. I tried deleting my db creating it new again, and I'm still getting the same exact error after migrating. I believe this is the bit that is triggering the error def get_avg(self): return self.reviews.annotate( … -
Django returning 500 on POST request
So, I have this simple contact form, which Django handles by sending e-mails to me and to the person who contacted us. I've written an AJAX funcion to handle it. The only thing is that, no matter what I try, I keep getting an 500 status. My Django (1.11) code: def contato(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] newmessage = "Mensagem recebida de {}.\nTelefone: {}\ne-mail {}\n {}".format(name, phone, email, message) send_mail( 'Nova mensagem pelo site', newmessage, 'PLACEHOLDER@EMAIL', ['PLACEHOLDER@EMAIL'], fail_silently=False ) send_mail( 'Recebemos sua mensagem!', 'Olá, {}!\nRecebemos sua mensagem e entraremos em contato em breve.'.format(name), 'PLACEHOLDER@EMAIL', [email], fail_silently=False ) return HttpResponse() And here's my AJAX request: form.addEventListener("submit", function(event) { event.preventDefault(); let dadoscontato = { name: name.value, email: email.value, phone: phone.value, message: message.value, csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value }; fetch('/contato/', { method: 'POST', credentials: 'same-origin', headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify(dadoscontato), }) .then(function(response){ console.log(response) return response.json(); }) .then(function(response){ alert('Mensagem enviada com sucesso!'); }); }); -
Attempting to open the admin panel after trying to add something to my table in Django crashes the server
I'm using Django to host a site off of the local host, with webpages that ideally will exchange information with a SQLite database in Django's Models. I'm attempting https://stackoverflow.com/a/19761466/12352379 solution to taking data from my html fields and adding them to my table. When I try to do that, the console shows a GET request with all of the relevant data, with a 200 code. When I go to the admin panel of Django to see if the item appeared in the table, I get this lovely error: PS J:\School\Full Stack\nov19Branch\Django\Real Project\fullStack> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 25, 2019 - 19:25:18 Django version 2.2.7, using settings 'fullStack.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [25/Nov/2019 19:25:23] "GET / HTTP/1.1" 200 4131 Not Found: /css/simple-sidebar.css [25/Nov/2019 19:25:23] "GET /css/simple-sidebar.css HTTP/1.1" 404 3603 [25/Nov/2019 19:25:25] "GET /characterCreator/ HTTP/1.1" 200 6118 Not Found: /characterCreator/css/simple-sidebar.css [25/Nov/2019 19:25:25] "GET /characterCreator/css/simple-sidebar.css HTTP/1.1" 404 4681 [25/Nov/2019 19:25:34] "GET /characterCreator/?characterName=pls&race=human&class=fighter&strength=1&dexterity=2&constitution=3&intelligence=4&wisdom=5&charisma=6&mybtn=Click HTTP/1.1" 200 6118 Not Found: /characterCreator/css/simple-sidebar.css [25/Nov/2019 19:25:34] "GET /characterCreator/css/simple-sidebar.css HTTP/1.1" 404 4681 [25/Nov/2019 19:25:48] "GET /admin/ HTTP/1.1" 200 4599 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52860) … -
i have SyntaxError: invalid syntax when trying migrate
this is my models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=256, unique=True) and this is my views.py from django.shortcuts import render form appTwo.moldels import User # Create your views here. def index(request): return render(request, 'appTwo/index.html') def users(request): user_list = User.object.order_by('first_name') user_dict = {'users':user_list} return render(request, 'appTwo/users.html', context=user_dict) and protwo/urls.py enter image description here and appTwo/urls.py from django.conf.urls import path from appTwo import views urlpatterns = [ path('', views.users, name='users'), ] ** i want to migrate but i have error the trace back is and File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/proTwo/urls.py", line 18, in from appTwo import views File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/appTwo/views.py", line 2 form appTwo.moldels import User ^ SyntaxError: invalid syntax (myDjango) hamid@hamid-PC:~/Desktop/my_django_stuff/project_two/proTwo$ ** -
django.core.exceptions.FieldError: Unknown field specified for CustomUser
I just want to add one field (organization) to the auth_user model of my Django 2.2 app. settings.py: INSTALLED_APPS = [ ... 'accounts.apps.AccountsConfig', ... ] ... AUTH_USER_MODEL = 'accounts.CustomUser' accounts\models.py class CustomUser(AbstractUser): organization = 'organization' def __str__(self): return self.username accounts\forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) fields = ('username', 'email', 'first_name', 'last_name', 'organization', 'password1', 'password2') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'Email Address' self.fields['first_name'].label = 'First Name' self.fields['last_name'].label = 'Last Name' self.fields['organization'].label = 'Organization' accounts\apps.py class AccountsConfig(AppConfig): name = 'accounts' admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] ... admin.site.register(CustomUser, CustomUserAdmin) This is the Traceback: File "manage.py", line 15, in <module> (..library stuff...) File "X\staticsheet\accounts\admin.py", line 5, in <module> from .forms import CustomUserCreationForm, CustomUserChangeForm File "X\staticsheet\accounts\forms.py", line 21, in <module> class CustomUserCreationForm(UserCreationForm): File "X\Python\Python37-32\lib\site-packages\django\forms\models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (organization) specified for CustomUser I've been looking for a solution to this everywhere and I've been following a simple tutorial but I keep getting this error. Any help is appreciated. -
Is it possible to have the submission option change depending on the the question type asked in django?
Scenario If you were designing an app where one user could set questions and another could answer them. Now instead of just requiring a checkbox answer each time you wish instead to change the submission type required (text, checkbox, file upload) depending on the question type being answered. Code Example class Question(models.Model): name = models.CharField(max_length=20) description = models.TextField() ANSWER_TYPE = ( ('c', 'checkbox'), ('t', 'text input'), ('u', 'file upload'), ) answer_required = models.CharField( max_length = 1, choices = ANSWER_TYPE, default = 'c', help_text = 'select the type of submission you require' ) Question So using the question code example above would this be possible and if so what would be the best way of implementing it?