Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Windows Apache stopped working and doesn't start anymore - "httpd.exe -k start" doesn't give errors
I have been hosting my Django REST project on a Windows server using Apache such that it works from https. Today it stopped working and I've been trying to find out the issue but I can't seem to get any useful info out of Apache. If anyone knows how to properly debug the error, or recognizes the issue I would greatly appreciate any help! I start Apache using PS C:\Apache24> bin/httpd.exe -k start Powershell doesn't say anything after this. But when I attempt to stop Apache it says it was never started! Again with no reason. PS C:\Apache24> bin/httpd.exe -k stop The 'Apache2.4' service is not started. I also checked the error.log, which again simply mentions that it failed to start. AH00378: Failed to start the 'Apache2.4' service This is my httpd.conf (I removed a lot of comments and boilerplate code). Note that it has worked before, I didn't change a thing. Define SRVROOT "c:/Apache24" ServerRoot "${SRVROOT}" Listen 8000 User daemon Group daemon ServerName 85.999.999.85:8000 # Django Project LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIScriptAlias / "c:/users/administrator/Desktop/django1/project/wsgi.py" WSGIPythonPath "c:/users/administrator/Desktop/django1/" <Directory "c:/users/administrator/Desktop/django1/project/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/users/administrator/Desktop/django1/static/" <Directory "c:/users/administrator/Desktop/django1/static/"> Require all granted </Directory> WSGIPassAuthorization on … -
Django DRF - How to interact with a POST endpoint using CURL?
I'm new to Django DRF or API development in general, please be patient with me ;) Beside some pure get API views I now wanted to setup my very first endpoint where I can send data to, so I decided to go with a user password change. Here is what I did so far: views.py @api_view(['GET', 'POST']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def update_user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = UserSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('id', 'user', 'password', 'pin', 'avatar') read_only_fields = ('id', 'user') def update(self, instance, validated_data): password = validated_data.pop('password', None) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance Now the question is how can I update the referenced fields like "pin" or especially "password" using curl. The first thing I always do is to get myself a new token like this: curl -X POST -d "user=admin&password=admin" http://localhost/api/v1/token/obtain {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWYzN2RiODUtYjU5Yy00YjRmLWFhNjYtMDExNGFmYWQ4ZDdiIiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTYzNDE3Mjg3MiwidXNlciI6ImFkbWluIiwib3JpZ19pYXQiOjE2MzQxMjk2NzJ9.zz9Zyai3Y7MhR_chGkzA6jXY_BdjN5Eu2muRvyWIppw"} With this token in place I can now reach the update_user endpoint but I don't understand how to interact with it … -
Type Error: Init Requires 1 Positional Argument Yet 2 Are Given
Hey so I'm getting this error when I'm trying to make a text area on my site to update a user's 'about' information. It just handles the info of an existing user to update their 'about' field. Any more info needed just let me know and any insight/solutions would be appreciated, thanks in advance. class change_about(UpdateView): def get_object(self, queryset=None): return User.objects.get(user=self.request.user) def form_valid(self, form): instance = form.instance # This is the new object being saved instance.user = self.request.user instance.save() return super(change_about, self).form_valid(form) -
Django Multiple Queries
I'm using lots of queries to find the sum of fields [ft_day, ft_night] in multiple records for specified date intervals e.g. last 7 days, last 6 months etc. This is needed to display a summary of total times at the aforementioned date intervals in a template. ft_total is a property in Models Is there a more efficient way to do this? Not really sticking to DRY here. Thanks for your help. views.py get_context_data() ## shortened ## context['last_6_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 5)/12), (self.date_now.month - 6) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) context['last_12_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 12)/12), (self.date_now.month - 12) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) -
Frontend, I don't understand if querySelector has been found Frontend
I'm writing the front,ajax response js. The final code comes, which must be inserted on the page Like after const div = document.querySelector('.row_wow_fadeIn>#xxx1'); the code doesn't work. js function ajaxSend(url, params) { // Отправляем запрос fetch(`${url}?${params}`, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(response => response.json()) .then(json => render(json)) .catch(error => console.error(error)) } const forms = document.querySelector('form[name=filter]'); forms.addEventListener('submit', function (e) { // Получаем данные из формы e.preventDefault(); let url = this.action; let params = new URLSearchParams(new FormData(this)).toString(); ajaxSend(url, params); }); function render(data) { // Рендер шаблона let template = Hogan.compile(html); let output = template.render(data); const div = document.querySelector('.row_wow_fadeIn>#xxx1'); div.innerHTML = output; } let html = '\ {{#twister}}\ <div>\ <img class="X" src="{{ image }}" class="img-fluid">{{ title }}\ <p class="text-dark">{{ price }} ₽</p>\ </div>\ </div>\ {{/twister}}' Html: <!--Grid row--> <div class="row_wow_fadeIn row d-flex justify-content-center wow fadeIn col-md-12"> <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div> <div id="xxx1" class="XXX"> {% for twister in case_list %} <img class="X" src="{{ skin.image.url }}" class="img-fluid">{{ skin.title }} <p class="text-dark">{{ skin.price }} ₽</p> {% endfor %} </div><input type="button" onclick="LetsGo()" value="!!!Исчо!!!"> </div> </div> <!--Grid column--> </div> -
I need my Kivy App to send data to my Django Website
So I created a App with Kivy that creates a poll. I want to send this poll data (Name, Time) to my website made with django. Has anybody experiece with it or knows how I can do it? -
Images from database not displaying in Heroku Django after hosting
I have few images in my SQLite database which I will be changing from admin panel over a period of time. I have hosted the django app in heorku(free service). All the static images are displaying (The one's not in database), but the uploaded images are not displaying. I have uploaded the image before deploying. The description for each image is being displayed but the image is not. I am using whitenoise and have viewed multiple other answers and they have not worked settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' if os.getcwd() == '/app': DEBUG = False html template: <div class="container"> {% comment %} Row 1 {% endcomment %} <div class="row my-5"> {% for image in images %} <div class="col-sm col-md-4 col-lg-4 col-xl-4 my-3"> <div class="card" > <img loading='lazy' src="{{image.image.url}}" class="img card-img-top my-2" alt="{{image.title}}"> <div class="card-body"> <p class="card-text">{{image.title}} </p> </div> </div> </div> {% endfor %} </div> </div> models.py : class Gallery(models.Model): image = models.ImageField(upload_to … -
The view "..." didn't return an HttpResponse object. It returned None instead
I am currently getting a Value Error on my current application where the program is supposed to print a pdf file. The full error message states the following: ValueError at /accConnect/trialBalanceMonthly/8 The view main.views.trialBalanceMonthly didn't return an HttpResponse object. It returned None instead. I have tried to check if there was any module I am missing and checked to see if the bool value that printing this file depended on was True (it was )- So I can't seem to find what could be causing this problem. My current code is as follows: URL.py: path('accConnect/trialBalanceMonthly/<int:reports_pk>' , views.trialBalanceMonthly, name='trialBalanceMonthly'), path('accConnect' , views.reportsHome, name='reportsHome'), View.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def trialBalanceMonthly(self , reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex # CHECKING TRIAL BALANCE MONTHLY SETTINGS if pkForm.Trial_balance_Monthly == True: # SQL STATEMENT baseTRBMonth = 'SELECT Master_Sub_Account , cAccountTypeDescription ,Debit , Credit FROM PostGL AS genLedger ' \ 'Inner JOIN Accounts ' \ 'on Accounts.AccountLink = genLedger.AccountLink ' \ 'Inner JOIN _etblGLAccountTypes as AccountTypes ' \ 'on Accounts.iAccountType = AccountTypes.idGLAccountType ' \ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) ' \ 'AND genLedger.TxDate > ? ' xtrbMonth = … -
Create a django model for saving train and test data in database
I am trying to create a website by django which a user can upload a csv file. in server I want to save this csv file as train data for a machine learning model. and I can't make a Model by the csv file because I don't know the name of the fields. and these names can change in differant datas. for example for one data it may seem like this: class TrainData(models.Model): humidity = models.IntegerField(...) wind_speed = models.IntegerField(...) is_it_raining = BooleanField(..) and we want to run a machine learning algorithm on this model by fields. and another data will be like: class TrainData(models.Model): X1 = models.CharField(...) X2 = models.CharField(...) X3 = models.CharField(...) y = models.CharField(...) a bad approach is (I guess) to convert this csv file into a DataFrame and convert DataFrame into a Pickle file and save it in data base by a model like bellow: class TrainData(models.Model): data = PickledObjectField() is there a better way to create this model?? and is creating data to pickle a good practice? -
Python Django variables data duplication after page refresh
I am passing a string to template, and It works fine, but when I reload the page, that string is duplicated. The string is generated dynamically and contains html-table, I want to render a table from variable in my template Only server reset helps to see the actual table without duplicates Code from views.py: def test(request): headings = ('RED', 'GREEN', 'BLUE') tb = Table() tb.make_headings(headings) cell_1 = Cell('1') cell_2 = Cell('2') cell_3 = Cell('3') row_1 = Row() row_1.add_cell(cell_1) row_1.add_cell(cell_2) row_1.add_cell(cell_3) tb.add_row(row_1) html_table = tb.create_html_table() return render(request, 'test.html', context = { 'table' : html_table }) create_html_table() function: def create_html_table(self): html_table = '<table>' for row in self.raw_table: html_row = '<tr>' for cell in row.cells: html_cell = '<td>{}</td>'.format(cell.get_data()) html_row += html_cell html_row += '</tr>' html_table += html_row html_table += '</table>' return html_table Row code: from .cell import Cell class Row(): cells = [] def __init__(self): self.cells = [] def add_cell(self, cell: Cell): self.cells.append(cell) def get_cells(self): return self.cells Cell code: class Cell(): def __init__(self, data = []): self.data = data def get_data(self): return self.data -
Without AuthMiddlewareStack how can I get logged user in Django channels?
Without AuthMiddlewareStack how can I get logged, user? Because I am not used auth models that's why self.scope['user'] returning the 'Anonymous'. I tried to add this class AllowedHostsOriginValidator - doesn't work. I want a session user. please help me. routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from chat.consumers import ChatConsumer from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('ws/chat/pm-with/<str:username>/',ChatConsumer()), ]) ) ) }) consumers.py from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import user,Thread,Message from chat.views import ChatView from django.contrib.sessions.models import Session class ChatConsumer(SyncConsumer): def websocket_connect(self,event): me = self.scope['user'] other_user = self.scope['url_route']['kwargs']['username'] getOtheruser = user.objects.filter(username = other_user).first() self.send({ 'type': 'websocket.accept', }) def websocket_receive(self,event): print("new event is received") print(event) self.send({ 'type': 'websocket.send', 'text': event.get('text'), }) def websocket_disconnect(self,event): print("disconnect event is called") custom user models models.py class user(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50,default="", blank=True, null=True) last_name = models.CharField(max_length=50,default="", blank=True, null=True) username = models.CharField(max_length=50,default="", blank=True, null=True) password = models.CharField(max_length=100,default="", blank=True, null=True) image = models.ImageField(upload_to ='user_image',default="",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(default="",blank=True, null=True) is_deleted = models.BooleanField(default=False) I want login users from custom models, not auth user models. please help me for this -
How to delete old multiple images on edit
I have multiple images in my product model. I got parts from here: multiple images I want to change old images to new when I use change_view. Here's my model.py: class Product(models.Model): title = models.CharField(max_length = 45) description = models.TextField(null = True) image = models.ImageField(upload_to = 'store/full/', null = True, blank = True) def __str__(self): return self.title class Meta: ordering = ['title'] verbose_name = "Product" verbose_name_plural = "Products" def get_image_filename(instance, filename): title = instance.product.title idd = instance.product.id slug = slugify(title) return "store/additional//%s-%s-%s" % (idd, slug, filename) class ProductImage(models.Model): product = models.ForeignKey(Product, default = None, on_delete = models.CASCADE, related_name = 'image_set') image = models.ImageField(upload_to = get_image_filename, verbose_name = 'Image') Here's my views.py: def create_view(request): ImageFormSet = modelformset_factory(ProductImage, form = ProductImageForm, extra = 4) form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, files = request.FILES) formset = ImageFormSet(request.POST, files = request.FILES, queryset = ProductImage.objects.none()) if form.is_valid() and formset.is_valid(): obj = form.save(commit = False) obj.save() for form in formset.cleaned_data: if form: image = form['image'] photo = ProductImage(product = obj, image = image) photo.save() messages.success(request, "Created!") return redirect('shop.all') else: print(form.errors, formset.errors) else: formset = ImageFormSet(queryset = ProductImage.objects.none()) context = { 'form': form, 'formset': formset } return render(request, 'shop/products/create.html', context) def change_view(request, id): … -
Reload django template into ajax response
is it possible to reload a Django template after an ajax call? This is my code. script.js $('.test').click(function(){ var platform = $('#testModal').attr('test-attr'); $.ajax( { type:"POST", url:"test", headers: { 'X-CSRFToken': TOKEN }, dataType: "json", cache : false, processData : false, contentType : false, data: string, success: function(data) { location.reload(); } }); }); view.py return render(request, "user_interface/index.html", {'my_var': 'abc', 'my_var_2': 'cde'}) I tried to use return HttpResponse(json.dump({'res': 'Ok', 'err': None}), content_type = "application/json") but when i reload the page it fails. -
how to resolve getattr() error in django?
I am doing a project in Django, and I think i have made changes in some models, then after i am getting these errors, (env) PS C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters\AMCH_recruiter\models.py", line 6, in <module> class Candidate(models.Model): File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\fields\__init__.py", line … -
Automatic connect gitlab pipline with azure web services
I have my webapp code on GitLab. I want to deploy it using Azure web services. But I want it in such a way that, when I push the code to branch it will first be pushed in GitLab then automatically on azure web services.. Is there any way to do this? I searched for a solution on the internet but not found the latest one. -
Django: Render list of model objects and post back the same list without changing item type in the list
On the first page, the user will click the upload button and several "model objects" will be stored into a list and render to one HTML component on the second page. Then if the user clicks the "save" button on the second page, the value in that input component will be posted back to the backend and further process will be done. view.py: def manual_upload_file(request): upload_objs = [TModel1.objects.get(m_id=1), TModel1.objects.get(m_id=2), TModel1.objects.get(m_id=3)] if "persist_data" in request.POST: objs_to_be_processed = request.POST["persist_data"] .... return render(request, 'components/page2.html', {'upload_objs':upload_objs }) page2.html: <form action="{% url 'page2' %}" method="post"> {% csrf_token %} <button class="btn btn-primary" name="persist_data" type="submit" value="{{upload_objs}}"> Save </button> </form> The problem here is that {{upload_objs}} in button value of page2.html will become pure string. And therefore all the model objects inside the list lose its property and all become part of string , i.e. when it post back, the request.POST["persist_save"] received in view,py is: "[<TModel1: TModel1 object (1)>, <TModel1: TModel1 object (2)>, <TModel1: TModel1 object (3)>]" Is there any template tag I can keep all objects as model object after render it to html page. For example, something like: value="{{upload_objs|list}}" Or is there any solution? Thank you -
Node.js and Django sharing a Postgresql database
I've built an application in Node.js and it's using a postgresql database. It's a mobile application for Android, which allows users to upload an image to the application using their mobile phone. We have another application that uses Django, and a model in python that uses OCR to extract text from images, and stores them in a table. I want to use the python code to run on the images that have been uploaded by the user using the mobile app, and process the image text and store it against the user record in the database. My problem is that the Node.js database doesn't use auth_user as the main table for users and I am unable to connect django to the existing postgresql db, because the tables are not standard django models. Any advice? The mobile app is how we collect images and pdfs, but python is the code that uses OCR and an ML library to process this - and we want to display them back to the user through the mobile app. Thanks p.s.: The database is hosted on Google Cloud, where all the images are stored too. -
TemplateDoesNotExist at / but filesystem loader says it does | happening in an extends tag
I am using Django 1.5.1 with Python 2.6.6. The error that I am getting is TemplateDoesNotExist at / when using the template extends {% extends "t_base_menu.html" %} The template that holds the extends is in the project/home/templates/home/index.html. The loader setting are (SITE_ROOT is correct): TEMPLATE_DIRS = ( join(SITE_ROOT, 'templates'), ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) In the error page the Template-loader postmortem says it exists, using django.template.loaders.filesystem.Loader: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /project/templates/t_base_menu.html (File exists) I have noticed that it is working if I move the t_base_menu.html to the project/home/templates folder. What am I missing? -
Form object not iterable in Django
I want to assign the input of a form to a function in my view but I keep getting this error. Please help do I fix it. Error receiver = list(ToolsForm.declared_fields['receiver_mail']) TypeError: 'CharField' object is not iterable -
Django returns image data as None
My utils.py: import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): f , str_image = data.split(';base64,') print(f) print(str_image) decoded_img = base64.b64decode(str_image) img_name = str(uuid.uuid4())[:10] + '.png' data = ContentFile(decoded_img, name=img_name) return data When I try to get a report, I get the 500 server error: Internal Server Error: /reports/save/ Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, * File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 13, in create_report_view img = get_report_image(image) File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 5, in get_report_image f , str_image = img.split(';base64,') AttributeError: 'NoneType' object has no attribute 'split' Although, in the browser console I can find 23 kbs of the data that goes as data:image/png;base64, and a bunch of characters. I'm trying to get the latter. Why does it not see the data? I have views.py as this: from django.shortcuts import render from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report def create_report_view(request): if request.is_ajax(): name = request.POST.get('name') remarks = request.POST.get('remarks') image = request.POST.get('image') img = get_report_image(image) Report.object.create(name=name, remarks=remarks, image=img, author=author) author = Profile.objects.get(user=request.user) return JsonResponse({'msg': 'send'}) return JsonResponse({}) -
How to run django orm query without using field name?
So i have one json data that contain field name of model as json key with value. i want to run orm query and define field name on run time. Ex: json_data = {"postgres_id":"10"} query = AcronymSecurityControlMaster.objects.get(postgres_id=10) json_data = {"age":"10"} query = AcronymSecurityControlMaster.objects.get(age=10) -
DRF is not re-evaluating queryset as expected gotcha
This is a question about whether DRF is working as it should or whether it could be improved to account for this use case. I have a simple API that returns a custom queryset like this: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.world_ranking() Where the custom queryset is: class RankingQuerySet(models.QuerySet): def world_rankings(self, rank_type="World"): # get most recent update update = RankingUpdate.objects.issued().filter(rank_type=rank_type, date__lte=TODAY).order_by("-asat", "-date").first() # if there is one, get all the player rankings for that update if update: return self.filter(update=update, player_id__gt=0, points__gt=0) else: return self.none() In the generics.py code of DRF, the get_queryset function has this code: def get_queryset(self): .... queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Given the comment "Ensure queryset is re-evaluated on each request" I was expecting it to do that. However, when I run my API test, the following sequence happens. Evaluation queryset Run setUpTestData() to populated data for test Make call to api without re-evaluating queryset Return no data If I put a custom get_queryset code into the api then it all works as I would expect and returns test data: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.none() def get_queryset(self): return Ranking.objects.world_rankings() Run setUpTestData() to populated data … -
django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor
I am trying to make a form using modelsform, it was working fine but, suddenly I don't know what suddenly happens and it started giving me this error django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor I have checked this error online and tried some solutions but nothing workout form me . here is forms.py file from django import forms from .models import Doctor class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','PhoneNumber','Email','City','Speciality','Image','KYCDocument') here is models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(max_length = 100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = 'blog_images', verbose_name = "Image") kycdocument = models.ImageField(upload_to = 'blog_images', verbose_name = "kycImage") -
create page like html with some header and footer
i want to create some html page with div shape like some ms word pages, with some header and footer for every pages, this is not that hard with some dive with fixed height and width but i want to use table on them as the tables grew and become bigger than page height another page with same footer and header created. i can use of server side languages with template like Django or javascripts is allowed too -
Django generate one-time password for admin site
So I want to generate a one-time password, "everytime" there a new login to admin site (let say I set timeout for 30 minutes or so), and send that password via email or else. Thankyou:)