Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
function gives wrong total of a week day between a date range in django
I have been looking at this function for hours and I can't seem to figure out why it is not giving me the result I am expecting. I have a test that generates a datetime start and datetime end. I want to calculate how many 'mondays' or any given day occur between that time range. def day_count(week_day, start, end): if week_day == 1: day = 6 else: day = week_day - 2 num_weekdays, remainder = divmod((end - start).days, 7) if (day - start.weekday()) % 7 <= remainder: return num_weekdays + 1 else: return num_weekdays to replicate, this is the data that I give it: end: 2020-08-22 00:00:00+02:00 start: 2020-08-20 22:15:55.371646+00:00 weekday: 6 I expect to give back num_weekdays = 1 but I get num_weekdays = 0 I have no clue how I can possibly fix this, num_weekdays and remainder are 0 when I debug as well. This is how i am calling the function: total_day_count = day_count(params['dt_start__week_day'], params['dt_start__gte'], params['dt_end__lte']) and this is how i get the params: params = {} if self.request.GET.get('day') == 'Today': params['dt_start__week_day'] = (timezone.now().weekday() + 1) % 7 + 1 elif is_valid_queryparam(self.request.GET.get('day')): day_of_the_week = self.request.GET.get('day') params['dt_start__week_day'] = (int(day_of_the_week) + 1) % 7 + 1 else: params['dt_start__week_day'] = … -
can't show the button inside the tooltip in bootstrap 4
As i am adding the button inside the bootstrap 4 tooltip but the data is showing in the frontend but i can't see the button inside it. everything seems to be alright but it's not showing the button https://github.com/bestcsp/problem/issues function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + "<h5> Cart for your items in my shopping cart </h5><div class='mx-2 my-2'>"; var i = 1; for (var item in cart) { popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + cart[item] + '<br>'; i = i + 1; } popStr = popStr + "</div> <a href='/market/checkout'><button class='btn btn-primary' id ='checkout'>Checkout</button></a> <button class='btn btn-primary' onclick='clearCart()' id ='clearCart'>Clear Cart</button> " console.log(popStr); // document.getElementById('popcart').innerHTML=popStr; document.getElementById('popcart').setAttribute('data-content', popStr); $('#popcart').popover('show'); } $('#popcart').popover(); updatePopover(cart); function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + " Cart for your items in my shopping cart "; var i = 1; for (var item in cart) { popStr = popStr + "" + i + ". "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + cart[item] + ' '; i = … -
Do I need to use the DRF if I want to handle Token Authentication?
currently I plan on using AWS Cognito to handle my authentication for users. I want to do a simple registration and login. So far, I have created a function which calls cognito's initiate_auth method. Currently my flow works like this: User goes to /signup After filling the form, I create a new user in the cognito backend and send them a verification mail User is redirected to the /login page The login function in the backend calls initiate_auth with the username and password, and retrieves some token information like this {'AccessToken': '***', 'ExpiresIn': 3600, 'TokenType': 'Bearer', 'RefreshToken': '***', 'IdToken': '***'} I believe these tokens are in the JWT format. My question now is, what exactly do I do with this? I know that I need to store this data, securely, somewhere, but I'm not sure what the best practice is. I've heard that these tokens/data need to be saved in cookies in order to access them properly, but I also heard that there are some encryption problems, which is why I was looking for a library which handles this for me. I've come across this library: https://github.com/SimpleJWT/django-rest-framework-simplejwt However, it seems like in order to use this library, I need to … -
setting up server for django project with celery, tensorflow
I am working on a django project where when an image(design pattern) is uploaded, it does below: extract dominant colors and save it for later filtering put the uplaoded image on blender 3d model and render&save it as product image tensorflow extracting features from the image and save it as npy for later similar image search I set up celery to do above tasks and everything worked fine till I set up taks #3(tensorflow). After having task #3 I'm getting caution about memory allocation from tensorflow when starting up celery. So I'm guessing django and celery both runs tensorflow which I think it's waste of memory. I started thinking seperating them for django(A server) and for blender&tensorflow(B Server). My thoughts are: A & B server both have django running and shares the same database. A handles the main website and B handles image processing tasks including blender & tensorflow. when an image is uploaded -> A post to B -> B does work and save the result to shared database. I'm new to setting up this kind of structure and looking for advices. Thanks very much for reading and help.. -
Django view returns None during Ajax request
I have a Django web application and I'm trying to make an ajax call for uploading a large image. If I can upload the image I am trying to upload, I'll read the image with the pythonocc library and return the volume information. Since this process takes a long time, I am trying to do it using the django-background-tasks library. According to what I'm talking about, the ajax request that I am trying to take the image and send it to the view is as follows. var data = new FormData(); var img = $('#id_Volume')[0].files[0]; data.append('img', img); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ method: 'POST', url: '{% url 'data:upload' %}', cache: false, processData: false, contentType: false, type: 'POST', data: data, }).done(function(data) { }); my view that will work after Ajax request; def uploadFile(request): if request.method == 'POST': file = request.FILES.get('img') filename = file.name key = 'media/' + filename s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('bucket') bucket.put_object(Key=key, Body=file) new_data = Data(author=request.user) new_data.save() data_id = new_data.id initial = CompletedTask.objects.filter(verbose_name=verbose) request.session['u_initial'] = len(initial) verbose = str(request.user) + '_3D' read_3D(data_id, key, filename, verbose_name = verbose) ###background-task function is called return redirect('data:uploadStatus') The view that calls this background task function should also redirect the view, which will … -
How can I access nested JSON object in Django Template properly?
I'm trying to access some info with dot notation but I'm getting a weird error. I'll try to explain as well as I can with my code. My relevant code from views.py file: def index(request): // removed "x" assignment as it is long an irrelevant month = (datetime.datetime.now()).strftime("%B") year = str(datetime.datetime.now().year) customers = table(x, month, year) return render(request, 'index.html', {'customers': customers, "month" : month, "year": year}) Here, I call my tablequery file with table function to return a JSON object of files I have from MONGODB(I am not using MONGODB as the default DB so I do it manually). My table function is as follows: def table(user, month, year): ///// Code to access DB removed curs = col.find() list_curs = list(curs) liststring = json.dumps(list_curs) liststring = re.sub("_", "", liststring) // have to remove _ from "_id" because template doesnt allow "_id" type of variable to be used with dot notation jt = json.loads(liststring) return jt Type of "jt" appears to be "list" in python when I print it. My relevant html code: <tbody> {% for customer in customers %} <tr class="gradeX"> <td>{{ customer.id }}</td> <td>{{ customer.isim }}</td> <td> {% for ekran in customer.ekranlar %} <li> {{ ekran }} DENEME {{ … -
Fixing Django admin Dashboard
Hi i was working on my Django admin interface and whenever i am clicking on any module on left rail it doesn't gets highlighted. Please let me know how i can high lite any module i.e dashboard,project, Duplicate Test case on left side after clicking it.enter image description here my dashboard I have clicked on any module say project, dashboard it gets opened up but the same module on left doesn't gets highlighted. -
Django Internal Server Error for only some pages
I'm working on a rock, paper, scissors game. I wanted to use a base.html page and extend it with the body of the other pages. It is working for 2 Pages but not for the other two. I can't find out why i get an Internal Server Error, why my CSS File is not loading. Has anyone seen or experienced this before?? [21/Aug/2020 09:36:49] "GET /yilmaz/game_view/ii/IQ HTTP/1.1" 200 1474 Internal Server Error: /yilmaz/static/yilmaz/base.css Traceback (most recent call last): File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\views\static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\utils\_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "c:\users\güney\appdata\local\programs\python\python38-32\lib\ntpath.py", line 78, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType [21/Aug/2020 09:36:49] "GET /yilmaz/static/yilmaz/base.css HTTP/1.1" 500 72104 The HTML of the page looks like this {% extends 'yilmaz/base.html' %} {% load static %} {% block content %} <h1>Schere, Stein, Papier</h1></br> <form method="POST"> <p>{{player_name}}Spiele gegen den Computer</p> {% csrf_token %} {% for key, value in context.items %} <p>{{key}}: {{value}}</p> {% endfor %} <label> <input type="radio" class="nes-radio" name="answer" checked value="0"/> <span>Schere</span> </label <br> <label> <input type="radio" … -
django.db.utils.operationalerror:2002 through host -cloudcluster
Tried connecting my django application to my server its giving error- Exception has occoured: OperationalError (2002,"can't connect to MYSQL Server on'mysql-1111-0.cloudclusters.net'(10060)") my database in settings.py is import django.contrib.gis.db.backends.mysql import django.db.backends.mysql import django.db.backends.mysql.client DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'database1', 'USER':'user', 'PASSWORD':'******', 'HOST':'mysql-11111-0.cloudclusters.net', 'Port':'11111', } } on migrating getting the above Error.Kindly help. -
Allow partial update in serializer_class in Django REST
I am trying to partially update my ProfileSerializer when i am making PATCH request. However i am not able to make it beacuse by default Serializer doesn't allow partial changes to be made. I am using Django Rest Framwork UpdateModelMixin to handle my patch request. Where can i set partial=True in my case? View: class ProfileViewPartialUpdate(GenericAPIView, UpdateModelMixin): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'bio', 'name', 'email', 'sport', 'location', 'image') -
Which Framework is best to learn for future...ASP.NET core(C#) or Django (python) [closed]
i am new to development i want to pursue my career in this field...which framework is best to learn for future ASP.NET (c#) or Django (python) . NEED experts advice to this.. thanks -
The annotate with Sum seems doesn't work Django
There's a db (mysql) table like below: class AccountsInsightsHourly(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) date = models.IntegerField(blank=True, null=True) hour = models.IntegerField(blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'accounts_insights_hourly' unique_together = (('account_id', 'date', 'hour'),) ordering = ["account_id", "hour"] Some datas saved in db are like : id account_id spend date hour created_time 1 1222 200 20200820 12 .... 1 1222 300 20200820 14 .... And I tried with to get the max spend for each account at the specified date. base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday). \ annotate(yesterday_spend=Max("spend", output_field=FloatField())). \ values("account_id", "yesterday_spend") # I got results like below <QuerySet [{'account_id': '1222', 'yesterday_spend': 200}, {'account_id': '1222', 'yesterday_s pend': 300}]> # expected result is <QuerySet [{'account_id': '1222', 'yesterday_spend': 300}> How can I make annotate work as expected? -
Django Model Form not displaying information stored in session
My views.py file class multi_form(View): model=Customer template_name='index.html' def get(self, request): form=RegForm() if request.session.has_key('pan_card_number'): first_name=request.session['first_name'] last_name=request.session['last_name'] personal_email=request.session['personal_email'] official_email=request.session['official_email'] permanent_address=request.session['current_address'] current_address=request.session['permanent_address'] pan_card_number=request.session['pan_card_number'] aadhar_card_number=request.session['aadhar_card_number'] loan_amount=request.session['loan_amount'] context = {'form': form} return render(request, 'customer/index.html', context) def post(self, request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): request.session['first_name']=form.cleaned_data['first_name'] request.session['last_name']=form.cleaned_data['last_name'] request.session['personal_email']=form.cleaned_data['personal_email'] request.session['official_email']=form.cleaned_data['official_email'] request.session['current_address']=form.cleaned_data['current_address'] request.session['permanent_address']=form.cleaned_data['permanent_address'] request.session['pan_card_number']=form.cleaned_data['pan_card_number'] request.session['aadhar_card_number']=form.cleaned_data['aadhar_card_number'] request.session['loan_amount']=form.cleaned_data['loan_amount'] form.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') context = {'form': form} return render(request, 'customer/index.html', context) What I want is the form to auto populate the fields filled earlier with those I have saved in django session variables. So, when the user has a GET request on visiting the page again he is shown the data he filled out earlier. How will I implement this thing? My template file <fieldset> <h2 class="fs-title">Registeration Form</h2> <h3 class="fs-subtitle">Please fill the details below</h3> {{form.first_name}} {{form.last_name}} {{form.personal_email}} {{form.official_email}} {{form.permanent_address}} {{form.current_address}} {{form.pan_card_number}} {{form.aadhar_card_number}} {{form.loan_amount}} <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> Will my template file remain the same or do I need to change it as well? -
Problems installing django channels and twisted on windows 10 with python 3.8
I am trying to install django channels on windows 10, I have python 3.8.3 and django 3.0.5 already installed. When I enter the command, pip install channels in the cmd of the virtual environment of my project, I run into a huge error when my system attempts 'Building wheel for twisted (setup.py)', and upon failing to build this, another giant error occurs when 'Running setup.py install for twisted'. I have tried downloading the appropriate version of twisted from https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted, however when I then open the file using a code editor and try to run it I receive this message: WARNING: Requirement 'Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl' looks like a filename, but the file does not exist ERROR: Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl is not a valid wheel filename. This issue has been plaguing me for days now and I cannot find the solution anywhere online. Please can someone help me to understand how to resolve this? -
is there anyway to set horizon session timeout more than 3600 seconds
i can't make horizon session age longer than one hour, i had setted SESSION_TIMEOUT to 7200 in settings.py,but it was not worked, session age is still one hour, if i set SESSION_TIMEOUT to a value less than 3600 , it will work. please help me,thank you very much. -
Unable to redirect on other other page giving MultiValueDictKeyError Django
I am working on one simple student management system in which i am providing different options like add student, display student, display all students etc. so first i tired to render all those functions with simple text html it works perfectly. views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'csvcrud/home.html') def add(request): return render(request, 'csvcrud/add.html') def display(request): return render(request, 'csvcrud/display.html') def displayall(request): return render(request, 'csvcrud/displayall.html') base.html <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap 4 Website Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </head> <body> <div class="container" style="margin-top:30px"> <div class="row"> <div class="col-sm-4"> <h2 class="text-center">Options</h2> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-add' %}">Add Student</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-display' %}">Display Student</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-displayall' %}">Display All</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-add' %}">Download CSV</a> </div> <div class="col-sm-8 border border-secondary rounded"> {% block content %}{% endblock %} </div> </div> </div> <br> <div class="jumbotron text-center" style="margin-bottom:0"> <p>Footer</p> </div> </body> </html> add.html {% extends "csvcrud/base.html" %} {% block content %} <h2 class="text-center">Add Students</h2> <form action="/add" method="get" name="myForm" enctype="multipart/form-data"> <div class="form-group"> <label for="sid">Student ID</label> <input type="text" class="form-control" id="sid" placeholder="Enter Student ID" name="sid"> … -
Django update an object using models.Field object
I have dozens of fields in a Django model. class Question(models.Model): op1 = models.CharField(verbose_name="Option 1",max_length=500,null=True,blank=True) op2 = models.CharField(verbose_name="Option 2",max_length=500,null=True,blank=True) op3 = models.CharField(verbose_name="Option 3",max_length=500,null=True,blank=True) .... I want to write a function def update_ith_option_of_question( q, i, val): op = d._meta.get_field('op'+str(i)) # I want to save val in field op of object q How do I write the above function? -
template cant recognize url name django
I have a search field in my website header, and it doesnt reconize the url search_result html file: <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> urls.py: path('search/', SearchResultsView.as_view(), name='search_results'), views.py: class SearchResultsView(ListView): model = post template_name = 'main/search_results.html' def get_queryset(self): # new return post.objects.filter( Q(title__icontains=q) | Q(writer__icontains=q) ) I get the error: Reverse for 'search_results' not found. 'search_results' is not a valid view function or pattern name. -
Why should put django project outside /root/
When I read document of django, I see this: [![Screenshots of document][1]][1] p [1]: https://i.stack.imgur.com/WmiNd.png And I want to know why should put django outside of /root/ In fact, i have done it(forgive me), and i want to figure out why I shouldn't did it. -
django filter get filter field value inside the view
I have my filter like this class SummaryFilter(django_filters.FilterSet): start = django_filters.DateFilter( field_name="date_modified", lookup_expr="gte", ) end = django_filters.DateFilter( field_name="date_modified", lookup_expr="lte", ) and in my view i am doing like this class GetRiskyUsersSummary(generics.ListAPIView): model = Summary queryset = Summary.objects.all() serializer_class = serializers.ModelSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = SummaryFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) response = {} ********doing some stuff here and return in response******* **** for doing these i need the cleaned start and end date as date objects like below but couldnt figure out the option for this in the library**** self.filter.cleaned_data.get('start') self.filter.cleaned_data.get('end') return Response({"response": response}) How can I get this data in the view ? -
How to connect another object (or user) to Django views (add_to_cart)
I am trying to develop an e-comm site. Where parents buy stuff for kids. Parent add children to his/her profile: class Kid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) slug = slug = models.SlugField(unique=True) last_name = models.CharField(max_length=120) province = models.CharField(choices=PROVINCE_CHOICES, max_length=2, default='AB') city = models.CharField(max_length=120) school = models.CharField(max_length=120) grade = models.CharField(max_length=120) teacher = models.CharField(max_length=120) Also, I have OrderItem and Order classes, taken from a tutorial and it works. I have added kid object to OrderItem, maybe I need to add it to Order too. class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) kid = models.ForeignKey(Kid, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f'{self.quantity} of {self.item.title}' class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) order_date = models.DateTimeField(auto_now_add=True) event_date = models.DateTimeField() ordered = models.BooleanField(default=False) In views, I have a define add_to_cart: def add_to_cart(request, slug): item = get_object_or_404(MenuItem, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter( user=request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity +=1 order_item.save() messages.info(request, "Quantity of " + item.title + " was updated.") return redirect('/menu/') else: order.items.add(order_item) messages.info(request, item.title +" was added to your cart.") return redirect('/menu/') else: event_date = timezone.now() order = Order.objects.create( user=request.user, event_date=event_date ) … -
How to fix an error on django admin interface
Hi i am using Django admin to work on some task. i have created a model and added project name. so whenever i am creating a project say 'project5' and adding details and if again i am creating another project with same name and same details it is being created. What i want is i do not want the project name created to be with same details. it should give error. Please let me know how to fix this. Here below i have created a model with a class name and some fields. -
Django FilterSet Using multiple Models
I am having some trouble on applying a filter to a table in django, when I apply the filter (i.e. click on "Search") nothing happens. No error. No crash. Nada. The table stays the same as if nothing had happened eventhough the url does change adding the search fields that I applied. I'll rename the original names of variables, models and everything in general for sake of simplicity. models.py from other_app.models import CustomUser from another_app.models import OtherModel class SomeThings(models.Model): # default User was replaced with an AbstractUser model user = models.OneToOneField(CustomUser, on_delete=models.PROTECT) id = models.CharField(max_length=10,primary_key=True) thing_1= models.PositiveIntegerField(blank=False) thing_2= models.PositiveIntegerField(blank=False) image= models.ImageField(null=True, blank=True) class SomeStuff(models.Model): id = models.OneToOneField(SomeThings, on_delete=models.PROTECT) stuff_1 = models.CharField(max_length=255, blank=False) stuff_2 = models.CharField(max_length=255, blank=False) stuff_3 = models.ForeignKey(OtherModel, on_delete=models.PROTECT, null=True) class OtherInfo(models.Model): id = models.OneToOneField(SomeThings, on_delete=models.PROTECT) character_1 = models.CharField(max_length=255, blank=False) character_2 = models.CharField(max_length=255, blank=False) filters.py import django_filters from .models import * class myFilter(django_filters.FilterSet): class Meta: model = SomeStuff fields = '__all__' exclude = ['stuff_2','stuff_3'] views.py from .filters import myFilter def search(request): products = SomeStuff.objects.all() filter= myFilter(request.GET,queryset=products) product= filter.qs context = {'products':products,'filter':filter,} return render(request, 'search.html', context) search.html {% load static %} ... some html stuff ... <form method="get"> {{ filter.form }} <button class="btn btn-primary" type="submit"> Search </button> </form> <table> <thead> … -
i'm just getting started with django and followed a tutorial. imitated every step but keep getting this error
t = ToDoList(name="tim") t.save() Traceback (most recent call last): File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main_todolist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 750, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 787, in save_base updated = self._save_table( File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 892, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 930, in _do_insert return manager._insert( File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1249, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1395, in execute_sql cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: main_todolist -
django.db.models ImageField save Image as Base64
I'm actually new to Django. Let's say I have this model as a class class UserAccount(AbstractBaseUser, PermissionsMixin): ... profile_photo = models.ImageField( upload_to='photos/profile-picture', blank=True) objects = UserAccountManager() def __str__(self): return self.email I want to save the profile_photo attribute as a base64 file (instead of file path). How do I do that? Context : In my client side (front-end), I can't render the image by getting its file path. So I want to save the image as base64 string in the DB instead of actual image path so that it will be easier to render in the front end