Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax call takes too much more time to be resolved
The waiting (TTFB) takes many seconds (52s) as we can see here enter image description here and I don't know the reason that caused the delay and the only thing I doubt is in an external directory ("app") I have added to my django's view because when I don't use it, everything goes well, and here my project structure. . ├── app | |_ __init__ | |_ oop(.py) | ├── conjug_app │ |_ __init__ | |_ admin | |_ apps | |_ models | |_tests | |_views │ ├── _my_conjugaison │ |_ __init__ | |_ asgi | |_ settings | |_ urls | |_wsgi ├── templates │ |_ "some files here" │ ├── manage(.py) My AJAX call: $(document).ready(function(){ $(".btn").on("click",(e)=>{ e.preventDefault(); // Get the current button value let vrb = e.target.innerText; //Get the value of the search input let getInputval = $('#searched_vrb').val(); if(vrb == 'Recherche'){ vrb = getInputval; }else{ vrb = vrb; } $.ajax({ type : 'POST', url : '/footer/', async: true, data : { csrfmiddlewaretoken: $('input[name = csrfmiddlewaretoken]').val(), verb_name: vrb, }, success: function (data) { $('body').html(data); }, error: function (data) { alert("it didnt work"); } }) }); }) the Views.py: def Footer(request): res0 = [] context = {} context0 = … -
How to send Django-Template variable to Morris.Line data variable?
I am trying to draw a chart with Morris.line. I have to draw a couple of them so I am trying to make a chart dynamically with for loop. Template.html - body {% for data in datas %} <div class="col-xl-6"> <div class="card"> <div class="card-header" id="test"> <input type="hidden" id="myVar" name="variable" value="{{ data.data|safe}}"> <h5>{{data.id}}</h5> </div> <div class="card-block"> <div id="myfirstchart" style="height:300px"></div> </div> </div> </div> {% endfor %} Template.html - Scripts <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var myVar = document.getElementById("myVar").value; new Morris.Line({ // ID of the element in which to draw the chart. element: 'myfirstchart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: myvar, // The name of the data record attribute that contains x-values. xkey: 'day', // A list of names of data record attributes that contain y-values. ykeys: ['value'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Value'] }) }); </script> here is my view: def data_chart(request): markets = Markets.objects.all().filter(~Q(spider=5)) cutoff = datetime.date.today() - datetime.timedelta(days=7) datas = [] for market in markets: raw_data = ( Products.objects.filter(created_dates__gte=cutoff) .values_list("created_dates__date") .filter(market=market.id) .annotate(count=Count("id")) .values_list("created_dates__date", "count") ) data = [{"day": str(day), … -
Mysql: Django: How to solve Mysql server gone away error
I am using mysql and Django: In Django using celery i get data from 10,000 api connections and then insert the data (10,000 bulk inserts) into sql table everyday. I have my table indexed for certain columns also Sometimes after 1000+ api connections, get mysql server gone After reading many solutions i am running import django.db django.db.close_old_connections() before every api connect. I am not sure will this solve my problem, i am still checking it after implementing it. Can any one give some confirmation will this solve my problem -
DRF Implementing Search Function based on Child field
I need some suggestion. Current my models are define as User = settings.AUTH_USER_MODEL class Profile(models.Model): #originally this is a one-to-one field but will cause an error in my nested serialization Userid= models.ForeignKey(User,on_delete=models.CASCADE,related_name='profile') X= models.CharField(max_length=50) class Post(models.Model): Postid = models.AutoField(primary_key=True) Userid = models.ForeignKey(User,on_delete=models.CASCADE ,related_name='posting') Y = models.TextField() User Model is the Django build in 'auth_User'. And my serialize.py is class viewchildItemSeralizer(serializers.ModelSerializer): class Meta: model=Post exclude = ['Z'] #some other field in post that is not required class viewchildProfileSeralizer(serializers.ModelSerializer): class Meta: model=Profile fields=['X'] class ViewItemSeralizer(serializers.ModelSerializer): posting= viewchildItemSeralizer(read_only=True ,many=True) profile = viewchildProfileSeralizer(read_only=True,many=True) class Meta: model=User fields=['username','email','posting','profile'] The code work fine(I am able to response in Json) if my search is base on the X field in the Profile.But I would also need to Implement another search function where base on the "search_argument" on Y field in Post I am able to return only the particular row value along with some data in User( username,email ) and Profile(X). I do not think that the queryset will be User.objects.filter(post__Y=searcharg) # as that will just return all the Post Item for that User #Unsure what would be the queryset if I am query from Post.. will search__related help ? plus, most likely I would also need … -
Django Form Render in Bootstrap Modal
I hope you could help me to solve this. I have a bootstrap modal HTML template with tabs Login/Register. More specifically in the home page there is a button when clicked a popup appears with 2 tabs buttons Login (tab1), Register (tab2). Below is the html code: <!-- Main Header Nav Starts --> <header class="header-nav menu_style_home_one navbar-scrolltofixed stricky main-menu"> <div class="container-fluid p0"> <!-- Ace Responsive Menu --> <nav> <!-- Menu Toggle btn--> <div class="menu-toggle"> <img class="nav_logo_img img-fluid" src="{% static 'images/header-logo.png' %}" alt="header-logo.png"> <button type="button" id="menu-btn"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <a href="{% url 'index' %}" class="navbar_brand float-left dn-smd"> <img class="logo1 img-fluid" src="{% static 'images/header-logo.png' %}" alt="header-logo.png"> <img class="logo2 img-fluid" src="{% static 'images/header-logo2.png' %}" alt="header-logo2.png"> <span>Evillio</span> </a> <!-- Responsive Menu Structure--> <!--Note: declare the Menu style in the data-menu-style="horizontal" (options: horizontal, vertical, accordion) --> <ul id="respMenu" class="ace-responsive-menu text-right" data-menu-style="horizontal"> <li> <a href="{% url 'dashboard' %}"><span class="title">Manage Property</span></a> </li> <li> <a href="#"><span class="title">Blog</span></a> </li> <li class="last"> <a href="{% url 'contact' %}"><span class="title">Contact</span></a> </li> <li class="list-inline-item list_s"><a href="" class="btn flaticon-user" data-toggle="modal" data-target="#bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a></li> <li class="list-inline-item add_listing"><a href="#profile"><span class="flaticon-plus"></span><span class="dn-lg"> Create Listing</span></a></li> </ul> </nav> </div> </header> <!-- Main Header Nav Ends --> <!-- Login/Register Starts --> <!-- Modal --> <div … -
DRF PATCH on ManytoMany Field
I would like to add a M2M entry using DRF to my model. And I found this article https://medium.com/@kingsleytorlowei/building-a-many-to-many-modelled-rest-api-with-django-rest-framework-d41f54fe372 The issue I have is, when I use "PATCH" to an asset nothing appears. models : class Asset(models.Model): [...] vulnerabilities = models.ManyToManyField("Vulnerability",verbose_name="vulnerability",blank=True,) class Vulnerability(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) level = models.PositiveSmallIntegerField() serializers: class VulnerabilitySerializer(serializers.ModelSerializer): key = serializers.CharField(source='id', read_only=True) controls = ControlSerializer(read_only=True, many=True) class Meta: model = models.Vulnerability fields = ( 'key', 'id', 'name', 'level', 'controls', ) class AssetSerializer(serializers.ModelSerializer): key = serializers.CharField(source='id', read_only=True) class Meta: model = models.Asset fields = ( 'key', 'id', 'name', 'weight', 'vulnerabilities', ) depth = 3 When I GET /api/asset/xxx { "key": "xxx", "id": "xxx", "name": "aaaaaaaaaaaa", "weight": 3, "vulnerabilities": [ { "id": "V004", "name": "xazeaze", "level": 3, "controls": [] } ] } So I try to POST an asset and it works : { "key": "A099", "id": "A099", "name": "Asset 999", "weight": 10, "vulnerabilities": [] <---- empty } BUT, when I want to PATCH/PUT for adding Vulnerabilities, there is nothing : Assets Id are "Axxx" Vulnerabilities Id are "Vxxx" as primary_key PATCH ./api/asset/A099 data : { "vulnerabilities": ["V001","V002"] } it returns an empty vulnerabilities: { "key": "A099", "id": "A099", "name": "Asset 999", … -
Django App Deployment to Azure Failing Via Three Methods (problems creating/accessing tmp files)
I have been trying to upload the code from my Django app to Azure. Using multiple methods, it has been failing, with the log messages shown below. The failure seems to relate to the creation of temporary directories by Onyx build. To be transparent, I'm new to both Django and Azure. First, I worked through the Azure tutorial (link below) and was able to get it working with minimal issues. https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone When I attempted to follow the same steps (using "webapp up") with my own app, I get the following error message: Zip deployment failed. {'id': 'XXXXX', 'status': 3, 'status_text': '', 'author_email': 'N/A', 'author': 'N/A', 'deployer': 'Push-Deployer', 'message': 'Created via a push deployment', 'progress': '', 'received_time': '2020-10-21T13:59:11.0137785Z', 'start_time': '2020-10-21T13:59:11.3572791Z', 'end_time': '2020-10-21T13:59:34.2598809Z', 'last_success_end_time': None, 'complete': True, 'active': False, 'is_temp': False, 'is_readonly': True, 'url': 'https://att-informativeness-task.scm.azurewebsites.net/api/deployments/latest', 'log_url': 'https://att-informativeness-task.scm.azurewebsites.net/api/deployments/latest/log', 'site_name': 'att-informativeness-task'}. Please run the command az webapp log deployment show -n att-informativeness-task -g DjangoPostgres-attInform-rg Running the command they recommend, az webapp log deployment show -n att-informativeness-task -g DjangoPostgres-attInform-rg I get: [ { "details_url": null, "id": "XXXXXX", "log_time": "2020-10-21T13:59:11.2061269Z", "message": "Updating submodules.", "type": 0 }, { "details_url": null, "id": "XXXXXX", "log_time": "2020-10-21T13:59:11.324348Z", "message": "Preparing deployment for commit id '53d578b78c'.", "type": 0 }, { "details_url": null, … -
Multiple requests at same time in Django with Sqlalchemy
I am using Django with Sqlalchemy , I am worried about the situation where lets say multiple users request at the same time. I have connection setup with odbc like given below: enginemssql = create_engine(f'mssql+pyodbc://{username}:{password}@DB') do i need to change the connection to avoid exception when multiple requests are made at the same time ? any suggestion will be helpful Thanks -
Django, how to get the time until a cookie expires
Before marked as dup (I believe many answers are incorrect becase): According to my research: request.session.get_expiry_age returns the TOTAL lifespan of the cookie, not the time from now until it expires. It always returns the same value, irrespecitive of how much time is left. Similarly get_expiry_date adds the total lifespan to the now time. It always increases when called. Hence niether of them help. settings.SESSION_SAVE_EVERY_REQUEST refreshes the cookie on every request, this is NOT what I am trying to achieve. get_session_cookie_age() ONLY returns the value of settings.SESSION_COOKIE_AGE, as seen in the sourcecode: def get_session_cookie_age(self): return settings.SESSION_COOKIE_AGE I use the cached_db session back end. The cached part is made none in void because it has to save the cookie everytime, hence SESSION_SAVE_EVERY_REQUEST is not applicable. The reason I ask this question is because I wish to refresh a cookie ONLY if the time left has gone below a threshold, and hence have some hysterious (have the benefits of caching and auto refreshing). Here is my code that does not work because of the behaviour of get_expiry_age/get_expiry_date as explained above: from django.conf import settings from django.utils.deprecation import MiddlewareMixin class SessionExpiry(MiddlewareMixin): def process_request(self, request): """Automatically refresh a session expirary at a certain limit. … -
func form.is_valid() return all time False
I have a form that takes "username" from the User model and my own "email" field. I want to change this data for the User model. At first glance everything seems to work fine, the name changes and the mail is the same. But if I only change the mail and I don't touch the username, I get an error: "A user with this name already exists. file views.py: form=UserUpdateForm(request.POST) if form.is_valid(): user=User.objects.get(username=self.request.user) user.username=form.cleaned_data.get('username') user.email=form.cleaned_data.get('email') user.save() file forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=False) def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) if 'label_suffix' not in kwargs: kwargs['label_suffix'] = '*' self.fields['username'].widget = forms.TextInput(attrs={'class':'input-text'}) self.fields['email'].widget = forms.EmailInput(attrs={'class':'input-text'}) class Meta: model = User fields = ("username","email",) def clean_email(self): cleaned_data = super(UserUpdateForm,self).clean() email=cleaned_data.get('email') return email -
from Django email coming to my Gmail account but sender detail(empty email coming) not coming in my Gmail please suggest any solutions
from Django empty message coming to my Gmail account message body not coming def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_phone = request.POST['message-phone'] message_body = request.POST['message-body'] message_email = request.POST['message-email'] send_mail( 'message_name', 'message_body', 'message_email', ['mye@gmail.com'], fail_silently=False, ) return render(request, 'contact.html', {'message_name': message_name}) else: return render(request, 'contact.html', {})** -
Get the url that should have a function which renders an HTML, Django doesn't show it and returns TemplateDoesNotExist
I want to show an html file when I go to http://localhost:8000/signup/. I tried this views.py: from django.shortcuts import render def signupuser(request): return render(request, 'todo/signupuser.html') And here is urls.py: from django.contrib import admin from django.urls import path from todo import views urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signupuser, name="signupuser") ] But it returns: Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\antoi\Documents\Programming\Learning\Django\todowoo\todo\views.py", line 5, in signupuser return render(request, 'todo/signupuser.html') File "C:\Python36\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: todo/signupuser.html [20/Oct/2020 19:10:08] "GET /signup/ HTTP/1.1" 500 78389 Pero el template existe, esta en C:\Users\antoi\Documents\Programming\Learning\Django\todowoo\todo\templates\todo -
Sending data as JSON file in a django site using python
I am having problems with passing data from my site build with Django to Azure logic app. Currently data is passed as follows: post_data = {'text_thing': text_thing, 'number_thing': number_thing} files = { 'json':(None, json.dumps(post_data), 'application/json') } #a django function that sends 'files' to logic app response = requests.post('example.com', files=post_data) I am unable to read it using Parse JSON function. Is this a correct way of sending data encoded as JSON? -
Django login authentication and session without user models and ORM
For various reasons, I cannot use Django's ORM features. Instead I have to query into a database to check passwords instead of using models. I can already do that. But I can't figure out how to make a custom auth backend work with that. This doc page details how to set up a custom auth backend. However, I am unsure as to how it is still tracking whether a user is logged in. The authenticate and validate functions seem to be returning a User Object. And session seems to be used to track logged in users. What I don't understand is how to make that work with a custom user class that doesn't use models. How am I supposed to get the session key? Why is it set SESSION_KEY = '_auth_user_id' at the start of init.py? Does that get updated when user logs in? And What is session_auth_hash? Request.user exists. But if I set it for one request, do all subsequent requests in that session refer to that user? All I want to do is let a user login and logout after matching database credentials. -
How to add an optional slug in a Django Url
I want to add an optional Stackoverlow like slug to my urls in Django path( r"item/<int:pk>/<slug:slug>", ItemDetailView.as_view(), name="item_detail", ), How do I make the slug optional so that it works in all three cases: item/1 item/1/ item/1/slug -
How to display uploaded Dicom image metadata in detailed view in Django?
I am a new to coding and working on a small Django project in which I want to display Dicom image metadata. I included FileField in the Django model to upload a Dicom image and I want to display the uploaded Dicom image metadata in Generic detailed view. I tried overriding the context method and accessing the image path but getting an error. How do I proceed with it? Please help! #My model class Patient(models.Model): name = models.CharField(max_length=100) ailment = models.TextField(max_length=200) date_tested = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='.',default='download.jpg') dicom = models.FileField(upload_to='dicom/',null=True) #My Detailed view class PatientDetailView(LoginRequiredMixin,DetailView): model = Patient def get_context_data(self,**kwargs): medinfo = dict() context = super().get_context_data(**kwargs) dcpimg = imageio.imread(self.dicom.path) for keys in dcpimg.meta: medinfo[keys] = str(dcpimg.meta[keys]) context['medinfo'] = medinfo return context ##Iam getting this error AttributeError: 'PatientDetailView' object has no attribute 'dicom' -
Django raw sql or stored proc to run paramatised view?
Thanks in advance for advice. I'm new-ish to Django, creating a site with (amongst other things) products that people can upvote (ie 'like'). I'm showing related liked products at the end of the product detail page (ie people that likes this product also liked these products). Method I'm doing recording likes is a link table that pairs product ID with user ID. To get the related products is a reverse lookup on the upvote table. My SQL code does this fine, and I can feed the result to get a collection of related products in a class function: def related_products(self, max_results=4): sql = f"\ SELECT PRODUCT_ID AS ID\ FROM PRODUCTS_UPVOTE\ WHERE VOTER_ID IN ( \ SELECT VOTER_ID\ FROM PRODUCTS_UPVOTE\ WHERE PRODUCT_ID = {product_id} \ )\ GROUP BY PRODUCT_ID\ HAVING PRODUCT_ID != {product_id}\ ORDER BY COUNT(PRODUCT_ID) DESC\ FETCH FIRST {max_results} ROWS ONLY" return Product.objects.raw(sql) This works fine, but it doesn't 'feel' right putting lines of SQL code in the model like this - surely better to use a stored proc? But I see many sites warning against this. Or maybe there's a better way to handle running views with parameters in this that I'm not seeing? What's the recommended method for … -
How to upload a File from a form in Django
I want to upload a file to an S3 location from a form. I'm using Python3 and django This is what I have in my model: class MediaSubtitle(models.Model): media = models.ForeignKey( "Media", related_name='%(app_label)s_%(class)s_media', verbose_name="Media") language = models.CharField( max_length=255, db_index=True, verbose_name="Taal", blank=False, null=False) source = models.FileField( upload_to='subtitles/%Y/%m/%d', blank=True, validators=[FileExtensionValidator(allowed_extensions=['srt', 'sub'])]) def __str__(self): return "%s" % (self.media,) class Meta: verbose_name = "Media Ondertitel" verbose_name_plural = "Media Ondertitels" And this is what I use in my forms.py: class AddSubtitleForm(forms.ModelForm): def __init__(self, parent, **kwargs): super().__init__(**kwargs) self.parent = parent self.fields["language"].required = True self.fields["source"].required = False def save(self): result = MediaSubtitle( language=self.cleaned_data["language"], source=self.data["source"], media=self.parent) return result.save() class Meta: model = MediaSubtitle fields = ("language", "source") How Can I make sure that the moment the save is executed that the file is uploaded? -
I want to render a page only when the user is logged in, otherwise render the login page. I'm using firebase for authentication
from django.shortcuts import render from django.contrib import auth import pyrebase config = { 'apiKey': "", 'authDomain': "", 'databaseURL': "", 'projectId': "", 'storageBucket': "", 'messagingSenderId': "", } firebase = pyrebase.initialize_app(config) database = firebase.database() _auth_ = firebase.auth() def loggedin(request): email = request.POST.get('email') password = request.POST.get('password') try: user = _auth_.sign_in_with_email_and_password(email,password) except: message = "Invalid Credentials" return render(request,'signin.html',{"messg":message}) session_id = user['idToken'] request.session['uid'] = str(session_id) return render(request,'loggedin.html',{"e":email}) def logout (request): auth.logout(request) return render(request,'signin.html') def joinexam(request): #i want to render this page only when the user is logged in return render(request,"joinexam.html") I want to render the "joinexam.html" page only when the user is logged in. If the user isn't logged in and tries to access 127.0.0.1:8000/joinexam i want to redirect the user to login page -
OnetoOneRelatedField model details are not populating while trying to post details through APIVIew in Django Rest Framework
models.py class Address(models.Model): name=models.CharField(max_length=100,default='') place=models.CharField(max_length=100,default='') class wish(models.Model): created=models.DateField(auto_now_add=True) title=models.CharField(default='',null=True,blank=True,max_length=100) wishtext=models.CharField(max_length=1000) address=models.OneToOneField(Address,null=True,on_delete=models.CASCADE,) serializers.py file. class WishSerializer(serializers.ModelSerializer): class Meta: model = wish fields = ['id','title','wishtext','address'] depth=1 views.py class WishList(generics.ListCreateAPIView): #permission_classes = [permissions.IsAuthenticated] queryset=wish.objects.all() serializer_class = WishSerializer Note: am able to get the all details including address model details. But when i am trying to post details ,able to see only wish model fields but not the address object drop down field. Please help me on this? -
Unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
I am trying to calculate the difference between 2 dates in weeks. One date gets fetched from database and the field is defined as models.DateField(blank=True, null=True). I want to calculate the difference between the date from database and today. After watching some tutorials, I came up with this implementation: serializer.py: foo = Foo.objects.get(id=1) calculate_difference_between_two_dates_in_weeks(get_today(), foo.start_date) The value of start_date in database is only 2020-10-23. utils.py: from datetime import datetime, timedelta from django.utils import timezone def get_date_in_datetime(date): time = datetime.min.time() return datetime.combine(date, time) def get_today(): return timezone.now() def calculate_difference_between_two_dates_in_weeks(date_one, date_two): d1 = get_date_in_datetime(date_one) d2 = get_date_in_datetime(date_two) d1 = (date_one - timedelta(days=date_one.weekday())) d2 = (date_two - timedelta(days=date_two.weekday())) return (d2 - d1).days / 7 I keep getting an error saying unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'. When I print d1 and d2 after d2 = get_date_in_datetime(date_two), I get 2020-10-21 00:00:00 for d1, and 2020-10-23 00:00:00 for d2. They look the same but I still get the same error. How can I convert datetime.datetime to datetime.date or vice versa to have the same type so the calculate_difference_between_two_dates_in_weeks function can work? -
Disable original text error messages in Django
I have a model in which for each field I have written text messages for errors. But if you enter incorrect data, native Django messages are displayed. How do I display mine? class AbstractUser(AbstractBaseUser, PermissionsMixin): """Создал абстрактоного юзера от которого будут унаследованны остальные юзеры""" phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', error_messages={'blank': "This field cannot be blank", 'invalid': "Phone number field is not valid", 'unique': "This phone number is already registered", } ) According to my model, if the field is empty, there should be an error "Phone number field cannot be blank" -
Count number of element exits on db: Django
I want to count the car_model that exits on db. if car_model do not exits then it should count zero. Any help would be much appreciated. Thank you so much in advance. models.py class CarOwnerCarDetails(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) car_model = models.CharField(max_length=10) views.py class CarModelListView(ListAPIView): # permission_classes = (IsAuthenticated,) def get(self,request,*args,**kwargs): qs = CarModel.objects.all() serializer = CarModelListSerializer(qs,many=True) data = serializer.data return Response({ 'success' : 'True', 'message' : 'Data retreived successfully', 'data' : data, },status=HTTP_200_OK) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data["car_model"] = CarOwnerCarDetails.objects.count() data.append(car_model) print(car_model) return data -
How to check if a user has new notifications
my question is this: If a user is returned a list of notifications on a page (via Django api endpoint) , how can I check which notifications have been viewed and which are new? I've been thinking of something along the lines of like: storing the length of the notifications array from the previous session and comparing it to the new array. If the length is longer, then a notifications component is displayed. Can this be done with cookies or something built into Vue? Right now Directors are able to view an application that a user submits and change the status to 'accepted' or 'rejected'. Users can then see that change on their end when they visit /applications. <p>Status: {{application.status}}</p> I was thinking of including a POST request with the director's PATCH request to create a new notification object. Hence, what I described above. Directors can change the application decision via PATCH methods: { applicationDecision($axios, params) { const config = { headers: { "content-type": "application/json; " } }; let response = this.$axios.$patch( `/api/v1/apps/${this.applicants.id}/`, this.application, config ); Users accessing their applications async asyncData({ params, $axios, store }) { try { const body = store.getters.loggedInUser.id; let applications = await $axios.$get(`/api/v1/apps/`, { params: … -
Implementing point search in a polygon using Django
There were some difficulties while implementing my application in django. What the app should do: Accepts and saves Delivery zones as a set of coordinates; Accepts data from Couriers with reference to the delivery area; Accepts the coordinates of the delivery location and returns the Courier data and the Delivery zone ID. I coped with two points, but there were problems with the last one. I found how to solve this problem using Python shell: from django.contrib.gis.geos import GEOSGeometry p = GEOSGeometry(location, srid=4326) DeliveryZone.objects.filter(coordinates__contains=p) But I don't know how to implement this inside my app. My models.py from django.contrib.gis.db import models class DeliveryZone(models.model): coordinates = models.MultipolygonField(srid=4326) def __str__(self): return f"#{self.id}" class Courier(models.model): delivery_zone = models.ForeignKey(DeliveryZone, on_delete=models.protect) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return f"#{self.id} {self.last_name}" class Delivery(models.model): location = models.PointField(srid=4326) def __str__(self): return f"#{self.id}" And views.py from django.contrib.gis.geos import GEOSGeometry from rest_framework import viewsets from .serializers import DeliveryZoneSerializer, CourierSerializer, DeliverySerializer from .models import DeliveryZone, Courier, Delivery class DeliveryZoneViewSet(viewsets.ModelViewSet): queryset = DeliveryZone.objects.all() serializer_class = DeliveryZoneSerializer class CourierViewSet(viewsets.ModelViewSet): queryset = Courier.objects.all() serializer_class = CourierSerializer class DeliveryViewSet(viewsets.ModelViewSet): queryset = Delivery.objects.all() serializer_class = DeliverySerializer I can provide more information if necessary.