Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter NeoModel Nodes by Relationships in Python
I have the 2 StructuredNodes User and Token as a one to one relationship. Coming from using Django for relational databases, if I want to get the User given a token, I'd simply do User.objects.get(token__key=token). But using Neo4j with NeoModel, I'm struggling to find a way to do this simple query. Also, when I have the User instance, I can do user.token.single() to get the Token instance, but the same doesn't work the other way around. token.user.single() returns CardinalityViolation: Expected: one relationship in a outgoing direction of type FOR_USER on node (49) of class 'Token', got: none. and token.user returns a neomodel.cardinality.One object. class User(DjangoNode): uid = UniqueIdProperty() firstname = StringProperty(index=True, required=True) lastname = StringProperty(index=True, required=True) email = EmailProperty(unique_index=True, required=True) password = StringProperty(requried=True) token = RelationshipFrom('Token', 'OWNS_TOKEN', cardinality=One) def post_create(self): token = Token().save() self.token.connect(token) class Token(DjangoNode): user = RelationshipTo('Token', 'FOR_USER', cardinality=One) key = StringProperty(unique_index=True, default=generate_key) created = DateTimeProperty(default_now=True) -
Is it possible to query database using a variable as the model name?
I have a lot of models in one app. I need to iterate over them based on a corresponding value. So for example: for x in dictionary: q = x.objects.get() Where x is the string variable name of the model and q is the desired query set -
Saving values set in Frontend to Django Database
I have a website which allows Users to pick a few hobbies they enjoy. Currently the website loads these hobbies from a Model and lists them with a Checkbox. What I want to do is when a User saves the form, it should also save these Checkbox values to the database - i.e if they tick Football, the database should save the fact that this User enjoys football. I am new to Django and Python so not too sure how to accomplish this. Here is the code I am using. This is the Models.py file for the Hobbies: TYPES = ( ("Football", "Football"), ("Cricket", "Cricket"), ("Swimming", "Swimming"), ("Cycling", "Cycling") ) class Hobby(models.Model): myfield = models.CharField(max_length=50, choices = TYPES, default=TYPES[0], null=True) football = models.BooleanField(default = False) cricket = models.BooleanField(default = False) swimming = models.BooleanField(default = False) cycling = models.BooleanField(default = False) This is the relevant views.py file: def profile(request, user): # use this for debugging: # import pdb; pdb.set_trace() if 'email' in request.POST: email = request.POST['email'] gender = request.POST['gender'] dob = request.POST['dob'] ## hobby = request.POST['hobby'] if user.profile: user.profile.email = email user.profile.gender = gender user.profile.dob = dob ## user.profile.hobby = hobby user.profile.save() else: profile = Profile(email=email, gender=gender, dob=dob) profile.save() user.profile = … -
From java spring to python django
I have many years of experience writing backend applications using Java (in past years was focused more on JEE but recent years mainly springboot applications). Lately I started cooperating with several friends working on some project and everyone has some passion to python, I also have good memories from python development I did back then during my university days but also small projects I used python throughout my work. However, I mainly used python for short programs and not as a whole service exposing REST APIs. I started playing with Django to build a REST API service, but I find many different concepts I would expect when writing spring application. There are some minor things like having all my models in a models.py file and not having 1 file for module, and what bothers me even more is the lack of a business layer (@Service like in spring) and general separation between the client layer (that accepts the REST requests), service layer and data layer which uses the models. I would expect my client not to have models but rather DTOs. I tried to google how people overcome this messy architecture, but maybe I am missing something and the "hello … -
Import existing db to Django app container
I'm developing a new feature for our mobile app, but I'm working with a recently cloned local instance of our backend. I'm looking for a way to somehow import an existing .sql file to the Django docker container. It's a perfectly fitting db, the only issue is that I couldn't figure out how could I import it into the container/dev shell, currently it's outside the container. -
Django Chart.js ajax javascript "string data parsing error"
I am creating chart web page through Django and Chart.js (in the views.py of Django) class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): context = super(ChartView, self).get_context_data(**kwargs) context['labels'] = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"] context['datas'] = [12, 19, 3, 5, 2, 3] return context in the html file (template file) <script> $( document ).ready(function() { var data = { labels: {{ labels }}, datasets: [ { label: "Site Registrations in the Last 30 Days", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: {{ datas }} } ] }; var ctx = document.getElementById("myChart").getContext("2d"); var myLineChart = new Chart(ctx).Line(data); }); </script> The html page rendering is having error. (The page source looks like this) <script> $( document ).ready(function() { var data = { labels: [u&#39;Red&#39;, u&#39;Blue&#39;, u&#39;Yellow&#39;, u&#39;Green&#39;, u&#39;Purple&#39;, u&#39;Orange&#39;], datasets: [ { label: "Site Registrations in the Last 30 Days", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [12, 19, 3, 5, 2, 3] } ] }; var ctx = document.getElementById("myChart").getContext("2d"); var myLineChart = new Chart(ctx).Line(data); }); </script> Clearly, you can see that {{ datas }} are getting correct value. However, {{ labels }} are getting wrong values. I do … -
Django crazy URL rewrites
i'm currently facing a issue that i realy don't understand at all, i search trough the hole code and was not able to find any reffereces here, i delted all caches, databases, venv etc. With no effects at all. It's all about the 'login' url pattern urls.py from Project_Accounts import views as Project_Accounts .... url(r'^admin/', admin.site.urls), # Reg and Auth url(r'^login/$', Project_Accounts.login, name='login'), url(r'^signup/$', Project_Accounts.signup, name='signup'), .... urlpatterns += [ path('Project_Accounts/', include('django.contrib.auth.urls')), ] base.html {% if user.is_anonymous %} <a href="{% url 'signup' %}" class="top-menu"> <button type="button" class="btn btn-success">Sign-Up</button> </a> <a href="{% url 'login' %}" class="top-menu"> <button type="button" class="btn btn-primary">Login</button> </a> {% endif %} views.py (Project_Accounts) def login(request): if request.method == 'POST': form = LoginForm(request.POST, request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: request.session.flush() if user.pubpgp: if user.pubpgp_enabled: request.session['userID'] = user.pk return redirect(reverse('login_2fa')) else: hybridlogin(request, user) return redirect(reverse('home')) else: hybridlogin(request, user) # Redirect to a success page. return redirect(reverse('home')) else: return render(request, 'Project_Accounts/login.html', {'form': form}) else: return render(request, 'Project_Accounts/login.html', {'form': LoginForm()}) If my base.html gets displayd signup view works fine, and every other also execpt the login. The URL i get back for login is "127.0.0.1:8000/Project_Accounts/login" but it use to … -
What would be the most efficient way of creating charts/graphs with data from a Django backend
I built an application using Django and I was wondering what would the most efficient way of creating charts and graphs for my data (for personal viewing). I was thinking of having the charts/graphs in a dashboard with the ability to create and delete records in the database(perhaps in a different tab). Originally I was thinking of having this in the Django admin panel since I already use it a lot for looking at/deleting/creating small data. I researched various custom django admin libraries but a lot of them just seems like a UI improvement. Another small feature that I wanted was to regroup various models in different applications into one listing as opposed to the default layout where the main heading is the various django application and under each is the models for the application. I have a couple ideas about how to go about doing this: Create custom django admin template for what I need. This would include graphs/charts but I'm not sure about the regrouping. Maybe create a front-end application to do the graphs and make the groupings myself. This would communicate to the backend via GET/POST/DELETE requests. I would write something in the backend to transform the … -
How to model a one to many relationship in Django
in my current Django project I have list of players and a list of games and I'm looking for a Django field to store the information in which games the player participate. To give an example: User 1 played Game 1, 2, 3, and User 2 played 2, 3... Since not all players of a game are registered, I'm not looking for the relation game to player. So, I'm looking for something like an one-to-may field (player to several games). So far, I found the ForeignKey field. However, when I add this to game, I can only store one player not several player ids. Or do I missed something? How do I express my problem in Django model fields? -
Django: reset a specific field of a model every hour
I have a field in one of my models in django which I want to be reset every hour. (i.e. at each o'clock its value becomes zero) How can I do this task? Can I schedule a function in django? As you know we can define EVENTs and TRIGGERs in mysql and other database backend. Also I am familiar with signals in django but those can not fit in my needs. (because database event is somewhat outside of django and have problems; with signals although it seems this is impossible!) -
Error in function "int() argument must be a string"
I have issues with the following code in my Django project. Anyone one have a clue what's wrong? Exception Type: TypeError at /tasks/2/3/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' (Django 2.1) def step_detail(request, task_pk, step_pk): user = request.user steps = Step.objects.filter(task_id=task_pk) step = get_object_or_404(Step, task_id=task_pk, pk=step_pk) next = "" if int(Step.step_number) < len(steps): next = "/%s/%s/" % (task_pk, int(step_pk) + 1) user.userprofile.current_step.update(step_pk) else: next = "/task_done/" user.userprofile.current_step.update(step_pk) user.userprofile.daily_task_done_time(datetime.datetime.now()) if request.POST: if "nextstep" in request.POST: return redirect(request.POST.get('next')) return render(request, 'dailytask/step_detail.html', {'step': step}) Environment: Request Method: GET Request URL: http://127.0.0.1:8000/tasks/2/3/ Django Version: 2.1.1 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dailytask', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/iamsuccessful/ebdjango/dailytask/views.py" in step_detail 60. if int(Step.step_number) < int(len(steps)): Exception Type: TypeError at /tasks/2/3/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' -
Running Django on server with remote interpreter - Prevent Django from creating a test database
I'm trying to use PyCharm's remote interpreter capability to debug my Django app on our dev server. The connection is working, but when I try to run or debug using the remote interpreter I get this error from the run console: Creating test database for alias 'default'... Failed (ORA-01031: insufficient privileges) Got an error creating the test database: ORA-01031: insufficient privileges As far as I can tell, Django is trying to create a test database to use with my test cases. I don't have any test cases on our server yet and don't need them right now. I'm also using my personal schema of which I am the owner. How can I prevent Django from trying to create this database so that I can run my code? -
Django: Could someone help me convert a function based view into a class based view?
I'm having a lot of difficulty in converting the following function based view into a class based version. I need to display clickable boxes on a webpage that show the 'projects' that are in the database. The function based view that I have works perfectly but I cannot now translate it to a CBV. I'm hoping someone might be able to have a look at it and help structure my approach. I've been stuck for a long time on this. def assets_by_project(request): project_data = project.objects.all() query = request.GET.get('q') if query: results = box.objects.filter(Q(project_assigned_to__icontains=query)) else: results = "NA" return render(request, 'main_app/assets_by_project.html', { "project_data":project_data }) -
Django multilingual site
I am trying to create a multilingual website, which would get content from DB based on selected language. I can get the selected language easily using get_language() in the view. Right now, my models look like this (simplified): class Article(models.Model): author = models.CharField("Author", max_length=255) class ArticleText(models.Model): id = models.OneToOneField(Article, on_delete=models.CASCADE, primary_key=True) en = models.TextField("English") fr = models.TextField("French") My idea (based on research here on SO) was that I would store the article's text content elsewhere, linking it's primary key to the actual Article object's primary key. The Article model contains just general info (publish date, author, etc.), which is the same for all languages. However, I am not really sure how to access the data from my template. Right now I use: context["articles"] = models.Content.objects.select_related("id") I can then access the various fields in my template using {% for article in articles %} <h3>{{ article.author }} - {{ article.fr }}</h3> {% endfor %} However, I want the language ({{ article.$LANGUAGE }}) to change based on the selected language. Something like {{ article.$get_current_language }} --> {{ article.fr }} I guess I could do the following in the template: {% if get_current_language == en %} {{ article.en }} {% elif get_current_language == fr … -
Calling a foreign key relationship in an "if" statement in Django template
I have two models, Booking and Confirmation that are related via a ForeignKey relationship through "booking." I want to only display bookings in my detail view that have an attribute value of is_confirmed ==True. I don't really want a queryset, I just want to display the booking information from the "Booking" model if the confirmation is True in the template. models.py: class Booking(models.Model): user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE) expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings') title = models.CharField(max_length=200, default='Video call with ..', null=True) start_time = models.DateTimeField('Start time', null=True) end_time = models.DateTimeField('End time', null=True) notes = models.TextField('Notes', blank=True, null=True) class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' def get_absolute_url(self): return reverse('booking:booking_detail', kwargs={"pk": self.pk}) class Confirmation(models.Model): booking = models.ForeignKey(Booking, on_delete=models.CASCADE) expert_confirming = models.ForeignKey(CustomUser, on_delete=models.CASCADE) is_confirmed = models.BooleanField(default=False) def get_absolute_url(self): return reverse('booking:booking_detail', kwargs={"pk": self.booking_id}) views.py: class BookingDetailView(DetailView): model = Booking template = 'templates/booking_detail.html' booking_detail.html: <div class="container" id="booking_content"> <p>{{ booking.title }}</p> <p>{{ booking.start_time }}</p> <p>Booking request by: {{ booking.user }}</p> <p>Expert requested: {{ booking.expert }}</p></div> I'm not sure how the if statement in the template should reference these related models to display what I want. -
Django: Modify Class Based View Context (with **kwargs)
I've a Function definition that works perfect, but I need to update to a Class Based View. function def: def ProdCatDetail(request, c_slug, product_slug): try: product = Product.objects.get(category__slug=c_slug, slug = product_slug) except Exception as e: raise e return render(request, 'shop/product.html', {'product':product}) So far, I've read that to modify the context of a Class Based View (CBV) I need to overwrite the def get_context_data(self, **kwargs) in the CBV. So, I've done this: Class Based View: class ProdCatDetailView(FormView): form_class = ProdCatDetailForm template_name = 'shop/product.html' success_url = 'shop/subir-arte' def get_initials(self): # pre-populate form if someone goes back and forth between forms initial = super(StepOneView, self).get_initial() initial['tamanios'] = self.request.session.get('tamanios', None) initial['cantidades'] = self.request.session.get('cantidades', None) return initial # pre-populate form if someone goes back and forth between forms def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(category__slug=c_slug, slug = product_slug) return context def form_valid(self, form): # In form_valid method we can access the form data in dict format # and will store it in django session self.request.session['tamanios'] = form.cleaned_data.get('tamanios') self.request.session['cantidades'] = form.cleaned_data.get('cantidades') return HttpResponseRedirect(self.get_success_url()) How should I pass the arguments c_slug, product_slug to the get_context_data definition for this CBV to work as the Function definition? -
Django DB editing
import json from django.http import Http404, HttpResponse from main.models import Personnages def store_data(request): if request.is_ajax() and request.POST: value = request.POST.get("value") toChange = request.POST.get("name") id = request.POST.get("id") #A IMPORTER perso = Personnages.objects.get(id=id) perso.toChange = value perso.save() return HttpResponse(value+toChange) else : raise Http404 I have written this code (sorry for the french words) but the problem is that I don't find solution for the part perso.toChange = value Who actually doesn't work because I try to put the string extract from ajax instead of the field. But I haven't find a solution :x Thanks ! (Sorry for my poor english, I really try to improve it ^^) -
Is it possible to sort ManyToManyField in Django in an added order?
I'm using Django grappelli admin and its "Related lookup fields" like the image below. Fist, I store it in the below order. After submitting it, the order changes like the below. I need to keep the order that I pick one by one, however every time submitting it, the system changes the order. I tried to use ordering attribute in Meta class, but it doens't work. How can I keep the order that I pick one by one in Django admin's ManyToManyField? index.html {% for store in article.similarstores.all %} {{ store.businessName }} {% endfor %} models.py class Store(models.Model): class Meta: ordering = ['-created_by'] businessName = CharField(unique=True, max_length=40) ... def __str__(self): return str(self.id) + ". " + self.businessName ... class Article(models.Model): ... similarstores = ManyToManyField(Store, blank=True) ... -
Modify value in data table UserProfile using function
I am trying to run .save() to change the value of a user model field. Here is my code: Views.py: def traffic_task(request): tasks_traffic = Task.objects.filter(category="traffic") random_task = random.choice(tasks_traffic) task_id = random_task.pk user = request.user user.userprofile.daily_task = task_id user.save() return task_detail(request=request, pk=task_id) Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) daily_task = models.IntegerField(default=0) daily_task_done = models.BooleanField(default=False) daily_task_done_time = models.DateTimeField(default=datetime.now() - timedelta(days=2)) They are in two different apps so maybe it's an import missing? -
Ajax request in a Django blog - Guidance needed on frameworks
I'm looking for guidance on what framework to use for ajax requests. Context I'm building a blogging app with Django and learning JS. The aim is to have a list of blog posts and when the user clicks to open the post it opens in the same page. Then the user can click to see the list of blog posts again which closes the blog post and allows them to open a different post. I think this requires AJAX but I don't know what framework or library will be best to learn for this application, Angular, Node, VUE or React. Basic HTML Layout <div class = "blog-container"> <div class = "blog-list"> {% for post in index %} <div class="blog-post"> <h2> {{ post.post_title }} </h2> </div> {% empty %} <p>No blog posts</p> {% endfor %} </div> <div class = "blog-post-full"> <p>FULL BLOG POST</p> </div> </div> My main concern I'm leaning towards either React or Angular but that is mainly due to articles like this, this or videos like this and that I have seen them mentioned in job descriptions as a desirable skill. Thanks in advance for any advice, I really appreciate everyone's help! -
MultipleChoiceField not being submitted with form
I've been trying to create a custom admin interface using Django and Python as a learning experience, so I do not want to use any 3rd party apps or anything like that. The problem arises when I (as a superuser) try and add a user. I am unable to set the user's permissions. Currently I am using a MultipleChoiceField to allow the adding of permissions to the new user, but the problem is that whenever I try to add the new user, I get the error message Enter a list of values, even though I have selected permissions. And this is also a problem when I leave the select field blank when I don't want the user to have any permissions. I've tried creating a custom MultipleChoiceField, which is a subclass of the MultipleChoiceField, and then overriding the to_python() and validate() methods. I also tried accessing the data in the clean() method, but since the form field failed validation, it does not exist within the cleaned_data dictionary. I also tried to override clean_permissions method, but that did not work either. And in the to_python() method, I only seem to be receiving the last item in the select field. Below is … -
Django ImageField is empty
I am trying to create a form that uses ajax to create a new user. All the other fields work, besides the ImageField. I don't get a error when submitting, but the image will still not save. Github Repo: https://github.com/VijaySGill/matching-app urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('matchingapp/', include('matchingapp.urls')), path('admin/', admin.site.urls), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=6, blank=False) dateOfBirth = models.DateField(null=True, blank=False) bio = models.TextField(max_length=500, blank=True) profileImage = models.ImageField(upload_to="profileimage", blank=True, null=True) hobby = models.ManyToManyField(Hobby, blank=False) views.py @csrf_exempt def registerUser(request): ... image = ImageUploadForm(request.POST, request.FILES, instance=newUser) if image.is_valid(): userprofile = image.save(commit=False) userprofile.user = request.user userprofile.save() ... return JsonResponse(data, safe=False) register.html $('form').on('submit',function(e){ e.preventDefault(); ... var fd = new FormData($("#profileImage").get(0)); fd.append("username", $("#username").val()); fd.append("email", $("#email").val()); fd.append("password", $("#password").val()); fd.append("firstName", $("#firstName").val()); fd.append("lastName", $("#lastName").val()); fd.append("gender", gender); fd.append("dateOfBirth", dob); fd.append("hobbies", JSON.stringify(selectedHobbies)); if($("#password").val() == $("#confirmPassword").val()){ $.ajax({ type:'POST', url: '/matchingapp/registerUser/', processData: false, contentType: false, data: fd, ... }); forms.py class ImageUploadForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profileImage',) -
How to collect form data from django and pass it to xgboost model for prediction
I have a model that I want to use for predictions which I have loaded using pickle and I have a form created in using django. But when a user submits the form I want it to be in store it in a csv format in a variable so I can perform Xgboost prediction on every form the user fills and after it outputs the prediction. COuld it be its not getting any input. New to this from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name views.py from django.shortcuts import render from .models import Applicant from .forms import Applicant_form from django.views.generic import ListView, CreateView, UpdateView from django.core.cache import cache import xgboost as xgb import pickle from sklearn.preprocessing import LabelEncoder class CreateMyModelView(CreateView): model = Applicant form_class = Applicant_form template_name = 'loan/index.html' success_url = '/loan/results' context_object_name = 'name' class … -
Django-rest-framework and django-rest-framework-jwt APIViews and validation Authorization headers
I'm using DRF and DRF-jwt to secure my APIs. Currently I have some CBV written like this class Organization(APIView): permission_classes = (IsAuthenticated,) @method_decorator(csrf_exempt, name='dispatch') class OfficeVisitsOverview(APIView): def post(self, request, *args, **kwargs): cursor = connection.cursor() (before, today) = getDateRange() cursor.execute("SELECT format(COUNT(*), 'N0') \ FROM Medi_OfficeVisit \ WHERE ( cast(VisitDate as date) BETWEEN '{0}' AND '{1}' ) \ ".format(before, today)) data = dictfetchall(cursor) connection.close() return JsonResponse({"numberOfOVs": data[0][""]}) From my understanding the APIView and the permission class IsAuthenticated makes sure that theres an Authorization token being sent with the request header. How can you be sure that no one has modified the JWT? How do i know that the Secret_Token in my Django app is being used every time to decode/encode/verify/validate the JWT that is being received/sent with every request? Is this enough security for my APIs to be opened to the public? -
Template rest one day from the date
In my view.py I obtain a date from my MSSQL database in this format 2018-12-06 00:00:00.000 so I pass that value as context like datedb and in my html page I render it like this {{datedb|date:"c"}} but it shows the date with one day less like this: 2018-12-05T18:00:00-06:00 Is the 06 not the 05 day. why is this happening? how can I show the right date?