Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tag within URL tags
I would like to use dynamic images based on a a pk of the page. To be clearer I have a survey app, using one question per page .. which mean that the user is presented a question he answers and is redirected to the next question. Each question has a different id and I would like to attach to each question an image. Right now I have a static image lik that : <div class="col-5"> <img src="{% static 'images/RightSpeech.jpg' %}" class="img-fluid" alt="Responsive image"> </div> but I would like to make it dynamic.. I tried something like that with no success: <div class="col-5"> <img src="{% static 'images/image{{question.pk}}.jpg' %}" class="img-fluid" alt="Responsive image"> </div> any idea ? -
Django parallel are fialing if tests need to access files
I have a Django app that has many tests and it's taking a long time to finish testing, I'm thinking to run those tests on parallel, I tried but there is a problem with tests that need to access files, some tests are creating files and check if these files are created and exists in a path. For example, we have a test that will check-in a git repository and check if the git repository exists in the path. How to fix this issue? -
File lock in django
In my web application,created using django. I am reading a file from different instance and displaying the file with few editable text boxes. Once we edit it, when the save is clicked the file is written on the instance from where it is read. Now I have to lock the file once an user opens the file and edits it and tell other users to wait(but still they should be able to view the file only save cannot be done). I tried django-lock, simple Filelock. But did not get a clean example and got stuck. Note: There are no Models created. Users are created through the admin page. I read many docs where it is mentioned about models. If models are the only option how should i use it in my application. -
Django Connection Timed Out
I have installed a Django server on my home computer which is accessible from internet. The user can upload a file which is processed and than is redirected to another web page from where can download the result. The duration of input file handling can take between 30 secs to ~ 10 minutes depending of it's size. If I access the website from my home network, everything is working fine but when I access it from internet, I can only use small input files which can take up to max 30 seconds to process. If I wait for the result for more than 30 seconds, I get "Connection Timed Out" on my browser. Which would be the simplest solution to overcome this problem, either a timeout parameter config or making Django to send keep alive messages to user? Thank you -
Not getting parameters from openlayer 2 -request to django 1.11
I am using openlayers 2, Python2.7 & Django 1.11. For a search, I need to send a request with parameters from openlayers(javascript) to Django 1.11. I am able to submit the request but the parameters are not getting. My code is: Javascript: var params = '' var opnLyrRequest = new XMLHttpRequest(); params = 'pid=15&ctype=25&stype=50' opnLyrRequest.open('POST','/test/search/',true); opnLyrRequest.onreadystatechange=function(){ if(opnLyrRequest.readyState==4 && opnLyrRequest.status==200){ if(pinGeoJsonFrmt.read(opnLyrRequest.responseText)!=null){ dataLoc = pinGeoJsonFrmt.read(opnLyrRequest.responseText); if (dataLoc.length > 0) alert("Found !!"); else alert("No Data Found !!"); } } } opnLyrRequest.send(params); And the Django code working on the above request is: @csrf_exempt def searchSubmit(request): print request print request.method print request.POST print request.GET .... .... The getting output like this: <WSGIRequest: POST '/test/search/'> POST <QueryDict: {}> <QueryDict: {}> The parameters are missing !! -
bootstrap navbar dropdowns not showing with django
I'm trying to add twitter-bootstrap to a django project. I've got a html file called base.html which acts as a wrapper file for other html code which is placed inside of it before it gets send back in the HttpResponse. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="{% static '/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src = "{% static '/js/bootstrap.min.js' %}"></script> <title>TITLE</title> </head> <body> {% autoescape off %}{{ content }}{% endautoescape %} </body> </html> This file is the only file which will ever get send back to the visitor of the webside so I would imagine that if I add the files bootstrap needs inside base.html that it would work also on the code in content. Infact, all the css stuff seems to work fine but whenever I try to open a dropdown menu in the navbar of my site, it does not show up. This is the source code of the page that has difficulties: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src = "/static/js/bootstrap.min.js"></script> <title>TITLE</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse … -
Fill a form field with initial values from another model (which is a foreign key)
I have 2 models, Company and Post. class Post(Meta): company = models.ForeignKey(Company, related_name='company', on_delete=models.CASCADE) company_description = models.TextField(max_length=800) What I need: 1) When a user create a post, the company FK will be set thru code 2) Also at form initialization the field company_description, will be prepopulated from the Company model, field description(not the same name) 3) On save if the user doesn't modify anything to the field, the initial value will be save 1,2,3 only on creation. I checked Django documentation regarding initialization but their example, is more simple they just get some data/text, in my case I first need to set FK, than get description from the FK Model, so not just text. -
Post form data to Api for foreign fields
I have : class StudentProgramSerializer(serializers.ModelSerializer): school_program = SchoolProgramSerializer() student = StudentSerializer() class Meta: model = School exclude = ('student_program_id', ) class CourseSerializer(serializers.ModelSerializer): school_program=SchoolProgramSerializer(read_only=False) class Meta: model = Course exclude = ('course_id',) def create(self, validated_data): program_dict = validated_data.pop('school_program.school', None) print(program_dict) program = Program.objects.get(program_name=program_dict) return Course.objects.create(program=program, **validated_data) models: class StudentProgram(models.Model): student_program_id = models.AutoField(primary_key=True) school_program = models.ForeignKey(SchoolProgram,on_delete=models.CASCADE) student = models.ForeignKey(Student,on_delete=models.CASCADE) class Course(models.Model): course_id = models.AutoField(primary_key=True) school_program = models.ForeignKey(SchoolProgram,on_delete=models.CASCADE) course_name = models.CharField(max_length=120) creation_date = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) update_time = models.TimeField(auto_now=True) def __str__(self): return self.course_name How to add a course in forms to a apiview? How to deal with foreign fileds? -
DJango Jinja logic in HTML Page, cannot display html snippet
I have the following code in an html page and am trying to use jinja logic to embed html somewhere specific (in the blog/about me section of the html) Code that doesn't work (see specifics below) <!-- About Section (Blog)--> <section class="bg-primary text-white mb-0" id="about"> <div class="container"> <h2 class="text-center text-uppercase text-white">Blog</h2> <hr class="star-light mb-5"> <div class="row"> <div class="col-lg-4 ml-auto"> <p class="lead">This is the blog section</p> {%block content%} {%endblock %} </div> <div class="col-lg-4 mr-auto"> <p class="lead">The blogs outlined in the models section and stored in the database, are going to be displayed here.</p> </div> It's these two lines that ordinarily produce an htmlsnippet output: {%block content%} {%endblock %} In another place on the site (right at the bottom) I've used the same logic, and the snippet output has displayed fine. Code that works fine <!-- Custom scripts for this template --> <script src="/static/js/freelancer.min.js"></script> <div> {%block content%} {%endblock %} </div> </body> </html> The error I get is: 'block' tag with name 'content' appears more than once 141 <div class="col-lg-4 ml-auto"> 142 <p class="lead">This is the blog section</p> 143 {%block content%} 144 {%endblock %} 145 </div> 146 <div class="col-lg-4 mr-auto"> 147 <p class="lead">The blogs outlined in the models section and stored in the … -
Enforcing unique constraint based on foreign key
I enforced a unique constraint for a column and since the constraint is enforced on the entire table, is there a way to make a column unique based on the foreign key? Models class Bucket(models.Model): """This class represents the bucket model""" title = models.CharField(max_length=255, blank=False, unique=True) class Bucketlist(models.Model): """This class represents the bucketlists model""" bucket = models.ForeignKey(Bucket, on_delete=models.CASCADE, related_name='bucketlists') name = models.CharField(max_length=255, blank=False, unique=True) E.g I created 2 buckets (bucket 1 and bucket 2) Created the following bucketlists bucketlist1 -> Bucket1 bucketlist2 -> Bucket1 Attempting to create bucketlist1 in bucket 2 bucketlist1 -> Bucket2 (This throws an error) -
How can I let the superadmin user and user itself to access a API?
I have a UserUpdateAPIView, in it I can edit the user information: class UserUpdateAPIView(RetrieveUpdateAPIView): queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4) serializer_class = UserDetailSerializer lookup_field = "username" def perform_update(self, serializer): serializer.save() The UserDetailSerializer: class UserDetailSerializer(ModelSerializer): """ user detail """ class Meta: model = User exclude = [ 'password', ] depth = 1 Now, every user can access the UserUpdateAPIView, so its a bad design. I just want the super admin and the user itself can access the APIView, how to implement it? I know I can use permissions = [IsAdminUser] to allow the admin users to access this API, but I just want to let the super admin user and the user itself to access. -
I have a TypeError: expected string or bytes-like object during "migrate" (Django)
I am using Django. I changed something in my model, which is 'datefield'. I changed it from datetimefield ('taxi_time') to datefield ('taxi_date') & timefield ('taxi_time'). I did manage.py makemigrations but I couldn't manage migrate. Error is following. Running migrations: Applying taxi.0017_auto_20171214_2256... OK Applying taxi.0018_auto_20171214_2336...Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 238, in add_field self._remake_table(model, create_field=field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table self.effective_default(create_field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1301, in get_db_prep_value value = self.get_prep_value(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value return self.to_python(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1258, in … -
How to print a form using reportlab package in django?
views.py in function some_view the drawing function p.doForm is not taking a Form model as input .what i have to do to print that form into pdf. i need to conver that object into string or send info form requests from django.http import HttpResponseRedirect, HttpResponse, request from django.shortcuts import redirect, render from .forms import Form_db_att from django.utils import timezone from .models import FormDb # Create your views here. def home(request): if request.method == 'POST': form = Form_db_att(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return HttpResponseRedirect('/home/test') else: form = Form_db_att() return render(request, 'mforma/name.html', {'form': form}) def thanks(request): form = Form_db_att(request.POST) model_instance = form.save() model_instance.save() return render(request, 'mforma/thanks.html', {'form': form}) from reportlab.pdfgen import canvas from django.http import HttpResponse def some_view(request): # Create the HttpReormponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = ' filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.doForm(Form_db_att) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response -
How to force duration display as H:i in django?
I have a duration field which with validations, the maximum is 24 hours. However when 24 hours is displayed it shows as: 1 day, 0:00:00 I want it to show as 24:00 I am currently displaying the DurationField: <td>{{ entry.duration }}</td> -
Http delete method using jQuery ajax on django rest backend fails on Safari, but works in Chrome
I want to use django rest framework as backend and jQuery in the frontend to post and delete. Using $.ajax POST works fine. But delete call fails on Safari but works in Chrome. Here is the sample code: django models.py: from django.db import models class Article(models.Model): title = models.CharField(max_length=250) content = models.TextField() create_date = models.DateTimeField(auto_now_add=True) urls.py: urlpatterns = [ path('api/v1/articles/', views.ArticleList.as_view()), path('api/v1/articles/<int:pk>', views.ArticleItem.as_view()), ] views.py: class ArticleList(generics.ListCreateAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleItem(generics.RetrieveUpdateDestroyAPIView): query set = Articles.objects.all() serializer_class = ArticleSerializer serializer.py class ArticleSerializer(serialisers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'create_date') jQuery: # on delete link $("#talk).on('click', 'a[id^=delete-]', function() { var pk = $(this).attr('id').split('-')[1]; delete_article(pk); }); function delete_article(pk){ $.ajax({ url: "api/v1/articles/"+pk, type: "DELETE", data: { pk: pk }, success: function(son) { $('#post-'+pk).hide(); console.log("delete successful") }, }) }; In Safari 11.0.1, in console it only shows "0: undefined". It is not going into success loop. In Chrome delete function is successful. -
Library, but also a project impacting another
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. My main focus in the moment is that each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround? -
Basic authentication curl reqest to django request
I want to convert this curl request to django request curl -user admin:cadmin --request GET http://13.125.119.197:8050/lua/iface_ports_list.lua?clisrv=server -
How to check django staff user first time login in admin panel?
I am workign on a django project and i am using the default auth app for authentication. I know that there is a last_login field in user model which stores the user's last login time. When a staff user logs in first timeinto the admin panel, i want to check if last_login field is none & redirect him to the change password page. I want to know where should i put this check ? Do i need to extend the login form, if yes how to do i pass it to my login function as the admin url's are generated by django admin app. Is there any login callback fucntion in django where i can do this ? -
Django Admin, modify/customize the names in the select box of a manytomany field
I have 2 models Category and Product. Category has a FK to itself, and Product a FK to Companies. class Product(Meta): categories = models.ManyToManyField(Category, related_name='products') class Category(SEO, MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) In Django Admin in Product Create/Edit Page I need to select the Categories for Parent. At this moment is just a long select box, with the names of Categories. I want to introduce the all path of the category-subcategory. Ex: Now: Category A Name Need: Category Parent Name :: SubCategory Parent Name :: Category A Name I don't want to modify def str because is used also in other places. -
Admin InlineForm add links to Detail Page of the Inline Model and add custom javascript
In Admin for InlineForm there is a link that goes to the website, be default the text is (View on site). I want to add a similar link that goes to that model(that is inline) Detail Edit Page. Insert a JavaScript script in one of the Edit/Details Model Page in Admin How can this be done ? -
d3 chart not responsive inside split container
I want to make this d3 js library chart responsive inside split pane. I use split.js for split pane and container. see this example Any helpful reply can be appreciated. Thanks in Advance <!DOCTYPE html> <html lang="en"> <head> <title>Split.js</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <style> html, body { height: 100%; } body { padding: 8px; background-color: #F6F6F6; box-sizing: border-box; } .split { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; overflow-y: auto; overflow-x: hidden; } .content { border: 1px solid #C0C0C0; box-shadow: inset 0 1px 2px #e4e4e4; background-color: #fff; } .gutter { /*background-color: transparent;*/ background-color: #00000017; background-repeat: no-repeat; background-position: 50%; } .gutter.gutter-horizontal { cursor: col-resize; background-image: url('vertical.png'); } .gutter.gutter-vertical { cursor: row-resize; background-image: url('horizontal.png'); } .split.split-horizontal, .gutter.gutter-horizontal { height: 100%; float: left; } </style> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <div id="c" class="split content"> <div id="a" class="split split-horizontal"> <div id="chart-div" style="width:50vw;height:80vh;border:1px solid blue;"></div> </div> <div id="b" class="split split-horizontal"> <textarea row="8" style="height: 90%; width: 100%;"></textarea> </div> </div> <div id="d" class="split content"> <!-- <textarea row="8" style="height: 90%; width: 100%;"></textarea> --> </div> </body> <script src="split.js"></script> <script> Split(['#a', '#b'], { direction: 'horizontal', gutterSize: 8, sizes: [50, 50], cursor: 'col-resize' }) Split(['#c', '#d'], { direction: 'vertical', sizes: [50, 50], gutterSize: 8, cursor: 'row-resize' }) Split(['#e', '#f'], { direction: 'vertical', sizes: … -
Temporal Database with Django Rest Framework using perform_update
We are trying to implement a temporal database so that we are able to track changes made All our models have the following fields vt = models.DateTimeField(db_column='VT', default=datetime(3000, 12, 31, 23, 00, 00, 000000)) # Value To vflag = models.IntegerField(db_column='VFlag', default=1) # Version Flag 1 = Current, 0 = Old When using the Django rest framework I’ve tried to modify the perform_update in my viewset to duplicate the existing record, make the updates and then set temporal fields appropriately. It works when I have 1 record and the first update However once I try and make a second update it fails and create a duplicate of the changes and overrides the very first record. Original Record Currency = AUD, VFlag = 1, VT = time1 Perform update - success Currency = USD, VFlag = 1, VT = time2 Currency = AUD, VFlag = 0, VT = time1 Next perform update currently produces - fails Currency = GBP, VFlag = 1, VT = time3 Currency = GBP, VFlag = 1, VT = time3 Currency = USD , VFlag = 0, VF = time2 Expected update output Currency = GBP, VFlag = 1, VT = time3 Currency = USD, VFlag = 0, … -
Django and Flask on same nginx server
I currently have a Djago app running on my main site when I visit mysite.com. However, I'd like mysite.com/flaskapp to run a separate Flask application. I'm able to set up two nginx site-enabled config files and run each app on a different port but, for various reasons, I'd like to run them all on the same port (if possible). When I configure my flaskapp/ location in my nginx server file I get a 404 error. Here's my supervisor config file: [program:MYSITE] command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi directory=/var/www/html/MYSITE/public_html autostart=true autorestart=true stderr_logfile=/var/log/MYSITE.err.log stdout_logfile=/var/log/MYSITE.out.log [program:FLASKAPP] directory=/var/www/html/MYSITE/public_html/FLASKAPP/api command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app autostart=true autorestart=true stderr_logfile=/var/log/FLASKAPP.err.log stdout_logfile=/var/log/FLASKAPP.out.log And my nginx site-enabled file: server { listen 80; listen [::]:80; server_name MYSITE; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/html/MYSITE/public_html; expires 30d; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock; } location /FLASKAPP/ { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock; } } I wrote a function to check the request url @app.errorhandler(404) def page_not_found(error): return 'This route does not exist {}'.format(request.url), 404 Which returns: This route does not exist http://MYSITE/FLASKAPP The Flask app is clearly working, but the routing is screwed up. How can I fix this? -
remove multiple cross sign when using python autocompelete light in django
I have implemented django-autocomplete-light with django 1.5. But in that i have face one issue like when i set default value of form, this library display multiple cross sign for single record. In that i have used choiceWidget. Here I attached image of issue. Here Some of code : event_form = event_form_class(initial={'klant': klant}) forms.py (in that event_form_class define ) self.fields['klant'].widget = autocomplete_light.ChoiceWidget('KlantAutocomplete') in template i have used following line: {{ event_form.klant }} -
Where can I write the after query logic in RetrieveAPIView?
Where can I write the after query logic in RetrieveAPIView? In my models.py I have a Message class: class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) is_read = models.DateTimeField(null=True, blank=True) create_user = models.ForeignKey(User, related_name="created_messages") receive_user = models.ManyToManyField(User, related_name="received_messages") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.title In the views.py: # the message list class UserMessageListAPIView(ListAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages # the message detail class UserMessageRetrieveAPIView(RetrieveAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages You see, in the UserMessageRetrieveAPIView I can retrieve the message instance. How can I do the logic to set the message's is_read ? Where I can set it?