Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formview form_valid, form has no attribute `instance`
I'm trying to create a form view using the FormView class. It works fine displaying the post form but when posting the data form_valid function is called and here I get an error: AttributeError: 'GameForm' object has no attribute 'instance' As I can understand the form object passed in the form_valid method doesn't contain an instance but examples show that it is possible.. What am i missing? views.py from django.shortcuts import render, redirect from django.views.generic import (ListView, DetailView) from django.views.generic.edit import FormView from .models import Game from .forms import GameForm # ... Other views class GameCreateView(FormView): template_name = 'games/game_form.html' form_class = GameForm success_url = '/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.instance.author = self.request.user return super().form_valid(form) Website log AttributeError at /game/new/ 'GameForm' object has no attribute 'instance' Request Method: POST Request URL: http://127.0.0.1:8000/game/new/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'GameForm' object has no attribute 'instance' Django version = 3.1.3 Thanks in advance! -
How run makemigrations <app> --empty with Django and Docker?
I have a Django app with Docker and Docker-compose. So I can build, up or down my container but how can I run manage.py or django-admin command like makemigrationn <app> --empty ? In a "classical" Django project architecture, no problem But using Docker, I have an error django.core.exceptions.ImproperlyConfigured: Requested setting STATIC_URL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I try django-admin makemigrations myapp --empty --settings=core.settings.dev but have another error no module core found -
Can I create a script, "Virtual Environment" and run it in crontab?
They help me, they know I need to run a script to start the services, I use Django with Python and ubuntu server. I have been seeing many examples in crontab, which I will use, every time I restart the server, I run the Script, which contains the command to run the virtual environment and in addition to the command "python3 manage.py runserver_plus", apart was to see restart the server all nights, I was also successful with crontab, but I can't execute what the script contains. They can help me, I am not very expert, but I managed to do something. Is it the path of the script? Tried running the command directly, got no results. -
How to not show pre selected form data in django form
i have form that give list of subject name with multiple choice but when student select one of those choice then i want next time next time they again come to choice they will not see pre selected data. how can have that in django form? what would be the approach to have that solution? much appreciate for your help. thank you so much. models.py class Registration_Course(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) course = models.ManyToManyField(Student_Course_Name, blank=True) def __str__(self): return str(self.user) views.py class Course_Registration(generic.CreateView): model = Registration_Course template_name = 'test/reg.html' form_class = RegForm def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse("saved form") forms.py class RegForm(forms.ModelForm): answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect(), required=True, empty_label=None) class Meta: model = Registration_Course fields = ['course', 'student'] widgets = { 'course': forms.CheckboxSelectMultiple } -
Unique=True message need to show in the vuejs template
I am developing the VueJs app using Django rest framework, In the question model, For the content field I added the unique = true because I want the content to be different. In the api it is validating the field. class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240, unique=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") Now I want that error message in the vuejs template after the field . What I need to change in the script of the vuejs. <template> <v-container> <h1 class="mb-3">Ask a Question</h1> <v-form @submit.prevent="onSubmit" ref="form" v-model="valid" lazy-validation> <v-textarea v-model="question_body" placeholder="What do you want to ask?" rows="3" :counter= "240" :rules= "textarearules" auto-grow outlined row-height="25" shaped ></v-textarea> <v-btn type="submit" :disabled="!valid" color="primary white--text text-center" class="mr-4 mb-3" @click="validate" rounded>Publish</v-btn> </v-form> <div v-for="question in questions" :key="question.pk"> <h1>{{ question.content }}</h1> </div> <p v-if="error" class="muted mt-2">{{ error }}</p> </v-container> </template> <script> import { apiService } from "@/common/api.service.js"; export default { name: "QuestionEditor", props: { slug: { type: String, required: false } }, data() { return { questions: [], question_body: null, error: null, valid: true, textarearules: [ v => !!v || 'Answer is required', v => (v && v.length <= 240) || 'Answer must be less than 240 … -
Sudden 502 messages on Gunicorn
My server has been working great for about 18 months. My setup is Nginx, Gunicorn, Django on a Ubuntu server. I will share this next piece of information just for the sake of full disclosure. One of my hard drives died on this same server. It's not the hard drive with any of the data that I'm referring to, but this hard disk did end up getting a new uuid. I feel compelled to share this information because this was when I started having trouble. Could be coincidence, could be related, I dunno. This was last Friday and I've been struggling with it ever since. I get a 502 error. When I drill down a little bit that shows up as a Gunicorn error. I'll attach all of the information that I can think of below about my setup. But what gets me is that I can start Gunicorn from the command line, but not from the computer boot. This works from the command line, which tells me that I have something right: sudo service gunicorn stop sudo /media/Storage/sales_portal/venv/bin/gunicorn --chdir=/media/Storage/sales_portal --timeout 600 --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/gunicorn/error.log --log-level debug --workers 3 --bind unix:/run/gunicorn.sock sales_portal.wsgi:application My gunicorn.service file is: [Unit] Description=gunicorn daemon … -
Custom Django SlugField Validation and Breaks URL Matching
I wrote a custom field validator for slugs in my URLs (accepting periods in slugs for one model, SLUG_REGEX = '[-a-zA-Z0-9_.]+$'): def validate_my_slug(value): my_slug_re = re.compile(settings.SLUG_REGEX) if not my_slug_re.match(value): raise ValidationError( _('Slugs must consist of letters, numbers, ' 'underscores, hyphens, or periods.'), params={'value': value}, ) The field in models.py: slug = models.CharField(max_length=64, null=True, blank=True, validators=[validate_my_slug]) This works when saving models in Django admin. But then in my URLConf, this no longer works (it did work before changing the slug validation): path('product/<slug:slug>', ProductDetail.as_view(), name='product-detail') I found a solution using re_path, but I'm not sure it's the right/best way to do it: re_path('product/(?P<slug>[-a-zA-Z0-9_.]+)$', ProductDetail.as_view(), name='product-detail') Now this no longer works (comes before the re_path pattern above in urls.py): path('products', ProductList.as_view(), name='product-list') -
Django + AJAX Post method url 404 not found
Good afternoon, I am working on a simple like button in a Django Post class. I am using an Ajax get method but can't reach the like view and get a 404 error. Can anyone help, please? urls.py: urlpatterns = [ path('', views.home, name="wall-home"), path('like/', views.like, name="like") views: def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) post = get_object_or_404(Post, slug=slug) if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) ctx = {'message': "success"} return HttpResponse(json.dumps(ctx), content_type='application/json') Ajax: <script> $('#likebutton').click(function(){ $.ajax({ type: "POST", url: "{% url 'like' %}", data: {'slug': $(this).attr('slug'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", // handle a successful response success: function(response) { alert(response.message); alert('Success'); }, error: function(rs, e) { alert(rs.responseText); } }); }) -
Create a confirmation message from model in Django
I have an app in Django that has multiple models. I have a particular model like this: models.py class MyModel(models.Model): model_id= models.AutoField(primary_key=True) model_date = models.DateTimeField(verbose_name="Label 1") model_counter = models.IntegerField(blank=True, null=True) What I need is that the user confirm that he wants to save the model, even if the date is greater than today, in doing so the user can create a model that can be wrong for other users, but sometime it's correct that the date is greater than today. I cannot use a custom HTML form, only the default one. The user must interact someway with the page, and give direct aknowledgement that he knows that is saving a new model that can be dangerous for other users. The user must be able to abort the saving or modify the date. So I tried to use another field of the model to store the counter: def clean(self): condition = False if self.model_counter is None: condition = True else: condition = self.model_counter == 1 if condition : self.model_counter = 1 raise ValidationError("Attention, the date inserted is after the current date, click the SAVE button another time to proceed with the saving") As a counter I use another field of the … -
Bootstrap modal pop up breaks when i send "schemaname.tablename" into id field using Django Jinjna template
Below is my html script when I am sending a schema_name.table_name to the 'id' attribute of my modal and pop up modal is not displayed and the popup modal breaks, but work well as mentioned in the below note note: when I only send table_name pop up is displayed but i need to send schema_name as well please help <input type="checkbox" id='dbo.segment_customer_hash_mapping_history' name="acs[]" value="dbo.segment_customer_hash_mapping_history"> dbo.segment_customer_hash_mapping_history <!-- <form action="/dwdatacatlog2/" method="GET">--> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModaldbo.segment_customer_hash_mapping_history">Add filter <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-plus-circle" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/> <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/> </svg> </button> <!-- <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>--> <!-- Modal --> <div class="modal fade" id="myModaldbo.segment_customer_hash_mapping_history" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4>Add Filters</h4> <!-- <h4 class="modal-title">Modal Header</h4>--> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <p><small>Table name</small></p> <p>dbo.segment_customer_hash_mapping_history</p> <p> <select id="columnname" name="columnname" class="form-control" onchange="changecat(this);"> <!-- onchange="populatefilter()"--> <option value="int////audit_id"> audit_id<small>(int)</small></option> <option value="int////segment_id"> segment_id<small>(int)</small></option> … -
Django CKEditor clean files unattached to rich text fields
I am writing an image cleanup management command for my Django project. The principle of how this works is: get all references to files attached to object ImageFields like so: all_models = apps.get_models() for model in all_models: file_fields = [] filters = Q() for f_ in model._meta.fields: if isinstance(f_, FileField): file_fields.append(f_.name) is_null = {'{}__isnull'.format(f_.name): True} is_empty = {'{}__exact'.format(f_.name): ''} filters &= Q(**is_null) | Q(**is_empty) # Only retrieve the models which have non-empty, non-null file fields if file_fields: for file_field in file_fields: files = model.objects.exclude(filters).values_list(file_field, flat=True).distinct() db_files.update(files) get a list of stored image files delete all stored files not attached to an object ImageField This all works fine. But, I can't apply (1) to images that are embedded in objects using the CKEditor RichTextUploaderField. Any idea how I can get a list of those images to complete my cleanup? -
List of products
I have to complete a project this semester where I have to retrieve a list of products according to the user's search and make a report for selected items by the user. I searched a bit but is there any free API that provides a good amount of product data with some basic info. Reaching out to expert developers kindly help me -
Use query expression F() as input to a regular function in django
Suppose I have a model like this: class Order(models.Model): error_code = CharField(max_length=10, blank=True, null=True) I wish to create an annotated queryset where I will group all orders by error_code and count how many of each I have. Something like this: report = (Order.objects .values('error_code') .annotate(count=Count('id')) ) Also, I would like to look for descriptive messages for each possible error_code, which I have hard-coded on my code in a dict: messages = dict( '000'='Processing failure', '001'='Rejected credit card', '002'='Invalid credit card number', ... etc ) I would like to annotate the original queryset with a new value called message where I would get the error_code and check the messages dictionary. Something like this: report = (Order.objects .values('error_code') .annotate(count=Count('id')) .annotate( message=Value( messages.get(F('error_code')), CharField(), ) ) ) What I expected with the above code was to obtain the value of error_code on the query and pass it as a string to the messages.get() method. However F('error_code') doesn't return a str value; it returns a F expression object. Can I use expressions return values as input to regular Python methods? Is there any other way I could achieve what I explained above? I know I would be able to do this error_code to message … -
What is the best practice to update an html page on django using django-channels?
Django-channels is running with docker and redis. Everything is working fine. PROVA_CHANNEL.HTML {% extends 'base.html' %} {% block content %} <div id="refresh-this-div"> {% include 'prova_ordini_in_channel.html' %} </div> <script language="javascript"> var ws_url = 'ws://' + window.location.host + '/ws/ticks/'; var ticksSocket = new WebSocket(ws_url); console.log(ws_url); ticksSocket.onmessage = function(event) { var data = JSON.parse(event.data); console.log('data', data); // do whatever required with received data ... }; </script> {% endblock content %} When i run this function from the command center, the webpage prints out, in java console: { 'Nuovi ticks' : 12 } Django-channels is working! ''' from django.core.management.base import BaseCommand import json from asgiref.sync import async_to_sync import channels.layers from django.conf import settings class Command(BaseCommand): help = 'Displays current time' def handle(self, *args, **kwargs): ticks = {'Nuovi ticks': 12} channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( settings.TICKS_GROUP_NAME, { "type": 'new_ticks', "content": json.dumps(ticks), }) ''' The question is: If i want to refresh variables that i'm passing from the view ('context['ordini']') i'm obligated to call the view with AJAX, or there is another way to refresh the page?? 'FUNCTION IN VIEW.PY' ''' def prova_ticks(request): context = {} ordini = Ordine_delivery.objects.filter(stato_ordine='processing') context['ordini'] = ordini return render(request, 'prova_channel.html',context) ''' -
DRF ListAPIView return manytomany value names instead of pk
I have a Post Model contains tags field that have ManyToManyField to categories Model, when i call REST ListAPIView all post tags returns in pk I have tried to override list function in ListAPIView and map all tags_names for every post but this takes a huge time and destroys the performance I hope/Believe there something built in for this case models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=256) content = RichTextField() tags = models.ManyToManyField(Categories) def __str__(self): return self.title class Categories(models.Model): tag_name = models.CharField(max_length=256, unique=True) def __str__(self): return self.tag_name class Meta: ordering = ('tag_name',) unique_together = ('tag_name',) views.py from .models import Post from .serializers import NewPostSerializer, PostSerializer class NewPost(CreateAPIView): serializer_class = NewPostSerializer permission_classes = [IsAuthenticated, IsAdminUser] class PostList(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer serializers.py class NewPostSerializer(ModelSerializer): class Meta: model = Post fields = ['title', 'content', 'tags'] read_only_fields = ['tags', 'author_id'] when i visit ListApiView link returned results would be like this: [ { "id": 30, "title": "post title test", "content": "lorem text", "author": 3, "tags": [ 8, # should be games 3 # should be action ] } ] -
How to get a value from html using checkbox into views.py?-Django
I am not sure how to receive dynamic values from checkbox I want to take the id of Service model which I already have in my django project. I have a form which will take the values from checkbox to views.py. I want to know what is the right way to use the checkbox. Is this the correct way? <td><input type='checkbox' name='services' value={{ service.id }} class='btn btn-primary' /></td> -
django admin have choice option in field depend on values in other field
I'm just starting out in Django, and am having trouble setting up a model on the admin side. Here is the situation. I have 12 centers, each with over 20 laboratories. I have a model class for publications. On the admin side, I want to be able to assign centers and laboratories to each publication. More than one center can be assigned to each publication, and within each center more that one laboratory could be assigned. But, I do not want the laboratory field to list all the possible laboratories because there are too many. I would like the list seen in the laboratory field to only display laboratories in the centers that are chosen in the center field (and ideally, if more than one center is chosen, there will be separate lists to choose from for each) Here are the models I have: class Publications(models.Model): center = models.ManyToManyField('Center') laboratory = models.ManyToManyField('Laboratory') class Center(models.Model): name = models.CharField(max_length=255) class Laboratory(models.Model): name = models.CharField(max_length=255) So, after making Admin classes (PublicationsAdmin(admin.ModelAdmin), CenterAdmin(admin.ModelAdmin), LaboratoryAdmin(admin.ModelAdmin)) and registering them in admin.py, I can go to the admin page and add the centers and the laboratories and then when adding publications, I can choose the center(s) and … -
Can't get user id from request in django rest framework?
I wrote an api using django rest framework(DRF) which uses SessionAuthentication for validating users. This is my whole code # project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } # app/models.py from django.db import models # Create your models here. class Item(models.Model): name = models.CharField(max_length=50) amount = models.FloatField() # app/serializers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id','name', 'amount') # app/urls.py from django.urls import path from main import views urlpatterns = [ path('',views.ItemView.as_view(),name='view_list'), ] # app/views.py from .models import Item from .serializers import ItemSerializer from rest_framework.response import Response from rest_framework.views import APIView class ItemView(APIView): def get(self, request): items = Item.objects.all() items_serializer = ItemSerializer(items, many=True) return Response(items_serializer.data) def post(self,request): print(request.data) item_serializer = ItemSerializer(data=request.data) if item_serializer.is_valid(): return Response({'userid':request.user.id}) return Response({'error':'error'}) I then logged in to http://127.0.0.1:8000/admin with my username and password and I expected my post request of {name:"Steve",amount:10000} return a result similar to this { "userid": 3 } but its returning { "userid": null } How do we get user id from DRF request? -
Is there a way to know if an user owns a domain?
I'm developing a webapp(Django) that let users have an eshop just with a few clicks. I serve the shops under https://shopname.mydomain.es but then I give them the option to use a domain if they want. For example one of my users (user1) buys "happyuser.com" in a domain provider of his choice. Then I tell them to modify their DNS to point to my server. So far so good, everything works perfectly, I use Nginx to allow access from the connected domains and everything works correctly. Here comes my doubt. I use a middleware to detect the host, in this case "happyuser.com", I check a table in wich I have the relation between user and domain name. class UserDomain(models.Model): user = ForeingKey(...) domain = UrlField(...) Then I tell django to serve the correct shop. But what happens if another user (user2) also saves the domain "happyuser.com", how can I know wich user shop should I load?. I know is unlikely that this happens, but is there a way to prevent this problem? -
How to loop through a form object in django?
I want to loop through a form object in order to style the form as I wish. I'm not sure what I make wrong. I want the form to look exactly the same as before, after I integrate the form tags but it's not. this is the from class: class CreateUserForm(UserCreationForm): email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputEmail', 'placeholder': 'Email Address'}), label='') username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputEmail', 'placeholder': 'Username'}), label='') password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputPassword', 'placeholder': 'Password'}), label='') password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleRepeatPassword', 'placeholder': 'Repeat Password'}), label='') class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] html form before adding the forms tags: <form class="user" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" placeholder="Email Address"> </div> <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" placeholder="Username"> </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <div class="col-sm-6"> <input type="password" class="form-control form-control-user" id="exampleRepeatPassword" placeholder="Repeat Password"> </div> </div> <input type="submit" name="Register" class="btn btn-primary btn-user btn-block" value="Register Account"> <hr> <a href="#" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Register with Google </a> <a href="#" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Register … -
How to add an extra field for an existing model in case of many to many relationships in django
So I have a product Model which say looks like this : class ProductModel(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2, null=True) and I also have a cart model which looks like this : class CartModel(models.Model): customer = models.ForeignKey(User, on_delete= models.CASCADE, related_name="cart") products = models.ManyToManyField(ProductModel) the thing is I want to add a quantity field to the product so the user can add multiple products from the same product in the cart But I only want it when the product is in a cart (I don't want to add it in the ProductModel) Instead I want to add it to the product fields in the many to many relationship. I've done a bit of research and most of the answers aren't clear enough on how I should be doing this. -
can any one tell me how i can get user after login
I am trying to create logs of users but I can't seem to get an error around request.user.is_authenticated. please ignore my bad knowlede as this is my first post here's my code for log view User = settings.AUTH_USER_MODEL class ObjectViewed(models.Model): user = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE) # content_type = models.ForeignKey( # ContentType, on_delete=models.SET_NULL, null=True) InputAndOutput = models.CharField( max_length=10000, blank=True, null=True) ip_address = models.CharField(max_length=120, blank=True, null=True) # content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.InputAndOutput class Meta: db_table='analytics_objectviewed' ordering = ['-timestamp'] verbose_name = 'Object Viewed' verbose_name_plural = 'Objects Viewed' def object_viewed_receiver(sender, instance, request, *args, **kwargs): # c_type = ContentType.objects.get_for_model(sender) ip_address = None try: ip_address = get_client_ip(request) except: pass if request.user.is_authenticated: user = request.user new_view_instance = ObjectViewed.objects.create( user=request.user, # content_type=c_type, InputAndOutput=instance, ip_address=get_client_ip(request) ) -
Django CategoryView with multiple status
def CategoryView(request, cats): category_posts = Post.objects.filter(category__iexact=cats.replace('-',' '), status='1') return render(request, 'categories.html', {'cats':cats.title().replace('-',' '), 'category_posts':category_posts}) I have a function that let me view status 1, but now I need one that let me view 1 and 2 at the same time, tried some things but didn't work as expected. -
Run subprocess from inside Django app as root
I need to execute linux command from inside django app. The problem is that django app user is www-data and linux command creates files, so I get permission denied error. How to run subprocess.check_output(['some', 'command']) as root? -
how can I encrypt my Django rest framework response? [closed]
I have Django rest framework as Backend for multi-platform project (web, Ios, android), the connection is encrypted with HTTPS, my question is how can I encrypt the body of the response before sending it to the frontend? is there any library to use? any advices I would be grateful.