Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Daphne not accepting websocket connections
I am trying to use daphne in django project to handle the websocket connections. I have installed daphne and it seems to be running. However, I am unable to send any websocket connection request. This is my daphne.service file: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django/AysleServer/src ExecStart=/home/django/AysleServer/MyEnv/bin/python /home/django/AysleServer/MyEnv/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk> Restart=on-failure [Install] WantedBy=multi-user.target On checking the logs of Daphne it shows this: Started WebSocket Daphne Service. Starting server at ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk...> HTTP/2 support not enabled (install the http2 and tls Twisted extras) Configuring endpoint ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/pri...> Listening on TCP address 0.0.0.0:8001 I thought that http2 and tls were causing the issue so tried to install them in my virtual environment using the command: pip install -U 'Twisted[tls,http2]' But they were already present as shown below: Requirement already satisfied: Twisted[http2,tls] in /usr/lib/python3/dist-packages (18.9.0) Requirement already satisfied: idna!=2.3,>=0.6 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (2.8) Requirement already satisfied: pyopenssl>=16.0.0 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (19.0.0) Requirement already satisfied: service_identity in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (18.1.0) Requirement already satisfied: h2<4.0,>=3.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (3.2.0) Requirement already satisfied: priority<2.0,>=1.1.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (1.3.0) Requirement already satisfied: hpack<4,>=3.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (3.0.0) Requirement already satisfied: hyperframe<6,>=5.2.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (5.2.0) I am using Gunicorn to … -
How to display a variable in Django forms?
I am trying to use the value of my database to display it in the form. So if a user already filled a value before, they will see it when they access again to the page. So there is my HTML file : <div class="form-group row"> <label class="col-4 mt-1 text-right">Modèle</label> <div class="col-4"> {{ form.model }} </div> </div> My views.py file : def get_car(request, identifiant): if request.method == "POST": form = CarForm(request.POST) if form.is_valid(): car_instance = Car( identifiant, form.cleaned_data["model"] ) car_instance.save() return HttpResponseRedirect("/forms/car/{}".format(identifiant)) else: form = CarForm() form.identifiant = identifiant return render(request, "forms/car.html", {"form": form}) My models.py file : class Car(models.Model): model = models.CharField(max_length=16) (primary key is automatically created) And my forms.py file : class CarForm(forms.Form): model = forms.CharField(label="Modèle", max_length=32, widget=forms.TextInput({ "value": Car.objects.get(pk=1).model})) We can see in the forms file that I gave a value to pk, so the code will search the value from the user whose pk = 1 in my database. My question is how to give the pk value from the active user ? -
Website's search function not working after a few hours (deployed using heroku)
I'm rather new at this so pardon me if I've used the wrong terminology. So the thing is that I've made a website that has Django-Machina (a forum app) integrated. Now, Django Machina comes with search functionality that uses django-haystack and whoosh. I've set up Machina according to the docs and it is working well right now. However, I realised that the search function of the Machina forum stops working after a few hours of not touching the site. To solve it, I have to run heroku run python manage.py update_index for the search to function properly again. I suspect it might have something to do with the fact that the filesystem on heroku being epipheral and each dynos boots with a clean copy of the filesystem from the most recent deploy. With that being said, how do i overcome this? I have explored the possibility of utilising cron jobs but I am honestly kinda lost. Is there any other ways around this? I would appreciate it if someone can guide me through, thank you very much!!! -
Django-filter BaseInFilter
I am currently trying to use BaseInFilter. Users can input the ids separated by commas like the one shown in the picture. I want to make a validator(or regulate user's input) so that the user can only input integers here. If the user enters characters, the Django backend will throw out this error. I have also tried this: class BaseIntegerFilter(filters.BaseInFilter, filters.NumberFilter): pass class HardwareFilter(filters.FilterSet): queryset = Hardware serializer_class = HardwareSerializer id = filters.BaseInFilter(field_name="id", label="Comma separated list of hardware IDs", help_text="Comma separated list of hardware IDs") But this solution doesn't allow me to input commas in the textbox anymore. Could anyone help? Any help will be really appreatiated! -
How to fix AttributeError: 'WhereNode' object has no attribute 'select_format', raised by Django annotate()?
There are many similar questions on SO, but this specific error message did not turn up in any of my searches: AttributeError: 'WhereNode' object has no attribute 'select_format' This was raised when trying to annotate() a Django queryset with the (boolean) result of a comparison, such as the gt lookup in the following simplified example: Score.objects.annotate(positive=Q(value__gt=0)) The model looks like this: class Score(models.Model): value = models.FloatField() ... How to fix this? -
Return UserData by taking access token input in Django Python
Code: class UserDetailsAPI(APIView): def post(self, request, *args, **kwargs): print(request.content_type) data=request.data user = data.object.get('user') or request.user token = data.object.get('access') response_data = { 'access': token, 'user': UserSer(user).data } response = Response(response_data, status=status.HTTP_200_OK) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, response.data['access'], expires=expiration, httponly=True) return response Error: AttributeError at /api/userdetails/ 'dict' object has no attribute 'object' Request Method: POST Request URL: http://127.0.0.1:8000/api/userdetails/ Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'object' Plss Help -
how to call back json data in django web framework
i'm trying to display some posts as a notification class Booking(models.Model): check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) and my views.py def alerts(request): if request.is_ajax(): isnot_checked = Q(check_out__isnull=True) is_checked = Q(check_out__gte=timezone.now()) current_booking = Booking.objects.filter(isnot_checked | is_checked).order_by('-pk') return JsonResponse({'items':list(current_booking)}) my urls.py app_name = 'booking' path('notifications',alerts , name='alerts'), my template $.ajax({ url:'{% url 'booking:alerts' %}', type:'json', method:'GET', success:function(data){ let content=''; for(i = 0;i < data.items.length; i++){ content+='<div class="p-2 mt-1 text-center bgpurple textpurple">' +'<p class="p-1 text-white border-2 bgpurple rounded-3xl">'+{{i.check_in}}+'-'+{{i.check_out}}+'</p>' +'</div>' $(".allnotifi").html(content); } }}); <div class="fixed z-50 w-1/5 h-screen overflow-y-scroll shadow-xl header" id="notification"> <button class="px-4 py-1 m-2 bg-opacity-75 rounded-lg bgorange focus:outline-none " onclick="showNotifcation()"><i class="far fa-window-close"></i></button> <div class="allnotifi"> </div> </div> <button class="relative px-6 py-1 rounded-full focus:outline-none textpurple" onclick="showNotifcation()" style="background-color: #ed9720;"> <i class="fas fa-bell "></i> </button> but it returns this into the console Uncaught SyntaxError: Invalid left-hand side expression in postfix operation python = 3.6 django =3.2 , jquery : https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js is not there a better way to display some posts as notification please ? -
APScheduler:Apps aren't loaded yet when I run the script in Heroku
I created automated email and run 7 days a week, but when I call the table from my app module I got an error in heroku logs "Apps aren't loaded yet." How to fixed this error? The error happened when I call the table from app module in python script. clock.py .......some import........ from apscheduler.schedulers.blocking import BlockingScheduler import django from myapp.models import Table1 <------ error occurred from myapp.models import Table2 <------ error occurred django.setup() sched = BlockingScheduler() sched = Scheduler() @sched.cron_schedule(day_of_week='mon-sun', hour=24) def email_job(): car_status = Table1.objects.filter(Deadline__date = datetime.datetime.today()) plate = "" .......automated email code here.... procfile.py web: gunicorn core.wsgi clock: python3 core/clock.py wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = get_wsgi_application() Im using APScheduler==3.7.0 -
CORS with Django older version
I know there are other threads which speaks about same topic but here I have different issue. I have legacy django webserver (running with older version 1.3.1), have enabled cors as suggested in https://www.geeksforgeeks.org/how-to-enable-cors-headers-in-your-django-project/ It was working well until we stopped allowing OPTIONS method in our Apache configuration due to fix some security gaps. Now I need to ask if do we have any other way to allow OPTIONS method in Django without touching Apache configuration. After blocking OPTIONS I get below error. cors error - Cross-Origin Respurce Sharing Error: PreflightMissingAllowOrginHeader 405 method not allowed. Thanks for helping me here. -
How to pull data from a related model in a many-to-many relationship?
So, I have two applications that I want to link together in a many-to-many relationship in my project. The first application is described by the following model. model.py: class ChannelCategory(models.Model): name = models.CharField(max_length=200, db_index=True') def __str__(self): return '%s' % self.name class Channel(models.Model): category = models.ForeignKey(ChannelCategory, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) class Meta: ordering = ['category'] def __str__(self): return '%s (%s)' % (self.category, self.name) The second application is described by the following model class Tariff(models.Model): channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False) def __str__(self): return '%s' % self.name def get_channels_categories(self): return ([str(p.category) for p in self.channels_list.all()]) def get_channels_objects(self): return ([str(p.name) for p in self.channels_list.all()]) Now what do I want to do? Suppose that the tariff object contains 4 channels, which have different categories, and we get approximately the following picture: tariff A has 4 channels from 2 different channel categories, for example, the "mega" tariff has ['ChannelCategory_1: Channel_1', 'ChannelCategory_1: Channel_3', 'ChannelCategory_2: Channel_2', 'ChannelCategory_2: Channel_4'] I do not understand how to display information on the interface correctly. I need to get this kind of information on my template: ['ChannelCategory_1: 'Channel_1', 'Channel_3''] ['ChannelCategory_2: 'Channel_2', 'Channel_4''] I will be glad for any help, thanks in advance! -
Django - how to set user create article is by user is logon
class Article(models.Model): slidenumber = models.AutoField(primary_key=True) title = models.CharField(max_length=255) category = models.CharField(default='', max_length=30) description = models.TextField(default="") timeupdate = models.DateTimeField('Date Published') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False, default=1) If I set author field has default=1, when I login django admin page to create a article it will alway get author is my superuser (has ID =1), so How I can set if I login admin django page to create article by other user(not my superuser), the author field will get user is logon current. -
Django-tables2 : usage of linkify to point to the record itself
I am converting a small application by replacing handcrafted html-tables by django-tables2. But I am unable to add 2 linkify links (detail & update) towards separate pages. Django 3.2.4 django-crispy-forms 1.12.0 django-filter 2.4.0 django-tables2 2.4.0 models.py class Environment(models.Model): name = models.CharField(max_length=10) description = models.TextField(max_length=100, help_text="Enter a brief description") envType = models.CharField( max_length = 32, choices = ENVIRONMENT_TYPES, default = "D" ) def get_absolute_url(self): return reverse('environment-detail', args=[str(self.id)]) urls.py urlpatterns = [ path('', views.index, name='index'), path('environments/', views.EnvironmentList.as_view(), name='environments'), path('environment/<int:pk>', views.EnvironmentDetailView.as_view(), name='environment-detail'), path('environment/create/', views.EnvironmentCreate.as_view(), name='environment-create'), path('environment/<int:pk>/update/', views.EnvironmentUpdate.as_view(), name='environment-update'), ] views.py class EnvironmentList(PagedFilteredTableView): # based on https://stackoverflow.com/questions/25256239/how-do-i-filter-tables-with-django-generic-views model = Environment table_class = EnvironmentTable filter_class = EnvironmentFilter formhelper_class = EnvironmentListFormHelper forms.py class EnvironmentListFormHelper(FormHelper): model = Environment form_tag = False # Adding a Filter Button layout = Layout('envType', ButtonHolder( Submit('submit', 'Filter', css_class='button white right') )) tables.py class EnvironmentTable(dt2.Table): # https://github.com/jieter/django-tables2/commit/204a7f23860d178afc8f3aef50512e6bf96f8f6b name =dt2.Column(linkify = True) edit = dt2.Column(default="edit",linkify=lambda record: record.get_update_url()) #edit = dt2.LinkColumn('environment-update', args=[A('pk')]) class Meta: model = Environment template_name = 'django_tables2/bootstrap-responsive.html' attrs = { 'class': 'table table-bordered table-striped table-hover', 'id': 'environmentTable' } fields = ("name", "description", "envType", "edit" ) per_page = 7 environment_list.html {% extends "base_generic.html" %} {% load render_table from django_tables2 %} {% load crispy_forms_tags %} {% block content %} <h1>Environment List</h1> <br> <a href="{% … -
how to login automatically after signup in django class base view
i want to login automatically user when successful signup. but my code return anonymous user now so, i use CreateView in django CBV views.py class SignUpView(CreateView): template_name = 'users/signup.html' success_url = reverse_lazy('users:email_confirm_notice') form_class = CustomUserCreationForm def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) and i try it def form_valid(self, form): form.save() new_user = authenticate(username=form.cleaned_data.get('username'), password.cleaned_data.get('password1') login(self.request, new_user) return super().form_valid(form) success_url is TemplateView that is just display templates and customusercreationform change error message. it is expected that there will be no changes from the first function. What's my problem? -
Is there any method to find (resume, job posts) documents score matching based on NLP with django and react
I have created an API for uploading resumes and job descriptions. Now I have to match both uploaded files for n number of resumes for the respective job profiles. Views.py - I have to get only one job id and matching all resumes and it has to give scores for all profiles this way I'm planning. class Score(APIView): queryset = Resume.objects.all() serializer_class = ResumeSerializer def get_object(self): id = self.request.id return JobDescription.objects.filter(id=id) def get_queryset(self, request): """ Return a list of all Resumes. """ data = [x for resumes in Resume.objects.all()] return Response(data) def get_score(resumes,job_description): x = calculate_scores(Resumes,Jobs) return Response(x) urls.py - looks like this way from django.urls import path,include from . views import ResumeViewSet,JobViewSet,Score from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'resume', ResumeViewSet) router.register(r'job', JobViewSet) router.register(r'score', Score) urlpatterns = [ path('', include(router.urls)), ] Calculate the score is a function of the NLP module to compare both documents. Is there any method or how I can solve this problem For more info about the NLP, model go through this link - https://github.com/srbhr/Naive-Resume-Matching -
Django restapi Axios fetch to vuex - than trying to read updated object in other vuex module
I am trying to find a way to communicate with my database so would be accesible for all of the Vuex instance. This is my code for fetching the data with axios: import { getAPI } from '../../../axios-api' const staticpages = { state: { pages: [] }, actions: { loadData({ commit }) { getAPI('/pages/').then((response) => { // console.log(response.data, this) commit('updatePages', response.data) commit('changeLoadingState', false) }) } }, mutations: { updatePages(state, pages) { state.pages = pages }, changeLoadingState(state, loading) { state.loading = loading } }, getters: { getAllStaticPages : (state) => state.pages } } export default staticpages; Than in my App.vue which is the first instance of vue to be initialized i have this code inside my created lifecycle hook to start fetching the data: created() { this.$store.dispatch("loadData"); }, Everything works fine and i see the updated state data in vue developer tools: enter image description here Then i try to access this data in other module of vuex and here is the problem. I import staticpages with import: import staticpages from "../front/frontstaticpages"; when i console log staticpages i see something like this console log of staticpages so even inside vuex module everything seems to be fine. Than i console log staticpages.state … -
Error occurs during migrating the models in django
I am trying to make migrations when saving the models.py. I came across this error and I am at a complete loss. I am creating a database that saves all the employees details in an excel sheet. For instance, when any employee submits a file upload, all of the files will be saved to excel automatically. This is the error I came across. PS python manage.py makemigrations No changes detected PS python manage.py migrate Operations to perform: Apply all migrations: EmpDBUpload, User, admin, auth, contenttypes, sessions Running migrations: Applying EmpDBUpload.0002_auto_20210715_1226...Traceback (most recent call last): File "C:\Users\18050478\Desktop\Workspace\PCUpdated\PCUpdated\manage.py", line 22, in <module> main() File "C:\Users\18050478\Desktop\Workspace\PCUpdated\PCUpdated\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) self.effective_default(create_field) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 310, in … -
Where to begin: transciption webapp/software
I have an idea for a transcription application that will help me with my job. I am a novice programmer and haven't done any programming application for a while now. Please be patient if this seems like a dumb question. I could do with some pointers as to how to approach this. I have experience using django python to build simple webapps in the past, so if I'd prefer to start this project using these tools if possible. I want to have a program or webapp where users can load a video with subtitles from their device. I want to be able to play the video for the duration of one subtitle line. (I use Aesisub at the moment which has a similar function.) My initial idea is to load this in a web browser. Users should be able to play one section of a video with subtitles, line by line, with the option to skip back and forth to the next lines of dialogue. The app will show the video and subtitles. Could anyone give any advice on the simplest way to build such an app? Should I be thinking about a chrome extension? Would it be difficult to … -
How to get the current and local date and time in Django?
I want to get the local time, so I tried the following codes in my Django shell. from django.utils import timezone now = timezone.localtime(timezone.now()) date = now.date() time = now.time() ## from datetime import datetime now = datetime.now() >>> print(now) datetime.datetime(2021, 7, 15, 4, 13, 49, 624395) In both cases, I got the wrong time, but if I use the same code in my terminal as python code, I get the current and local time. >>> datetime.now() datetime.datetime(2021, 7, 15, 8, 22, 50, 316528) >>> -
Django rest API. , I have a task for getting an internship in python/Django . Can you help me to solving this task?
Design a DB and an API server in Django that has the following functionality: -
Filtering MYSQL pull using datetimefield model django
I have been having a hard time finding a solution specific to filtering a model get from a mysql db. models file: class PreviousLossesMlbV5WithDateAgg(models.Model): game_points_with_formula_field = models.FloatField(db_column='GAME POINTS WITH FORMULA:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. date_field = models.DateTimeField(db_column='DATE:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. class Meta: managed = False db_table = 'previous_losses_mlb_v5_with_date_agg' views file def indexsss(request): PreviousLossesMlbV5WithDateAgg.objects.values_list('game_points_with_formula_field',flat=True).filter(date_field= '2021-07-05') monday_list = list(monday_new) return render(request, "show4.html", context={'test45': monday_list} ) The data does not populate and also shows this in the terminal DateTimeField PreviousLossesMlbV5WithDateAgg.date_field received a naive datetime (2021-07-05 00:00:00) while time zone support is active. -
How do I change the format of the permissions field in the outputted fixture for the dumpdata command?
When I create data fixtures for user groups using the dumpdata command: python manage.py dumpdata auth.Group --indent 4 > fixtures.json I get the ids of the permissions (23, 25, 26) in the following format: { "model": "auth.group", "pk": 7, "fields": { "name": "Subscribers", "permissions": [ 23, 25, 26 ] } } How do I get it to be in the format below for the permissions field? { "model": "auth.group", "pk": 7, "fields": { "name": "Subscribers", "permissions": [ ["add_location", "main", "location"], ["change_location", "main", "location"], ["delete_location", "main", "location"] ] } } I looked up the documentation but couldn't find anything on this. -
Difference between shortcut reverse and url reverse in Django
I am learning django. And recently I have came upon something that I don't understand. There are two different version of reverse module that can be imported. One is: from django.shortcuts import reverse Another is: from django.urls import reverse What are the actual difference between them? Can someone explain to me in an easy way? -
Django cannot find specified path for FilePathField
Trying to use FilePathField for my images, but my application returns the following error: FileNotFoundError at /api/projects/ | [WinError 3] The system cannot find the path specified: 'portfolio/img' settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') models.py class Tech(models.Model): name = models.CharField(max_length=100, null=False) icon = models.FilePathField(path="portfolio/img") class Project(models.Model): title = models.CharField(max_length=100, null=False) desc = models.TextField() image = models.FilePathField(path="portfolio/img") tech = models.ForeignKey(Tech, on_delete=models.CASCADE, null=False) And my current file hierarchy: back core portfolio static portfolio img manage.py -
VM101:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I am using Sandbox for payment testing. Everything works fine till payment and the console throws an error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 The error points to this line of code at the fetch. I am not sure what's wrong with the Django app. I even have initialized URL at the top: var url = "{% url 'payments' %}" onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(details); sendData(); function sendData(){ fetch(url, { method : "POST", headers: { "Content-type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ orderID: orderID, transID: details.id, payment_method: payment_method, status: details.status, }), }) .then((response) => response.json()) .then((data) => { window.location.href = redirect_url + '?order_number='+data.order_number+'&payment_id='+data.transID; }) } }); } -
Convert SQL string into Model datetime in django
I'm using Django rest framework to expose a database as API, The database was created manually before the Django implementation. By error, a charfield is storing a DateTime data as a string, My model is unmanaged so that the database structure is not changed, however, I need to use the DateTime field as DateTime, not as a string so that I'll be able to filter the records by date. Can anybody help me out to check how to cast the value as datetime? Thanks in advance.