Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Storages - I/O operation on closed file
I am trying to upload file in Amazon S3 Bucket. For that purpose I have installed latest version of Django-Storages. Though media is getting serve from S3 bucket but I am unable to upload file to S3 bucket'. I get this error: Value error: I/O operation on closed file I read over here https://github.com/jschneier/django-storages/issues/382 that this issue is cause of django-storages version. I changed version to 1.6.0 then I started getting error: No module named 'django.utils.six' Then I changes django version and more errors start getting appear and so on. My first question: Does this I/O error is really due to just django-storages version? If that so, then how to cater this situation as I was using most upgraded version of everything? -
Limiting the amount of posts per category not working (Django forum)
I've created a forum on my website, which has 2 different categories within it. These categories are General Discussion and Events. I've split these categories up into their own sections and I've managed to do that just fine. The issue I'm seeing occurs when I try to limit the number of posts that can be seen on the page per category. For example, I only want 4 posts to be displayed for each category on the main forum before the user has to go onto a separate page for those specific category posts. To limit the number of posts per category, I've been using |slice:":4" which is think is the wrong approach. Below is what I've added. Just an FYI, the below does work when there are only 4 posts on the entire website, but as soon as there are more than 4, the amount of posts shown for each category starts to decrease. {% for post in posts|slice:":4" %} <div class="media text-muted pt-3"> <p class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray"> <strong class="d-block text-gray-dark margin-bottom-5"><a href="{% url 'forum_post_details' post.id %}">{{ post.title }}</a></strong> {{ post.content|truncatewords:30 }} </p> <hr> </div> {% endfor %} </div> <div class="my-3 p-3 bg-white rounded shadow-sm"> <h5 … -
Django creating and deleting user-wise caching
I am using Cache in Django. Everything is working fine but what I want is to clear the set of caches for a particular user only. I have a subscription-based platform and whenever a user makes a new subscription, all the caches related to him and only him should be deleted. To achieve user-wise caching, I have used @method_decorator(vary_on_headers('Authorization', 'cookie')) in the rest framework's methods. With this decorator, I am successfully achieving user-wise caching but how can I selectively delete all the caches related to the user. I could execute cache.delete(cache_key) or cache.delete_many(cache_key_list) individually for each URL but the tricky thing here is the find the exact key for those caches. -
How to return entire table row in array by foreign key and how to access from template in django models
I have tried like this. But it is returning the only one combined value. class employees(models.Model): nameininitials = models.TextField(null=True) nameinuse = models.TextField(null=True) employeeno = models.TextField(null=True) departmentname = models.TextField(null=True) def __str__(self): return '{} {}'.format(self.nameinuse, self.employeeno) class Region(models.Model): regionname = models.TextField(null=True) regionalincharge = models.ForeignKey(Erpemployees, on_delete=models.CASCADE,null = True) When I use datalist = Regions.objects.all() , I want all fields from primary table in different variables or array to use in template. -
Django 2.2 with external connection SQL SERVER
In my python 3.7 + Django 2.2 I need to connect to external SQL Server. Its not the main DB of Django (that remains in Postgres). I only need to make some query on a view. Im on Debian 9 and Im trying to install package to add sql server connection but I cant find on google a guide about Debian package to install. I try to install: pip install pyodbc pip install django-mssql-backend but the compile failed. I think Im missing some system libraries. Thanks. -
Django UnitTest keeps throwing KeyError
I have been building this unit-test for the Google Social Login View I made. There were lots of errors so far and I have been able to fix them all rummaging through StackOverflow. However, I have hit the wall while trying to get past this KeyError it keeps throwing at me. The KeyError seems to come from the request header and I tried all sorts of ways of adding key/value pair(in this case, "Authorization":"1234") into the header using Client. Below is my views.py import json import ast import httplib2 import google.oauth2.credentials import jwt import requests from google.oauth2 import id_token from django.shortcuts import render from django.views import View from django.http import JsonResponse from apiclient import discovery from oauth2client import client from pinterrorist.settings import SECRET_KEY from .models import User, Social, Follow class GoogleLoginView(View): def post(self, request): token = request.headers["Authorization"] url = 'https://oauth2.googleapis.com/tokeninfo?id_token=' response = requests.get(url+token) user = response.json() if User.objects.filter(social_id = user['sub']).exists(): user_info = User.objects.get(social_id=user['sub']) encoded_jwt = jwt.encode({'id': user["sub"]}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : user['name'], 'user_pk' : user_info.id }, status = 200) else: new_user_info = User( social_id = user['sub'], username = user['name'], social_service = Social.objects.get(name = "google"), email = user.get('email', None) ) new_user_info.save() encoded_jwt = jwt.encode({'id': new_user_info.id}, SECRET_KEY, … -
What is the best way to customize Django admin templates?
I have been trying to customize the django admin create/update form for a Model. I have a field in my database model that I want to generate through certain specification. For that I need a generate button that will generate data for that field and show those data before letting the admin/staff save the data. Model : - title - generated_data [ A paragraph containing random sentences from another Model ] I need an extra field in django-admin where I will specify how many random sentences I want to generate. Clicking generate button will generate that random paragraph and show it to user as a preview before he can save the data for both create and update. Is is possible customize django-admin to do that? -
Django, `KeyError <built-in function id>` in the form
I have created an app that give me the possibility to collect and store all daily income. In this case I have created the following model: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals All works perfectly. But now I want to give the possibility to be able to choose the year manage the now variable. So for this aim I have tried to create a new model, as the following: class Timing(models.Model): TYPE=[ ('2020','2020'), ('2021', '2021'), ] reference_year=models.CharField('Azienda/Privato', max_length=30, choices=TYPE, default="") And in my views I have added the code: now='2020' if request.method == 'POST': form = TimingForm(request.POST) if form.is_valid(): now = form.cleaned_data['reference_year'] But django give me the KeyError <built-in function id>. Where is the issue? I think that the problem is about the fact that now is not a datetime variable? -
my select2 js only work the first form in django formset
i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form this is my snippet <tbody class="tbody tb1 " id="form_set"> {% for item in items.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> <input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz"> </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.model | add_class:'col-12 0model model' | attr:'id:model'}} </div> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', deleteText:'remove', addCssClass:'btn btn-success', }); }) </script> <script type="text/javascript"> $(document).ready(function(){ $("#model").select2() }) </script> but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe? thanks -
User ralated Data from other model
I have 2 persons with same name in user model,and both of them have intrest too and level under Intrest model,How can i get a level of the person from User model in session model. And how can i fetch that data in views. class User(models.Model): user_name=models.CharrField(max_length=30): class Intrest(models.Model): user=models.Foreignkey(User,on_delete=models.CASCADE) sports=models.CharrField(max_length=30) line=( ('Beginner','Beginner'), ('Intermediate','Intermediate'), ('Advance','Advance'), ) level=models.CharField(max_length=50,choices=line) class Session(models.Model): Person=models.Foreignkey(User) Level= -
django rest framework fails to serialize foreignkey field from string value
I am trying to submit post data to an api endpoint, which should create a model instance and return the object back in the response. And here is the returned error message. IntegrityError at /api/messages/ null value in column "sender_id" violates not-null constraint DETAIL: Failing row contains (27, null, null, this is a test message, warning: this is a test. this is only a test. please disregard. ..., f, null, f, f). Those first two null fields should be the sender and receiver, which I assume aren't being serialized properly. The post request body looks like this. sender and receiver are foreign key fields. { "sender": "user1", "receiver": "user2", "subject": "this is a test message", "body": "warning: this is a test. this is only a test. please disregard. say hello to your mother for me.", "read": false, "sender_deleted": false, "receiver_deleted": false } Here are my model and view. class MessageSerializer(serializers.HyperlinkedModelSerializer): pk = serializers.IntegerField(read_only=True) sender = serializers.StringRelatedField() receiver = serializers.StringRelatedField() class Meta: model = Message fields = ['pk', 'sender', 'receiver', 'subject', 'body', 'read', 'sender_deleted', 'receiver_deleted'] class Message(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_mail') receiver= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_mail') subject = models.CharField(max_length=50, default='') body = models.TextField() read = models.BooleanField(default=False) sender_deleted = models.BooleanField(default=False) receiver_deleted = … -
How to create a Django API using django rest framework which shows response from some external source?
Hi all i am in a situation where i need to create a djnago api which on call from frontend gives a response fetched internally from some other source but not from serializers and models. Currently i am using djnago rest framework to create api like below MODELS # Create your models here. class submission(models.Model): # fixed fields to show on today panel/pending panel email_id = models.CharField(max_length=200, primary_key=True) email_sender = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.email_id SERIALIZERS class UserSerializer(serializers.ModelSerializer): class Meta: model = submission fields = ('__all__') VIEWS class SAMPLE(viewsets.ModelViewSet): queryset = submission.objects.all() serializer_class = UserSerializer URLS router = DefaultRouter() # user table router.register('user_table_all_data', SAMPLE, basename='user_table_all_data') and it works as charm , but in order to work with djnago rest framework i always need to call like this 1. create model or use existing model, 2. Create serializers,3. Create Views,4 create URLs, But what if i dont want to use Models say for example i want to show data from other source say which contains a sample json like below sampleData = {"Name":"RAJNISH","Age":32,"ADDRESS":"India"} so if my API is say 'sample/someid (not pk)' returns {"Name":"RAJNISH","Age":32,"ADDRESS":"India"} as response how can i do this in djnago rest framework -
django returns NoReverseMatch but it actually got the value
I'm making a shopping cart app for my website, and the function that worked yesterday was broken today. I got Reverse for 'delete-cart' with arguments '(4,)' not found. 1 pattern(s) tried: ['cart/delete_cart/<int:pk>']error, But you can see that it has displayed the value of the parameter, proving that it got the value but still returned the not found error, why??? Here is my relevant code: urls.py urlpatterns = [ path('',views.myCartListView,name='my-cart'), url(r'^delete_cart/<int:pk>',views.delete_cart,name='delete-cart'), ] views.py @login_required def myCartListView(request): context = {} if request.user: data = Cart.objects.filter(client=request.user) context['cart'] = data return render(request,'cart/my_cart.html',context) @login_required def delete_cart(request,pk): record = Cart.objects.get(pk=pk) record.delete() return redirect('cart/') my_cart.html {% for c in cart %} <tr> <th>{{c.item}}</th> <th>{{c.quantity}}</th> <th>{{c.price}}</th> <th>{{c.get_total_price}}</th> <th><a href="{% url 'delete-cart' c.id %}">DELETE</a></th> </tr> {% endfor %} -
The requested resource was not found on this server. django
I have added my path into urlpatterns songs.urls file which was included in 1 views.py error occured -
Django query expression for counting particular attendance
I have a field that has 1000 rows. In these rows there are 2 status available. Present and Absent. I want to know if there's a query expression to count the total number of students present or absent. class StudentInClass(models.Model): Attendance = models.CharField(max_length=20, default='None') Total_Present = models.IntegerField Total_Absent = models.IntegerField -
DJANGO:How to remove empty QuerySet from the list of QuerySet
This is my list of QuerySets.Now my concern is to remove the list of empty QuerySet i.e.QuerySet [] from the given list. [QuerySet [], QuerySet [], QuerySet [], QuerySet [],[User: kharel321, User: kharelkharel]>] Expected OutPut [[User: kharel321, User: kharelkharel]] -
Django Sitemap Error: 'datetime.time' object has no attribute 'timetuple'
I am using django's built-in sitemap feature to dynamically create sitemap. But I am keep getting this error, and I don't know why? Please help me... Traceback: File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 16, in inner response = func(request, *args, **kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 77, in sitemap else site_lastmod.timetuple() AttributeError: 'datetime.time' object has no attribute 'timetuple' My Code: class NoteClassSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'monthly' def items(self): return Classes.objects.all().order_by('-date') def lastmod(self, obj): return obj.date -
Django - compare user objects by field
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
Unable to render the data from models to view in django framework
When i try to run a server,I am getting an error where it shows TypeError: 'Organization' object is not iterable. I am attaching the Model and views for the reference.Can you check and determine why i am getting the error. ''' Model.py from django.db import models # Create your models here. class Organization(models.Model): name = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Ticket_status(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): ticket_id = models.CharField(max_length=200, unique=True) orgname = models.ForeignKey(Organization, null=True, on_delete=models.SET_NULL) status = models.ForeignKey(Ticket_status, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.ticket_id ''' views.py ''' ----------- from django.shortcuts import render from django.http import HttpResponse from.models import * # Create your views here. def organization(request, orgname): organization_name=Organization.objects.get(id=orgname) organization_count=Organization.objects.get(id=orgname).ticket_set.all() return render(request,'ticket\organization1.html',{'organization_name':organization_name,' organization_count': organization_count}) ''' -
Django post save signal not updating the database
Im not getting why this signal is not working. This same code worked once but after that i deleted the objects from admin and ran it again and it stopped working. @receiver(post_save, sender=FinancePending) def calcualate_FinancePending(sender, instance, created, **kwargs): amount_paid = FinancePending.objects.values_list('amountPaid', flat=True) amount_paid = list(amount_paid) total_amount = FinancePending.objects.values_list('TotalAmount', flat=True) total_amount = list(total_amount) # total - paid TotalFee = [int(s.replace(',', '')) for s in total_amount] AmountPaid = [int(s.replace(',', '')) for s in amount_paid] finance_pending = FinancePending.objects.all() i = 1 while i <= len(TotalFee): amount_pending = TotalFee[i-1] - AmountPaid[i-1] amountpending = FinancePending.objects.filter(invoiceNumber=i) amountpending.AmountPending = amount_pending i = 1 + i -
one variable show other not, when pass post ajax in django
I don't Why I get this error, TypeError: 'method' object is not subscriptable same thing I used in another post request ajax I got all variable. but here I only get frm variable but not pk . HTML <form id="message-form" action="message/message_form/" user_id="{{u.id}}" method="POST"> {% csrf_token %} <div class="container"> <div class="row"> <div id="text" class="col-10"> {{ msgform.text }} </div> <div class="col-1"> <button id="submit" class="btn" type="submit"><img height="30px" src="/static/img/send-button.png" alt="send"></button> </div> </div> </div><br> </form> Script <script type="text/javascript"> var frm = $('#message-form'); var id; id = frm.attr("user_id"); frm.submit(function () { $.ajax({ type: frm.attr("method"), url: frm.attr("action"), dataType: 'json', data: { csrfmiddlewaretoken: "{{ csrf_token }}", pk:id, frm:frm}, error: function(data) { // $("#MESSAGE-DIV").html("Something went wrong!"); } }); return false; }); </script> views.py def post(self, request): new_msg = request.POST.get('text') print(new_msg) form = MessageForm() //I GET ERROR HERE MY PK VARIBLE NOT PRESENT IN REQUEST POST print('request.id is here',request.POST.get['pk']) u = get_object_or_404(User,pk=request.POST['pk']) msg = message.objects.filter(sender=request.user).filter(receiver=u).all() | message.objects.filter(sender=u).filter(receiver=request.user).all() if form.is_valid(): smg = form.save(commit=False) smg.sender = request.user smg.receiver = u smg.save() if request.user != u and User.objects.filter(receiver__receiver=u,receiver__read=False).exists: notify.send(request.user, recipient=u, verb="message you please read in message box",public=False) msg = message.objects.filter(sender=request.user).filter(receiver=u).all() | message.objects.filter(sender=u).filter(receiver=request.user).all() data = { "messages":msg} return HttpResponse(json.dumps(data), content_type='application/json') -
Django Wizard form with custom template
This is my wizard view: <div class="outer-panel"> <div class="outer-panel-inner"> <div class="process-title"> <h2 id="step-title-1" class="step-title is-active">Tell us more about you.</h2> <h2 id="step-title-4" class="step-title">Secure your account.</h2> </div> <form method="POST"> {% csrf_token %} {{ wizard.management_form }} {{ wizard.form.media }} <div id="signup-panel-1" class="process-panel-wrap is-narrow is-active"> <div class="form-panel"> <div class="field"> <label>First Name</label> <div class="control"> {{ form.f_name}} </div> </div> <div class="field"> <label>Last Name</label> <div class="control"> {{ form.l_name}} </div> </div> <div class="field"> <label>Email</label> <div class="control"> {{ form.email}} </div> </div> </div> <div class="buttons"> {% comment %} <a class="button is-rounded process-button" name="wizard_goto_step" data-step="step-dot-1">Back</a> {% endcomment %} <a class="button is-rounded process-button is-next" name="wizard_goto_step" data-step="step-dot-4">Next</a> </div> </div> <div id="signup-panel-4" class="process-panel-wrap is-narrow"> <div class="form-panel"> <div class="field"> <label>Password</label> <div class="control"> {{ form.password}} </div> </div> {% comment %} <div class="field"> <label>Repeat Password</label> <div class="control"> <input type="password" class="input" placeholder="Repeat your password"> </div> </div> {% endcomment %} <div class="field"> <label>Phone Number</label> <div class="control"> {{ form.phone}} </div> </div> </div> <div class="buttons"> <a class="button is-rounded process-button" data-step="step-dot-1">Back</a> {% comment %} <a class="button is-rounded process-button is-next" data-step="step-dot-5">Next</a> {% endcomment %} </div> </div> {% comment %} {% else %} {{ wizard.from }} {% endcomment %} </form> </div> </div> Form View: from django import forms class ContactForm1(forms.Form): f_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs= { 'class': 'input', 'placeholder':'Enter First Name' })) l_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs= { … -
How do I unit-test my Google Social Log-in View?
I have been wondering how I can test my custom Google social login view for my django project. Below is my views.py import json import ast import httplib2 import google.oauth2.credentials import jwt import requests from google.oauth2 import id_token from django.shortcuts import render from django.views import View from django.http import JsonResponse from apiclient import discovery from oauth2client import client from pinterrorist.settings import SECRET_KEY from .models import User, Social, Follow class GoogleLoginView(View): def post(self, request): token = request.headers["Authorization"] url = 'https://oauth2.googleapis.com/tokeninfo?id_token=' response = requests.get(url+token) user = response.json() if User.objects.filter(social_id = user['sub']).exists(): user_info = User.objects.get(social_id=user['sub']) encoded_jwt = jwt.encode({'id': user["sub"]}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : user['name'], 'user_pk' : user_info.id }, status = 200) else: new_user_info = User( social_id = user['sub'], username = user['name'], social_service = SocialPlatform.objects.get(name = "google"), email = user.get('email', None) ) new_user_info.save() encoded_jwt = jwt.encode({'id': new_user_info.id}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : new_user_info.username, 'user_pk' : new_user_info.id }, status = 200) and below is my test.py code so far... from django.test import TestCase, client from .models import User class GoogleLoginTest(TestCase): def setUp(self): client = Client() User.objects.create(username='john', social_service_id=1) def tearDown(self): User.objects.last().delete() def test_get_user_view(self): response = self.client.get('account/google') self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), { 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : new_user_info.username, 'user_pk' … -
Django rest framework, create Foreign key object
I have the following models in my API: class Message(models.Model): sender = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) sent_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='sent_to') sent_at = models.DateTimeField(default=timezone.now) subject = models.CharField(max_length=120, help_text='Message subject is limited to 120 characters') content = models.TextField(validators=[validate_message_content], help_text="Message Body") def __str__(self): return f"{self.subject} : \n {self.content} " class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=120) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] messages = models.ForeignKey(related_name='messages', on_delete=models.CASCADE, to=Message, null=True ) def __str__(self): return f"{self.username}" def read(self): self.last_read_date = timezone.now() self.save() And the serializers: class MessageSerializer(ModelSerializer): class Meta: model = Message fields = ('subject', 'sent_to', 'content') class UserSerializer(HyperlinkedModelSerializer): messages = MessageSerializer(many=True) url = HyperlinkedRelatedField(view_name='UserViewSet', read_only=True) class Meta: model = User fields = ( FieldsConsts.URL, FieldsConsts.EMAIL, FieldsConsts.FIRST_NAME, FieldsConsts.LAST_NAME, FieldsConsts.PASSWORD, FieldsConsts.MESSAGES ) extra_kwargs = {FieldsConsts.PASSWORD: {SerializerFields.WRITE_ONLY: True}, FieldsConsts.SENDER: {SerializerFields.READ_ONLY}, FieldsConsts.SUBJECT: {SerializerFields.ALLOW_NULL: False, SerializerFields.REQUIRED: True}, FieldsConsts.CONTENT: {SerializerFields.ALLOW_NULL: False, SerializerFields.REQUIRED: True}, FieldsConsts.SENT_TO:{} } def create(self, validated_data): password = validated_data.pop(FieldsConsts.PASSWORD) user = User(**validated_data) # Hash passwords user.set_password(password) msg_data = validated_data.pop(FieldsConsts.MESSAGES) User.objects.create(**validated_data) for msg_data in msg_data: Message.objects.create(user=user, **msg_data) user.save() return user def update(self, instance, validated_data): instance.FieldsConsts.EMAIL = validated_data.get(FieldsConsts.EMAIL, instance.FieldsConsts.EMAIL) instance.save() return instance And the view: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [AllowAny] elif self.action … -
What is the best practices or pattern for creating sync (real time and offline) using Django?
I guess it's better to use WebSockets (channels). But the question is how can I guarantee that every device will have the latest set of data. For example when one device goes offline, then back online is Django channels gonna send messages again to him? Any suggestions for articles or examples? Thanks in advance.