Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is this view in django secure?
I am building a RESTAPI in Django using the following library called drf-firebase-token-auth. The client sends a get request with the token_id available in the Authorization header, and the library is expected to handle authentication in Firebase automatically. But the problem is if I do a simple get request without headers like curl <url+endpoint> the library doesn't verify if there's a an Authorization header and try to get a token for verification as if the request happens successfully as if drf-firebase-token-auth didn't raised it to be a problem. So I handled an exception whereas if the get request doesn't have an an authorization header, then raise an exception. But is it secure? from datetime import datetime from rest_framework import status from rest_framework.decorators import ( api_view, ) from rest_framework.response import Response # Create your views here. @api_view(["GET"]) def check_token(request): # if token is valid response with current server time try: if request.META["HTTP_AUTHORIZATION"]: date = datetime.now() return Response( data="Server time is: " + str(date), status=status.HTTP_200_OK ) except: return Response(data="Authorization header unavailable") -
DoesNotExist: Getting "Group matching query does not exist." error while saving a UserCreationForm of Django
I'm trying to save UserCreationForm of Django's built in auth application's form, using following in forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import * class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] My unauthenticated decorator is: def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func And views function looks like: @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form':form} return render(request, 'accounts/register.html', context) Complete Traceback is: Traceback (most recent call last): File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/decorators.py", line 9, in wrapper_func return view_func(request, *args, **kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/views.py", line 26, in registerPage user = form.save() File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/forms.py", line 138, in save user.save() File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 67, in save super().save(*args, **kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 801, in save_base post_save.send( File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in send return [ File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> … -
I'm having problem with accessing my django admin model
Error Showing: TypeError at /admin/store/order/23/change/ __str__ returned non-string (type NoneType) Request Method: GET Request URL: http://localhost:8000/admin/store/order/23/change/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: __str__ returned non-string (type NoneType) Exception Location: C:\Users\BHAVIN\Envs\test\lib\site-packages\django\forms\models.py in label_from_instance, line 1219 Python Executable: C:\Users\BHAVIN\Envs\test\Scripts\python.exe Python Version: 3.8.0 Code In my model.py: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) digital = models.BooleanField(default=False,null=True, blank=True) def __str__(self): return str(self.customer) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total -
About values('created_at__day') and values('created_at__week')
I wrote this code to sum up the daily and weekly counts with multiple data registered. What do the 2,3,18,22,27 in created_atday and 7,8,9,13 in created_atweek represent? Also, is there any way to make it easier to understand, such as 2021/3/5 for day and 2021/3/6- for week? I would appreciate it if you could tell me more about this. Data.objects.values('created_at__day').annotate(Sum('count')) Data.objects.values('created_at__week').annotate(Sum('count')) in the case of created_at__day "data": [ { "created_at__day": 2, "count__sum": 1004 }, { "created_at__day": 3, "count__sum": 491 }, { "created_at__day": 18, "count__sum": 1221 }, { "created_at__day": 22, "count__sum": 1201 }, { "created_at__day": 27, "count__sum": 999 } ], in the case of created_at__week "report": [ { "created_at__week": 7, "time__sum": 1221 }, { "created_at__week": 8, "time__sum": 1201 }, { "created_at__week": 9, "time__sum": 1663 }, { "created_at__week": 13, "time__sum": 999 } ], -
get all columns of 2 related models in django models
I am trying to get all the fields of Services and Suppliers as querySet in view class supplierMaster(models.Model): supplierId = models.AutoField(primary_key=True) supplierName = models.CharField(max_length=25) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.supplierName class servicesMaster(models.Model): serviceId = models.AutoField(primary_key=True) serviceName = models.CharField(max_length=50) supplierId = models.ForeignKey(supplierMaster, on_delete=models.CASCADE) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.serviceName -
Django automatically reload page files changes not working with django-livesync, how to solved the issue?
I have shown many posts in StackOverflow that those developer using "django-livesync" module to reload the pages and I tried same way but it's not reloading when I change any files. I followed, https://github.com/fabiogibson/django-livesync and How to automatically reload Django when files change? those techniques are failed that's why posting it again because I didn't see any solution anymore. I tried, 1st pip install django-livesync 2nd added "livesync" in INSTALLED_APPS before 'django.contrib.staticfiles' 3rd added middleware 'livesync.core.middleware.DjangoLiveSyncMiddleware', finally python manage.py runserver the server is running but reloading not working. Whenever I change any templates files, views, etc page not reloading automatically. below the project structure, and requirements.txt files for each version my goal is to reload the Django server http://127.0.0.1:8000/ automatically whenever I do python manage.py runserver. I will be very appreciated if get a good answer, Thanks. -
The right architecture to create a semi Jupiter notebook clone with Django and React
I am building a web app that lets a user upload a dataset and apply many data science procedures and tasks like EDA, data processing, visualization, and creating models. You can imagine it as a dashboard for repetitive data science tasks so it will be event-based like button clicks so on and not like Jupiter notebook way. So my question is, how to manage such a work flow? after a user uploads a document (dataset) many requests will take place to transform and apply a new action on the data, as the procedure might take a long time due to the long processing time, is there an efficient way/architecture to design such a system? and how to handle many operations on the same file without I/O errors? I have come across Django Channels and it seems to be a good solution since it provides async/sockets-based connections that will give enough time for each request and not be bounded by the http timeout. One workflow that is going to take place in the project is the following: - upload dataset - get all columns - get datatypes - get dataset description/info - modify datatypes - create new column set - agg … -
Directory structure for Django Python SQlite Project for Excel upload and Download
I am creating a project which uses Django Framework and SQLite for backend. I will be uploading and downloading excel documents. What should be the project directory structure. Kindly help -
How to create a form that update several objects?
I have several customers and users in my project. I can assign a customer to a user with a form. You can look to my question that I answered from here Now, I listed countries of the customers. I want to create a form that when a user click the button next to country and select the username it will assign to selected user. Assigned operation is actually update a customer's user field. How can I do that? views.py def country_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) countries = Customer.objects.values_list('country', flat=True).distinct() context = { 'customer_list': customer_list, 'countries': countries } return render(request, 'country_customer_list.html', context) country_customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Operations</th> </tr> </thead> <tbody> {% for country in countries %} <tr> <td>{{country}}</td> <td> <div class="row"> {% if customer.user == null %} {% else %} {% endif %} <div id="demo{{ forloop.counter }}" class="collapse"> {% if customer.user == null %} {% comment %}<form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-success ">Assign</button> </form>{% endcomment %} {% else %} {# Assigned to {{ customer.user.first_name }} {{ customer.user.last_name }}#} {% endif %} </div> </div> </td> </tr> {% … -
My Django Form Doesn't Add My Images To The Database
I Tried To Add An Image To My Database But I Can Only Insert It Manually In My Admin Panel It Doesn't Add It Automatically From My Form This Is My models.py option1photo = models.ImageField(null=True, blank=True) option2photo = models.ImageField(null=True,blank=True) option3photo = models.ImageField(null=True,blank=True) And My forms.py class AddpollForm(forms.ModelForm): class Meta: model = PollOptions fields = ['option1photo','option2photo','option3photo'] And My views.py polloptions_form = AddpollForm() if request.method == 'POST': polloptions_form = AddpollForm(request.POST) if polloptions_form.is_valid(): polloptions = polloptions_form.save(commit=True) return redirect('home') -
uWSGI resets worker on lifetime reached causes downtime
I configured my workers to have max-worker-lifetime=3600. It runs Django But What I see is that every 3600 seconds, both workers terminate together, and I have downtime of about 15 seconds and all requests fail with 502 from the remove server. These are the logs: Everything normal 00:00:00 worker 1 lifetime reached, it was running for 3601 second(s) 00:00:00 worker 2 lifetime reached, it was running for 3601 second(s) 00:00:01 HTTP 502 (on the remote server) 00:00:01 HTTP 502 (on the remote server) ... 00:00:01 HTTP 502 (on the remote server) 00:00:11 HTTP 502 (on the remote server) 00:00:11 Respawned uWSGI worker 1 (new pid: 66) 00:00:11 Respawned uWSGI worker 2 (new pid: 67) Everything goes back to normal I'm not sure why it has this behavior. This is the configuration used (only relevant parts): UWSGI_MASTER=true \ UWSGI_WORKERS=2 \ UWSGI_THREADS=8 \ UWSGI_LISTEN=250 \ UWSGI_LAZY_APPS=true \ UWSGI_WSGI_ENV_BEHAVIOR=holy \ UWSGI_MAX_WORKER_LIFETIME=3600 \ UWSGI_RELOAD_ON_RSS=1024 \ UWSGI_SINGLE_INTERPRETER=true \ UWSGI_VACUUM=true -
Django translate sentence with variable from .po files onto template
I want to translate a sentence that contains a variable by only changing the .html or the .po file. So the template looks something like this: <!-- Just for simplicity, I put price = 20.0 --> {% blocktrans with price=20.0 %} ${{ price }}/month {% endblocktrans %} and the .po file looks like this: msgid "$%(price)s/month" msgstr "每月 $%(price)s" Therefore, the output that I expect is '每月 $20.0', but the output that I got is '$20.0/month'. Is it because of syntax fault? I am using django 1.8.X (not really sure which) for extra info. I appreciate the help! -
python manage.py collectstatic not update files
I want to update my static file on AWS server and this is the setting which i have done on setting.py, my static folder is out of main app where is manage.py file File stu: manage.py db.sqlite3 main_app(folder) static(folder) AWS_ACCESS_KEY_ID = '---------------------' AWS_SECRET_ACCESS_KEY = '-----------------' AWS_STORAGE_BUCKET_NAME = 'agents-docs-django' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I have run this command python manage.py collectstatic but output this: 0 static files copied, 122 unmodified. I have made change in one file in static/js/File_name.js but that is not modified ! -
How to correctly provide a file path in JS xhttp.open()?
I'm trying to change data on a page, without the need to refresh. Using Python/Django/JS Following this: https://www.freecodecamp.org/news/ajax-tutorial/ I receive the following error when pressing the button to change the text on the page. : Not Found: /Budgeting/content.txt HTTP/1.1 404 In the above article it says: The file content.txt should be present in the root directory of the Web Application. I tried placing it inside of the root directly, but problem still persists and so I tried putting "content.txt" into every single directory of the Web Application. It still is unable to find the file. Directory structure with content.txt everywhere: hmtl file with JS: {% extends "base.html" %} {% block page_content %} {% load static %} <div id="foo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="changeContent()">Change Content</button> </div> <script> function changeContent() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("foo").innerHTML = this.responseText; } }; xhttp.open("GET", "static/content.txt", true); xhttp.send(); } </script> {% endblock page_content %} Also tried: {% extends "base.html" %} {% block page_content %} <div id="foo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="changeContent()">Change Content</button> </div> <script> function changeContent() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 … -
How to list countries of customers in Django?
I have several users and these users have several customers. Every customer has a country attribute. I want to listing customer's country in my project. I tried it with a for loop but when several customers have same countries it is listed same countries several times. I want to listed all countries just one time. How can I do that? Here are my codes views.py def country_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) context = { 'customer_list': customer_list, } return render(request, 'country_customer_list.html', context) models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.CharField(max_length=20) .. email = models.CharField(max_length=30) country_customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Operations</th> </tr> </thead> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.country}}</td> <td> ... </td> </tr> {% endfor %} </tbody> </table> -
django two filter with different key on merge with same key name
In django i have two query like : First = User.objects.filter(id=data.get('id')).values('first_id','first_name') Second = User.objects.filter(id=data.get('id')).values('second_id','second_name') combined_results = list(chain(competitorFirst, competitorSecond)) After this i am getting output like: {'first_id': '1', 'first_name': 'Hornets'} {'second_id': '2', 'second_name': 'corto'} what i actually want is like: {'id': '1', 'name': 'Hornets'} {'id': '2', 'name': 'corto'} can anyone please help how can i solve this . -
Django - permissions depends on subscription type
I make a project with subscription functionality. So users can choose from such subscriptions: Starter Premium Super etc. So when they use Payment Widget and server gets callback with successful status of payment I need to change "Role" or "Group" for this user in some "Permissions Model". So I consider it like a separate model with a user as a foreign key. So it looks like: User model: username password is_active Permissions model: username (Foreignkey to User model) some permission some another permission As example, every user can create an object of Apartment model. It looks like: Apartment model: full address short address So I want to limit users in creating this objects. E.g. user with "Starter" status can add only 2 apartments, "Premium" - 5 apartments and "Super" - 10 apartments objects. So that's very simple example of how permissions should work. How can I achieve such functionality? I know that Django has Roles and Groups, but is it appropriate for my goals? -
Django middleware is looped when using process_view
Django middleware is looped when using process_view I am trying to use the method to redirect a process during middleware. Middleware from django.urls import reverse from django.shortcuts import redirect, render class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): return redirect(reverse('check_license')) Urls path('check-license', views.check_license, name='check_license') View def check_license(): return render(request, 'check_license.html') -
Unable to install firebase-admin pip package for python django in Apple M1 chip
Unable to install firebase-admin in Apple M1 Chip System System Configuration System OS: macOS Bigsur(11.2.2) chip: Apple M1 python version: 3.9.2 Pip Version: 20.0.1 Djnago: 3.1.7 I create virtual env for my project using below steps install virtualenv using pip install virtualenv virtualenv venv -p python3.x (whichever you want) source /your_project/venv/bin/activate your venv will activate and then you can install requirements with the help of pip After this i try to install firebase-admin pip install firebase-admin and i get error like below File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/cffi/api.py", line 48, in init import _cffi_backend as backend ImportError: dlopen(/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so, 2): no suitable image found. Did find: /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/src/python/grpcio/_parallel_compile_patch.py", line 54, in _compile_single_file self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/src/python/grpcio/commands.py", line 250, in new_compile return old_compile(obj, src, ext, cc_args, extra_postargs, File "/opt/homebrew/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/unixccompiler.py", line 120, in _compile raise CompileError(msg) distutils.errors.CompileError: command '/usr/bin/clang' failed with exit code 1 ERROR: Failed building wheel for grpcio ERROR: Command errored out with exit status 1: /Volumes/DATA-D/user/Project/project_name/Api/fitquid/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/setup.py'"'"'; file='"'"'/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-record-jmxgwm9r/install-record.txt --single-version-externally-managed --compile --install-headers /Volumes/DATA-D/Drashti/Project/Fitquid/Api/webapis/fitquid/venv/include/site/python3.9/grpcio Check the logs for full command output. If try to insall pip … -
How to stop Django from hanging after page refresh using channels?
Using channels it connects properly when the page loads the first time but then hangs on refresh. Not sure why this is happening. I've placed the code below to see what might be happening? # index.html <script> let socket = new WebSocket('ws://127.0.0.1:8001/ws/'); socket.onmessage = () => { console.log("Connected"); }; socket.onclose = () => { console.log('Websocket closed'); } </script> # app/consumer.py from json import dumps from time import sleep from channels.generic.websocket import WebsocketConsumer class WSConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(dumps({'message': 'connected'})) for i in range(1000): self.send(dumps({'message': i})) sleep(2) #app/routing.py from django.urls import path from app.consumers import WSConsumer ws_urlpatterns = [ path('ws/', WSConsumer.as_asgi()) ] #core/asgi.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter from channels.routing import URLRouter from django.core.asgi import get_asgi_application from app.routing import ws_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(ws_urlpatterns)), }) # core/urls.py ... path('test/', views.IndexView.as_view()), ... In my settings I've added channels just below the .sites app but above everything else and I've added the ASGI_APPLICATION and running the application with python manage.py runserver 127.0.0.1:8001 -
Django multiple reshresh from view
I have some values in Django and I refresh them every 5 seconds on the page. I am using the ajax code below for this. But I have about 5 such values. I wonder what's the best way to do this? view: def ajax_system(request): system=get_system() return JsonResponse(system, safe=False) template: <script> $(document).ready( function() { setInterval(function(){ $('#ajaxsystem').load('/ajaxsystem'); }, 5000) }); </script> -
Django form not validating and saving into db
I'm not sure how to save the form into the database. I know the form is not valid because I tried do something else within that conditional. This is my models. I have the same thing for multiple values in models. from django.db import models class Initial(models.Model): happy = models.CharField( max_length = 2, ) ... interest = models.CharField( max_length = 2, ) This is my forms. Again, similar code for different parts of the form which I don't think is the problem. from django import forms from .models import Initial class initialForm(forms.ModelForm): happy = forms.MultipleChoiceField( required=True, label='You feel happy / content', widget=forms.RadioSelect, choices = emotion_choices, ) ... interest = forms.MultipleChoiceField( required=True, label='What creative outlet do you prefer?', choices=system_choices, ) def clean_init_form(self): new_init_form = Initial.objects.create( happyAns = self.cleaned_data['happy'], sadAns = self.cleaned_data['sad'], tiredAns = self.cleaned_data['tired'], jitAns = self.cleaned_data['jittery'], scaleAns = self.cleaned_data['scale'], interAns = self.cleaned_data['interest'], ) return new_init_form class Meta: model = Initial fields = "__all__" This is my views: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import initialForm from .models import Initial def submitForm(request): if request.method == 'POST': form = initialForm(request.POST) # create a form instance and populate it with data from the request: # check whether it's valid: … -
wagtail-modeltranslation Model already contain field
thank you for reading my post. actually my problem is that when migrating from: (wagtail==1.9.1 ; wagtail_modeltranslation==0.6.0rc2) to (wagtail==2.8 ; wagtail-modeltranslation==0.10.17) I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/wagtail_modeltranslation/apps.py", line 31, in ready handle_translation_registrations() File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/modeltranslation/models.py", line 75, in handle_translation_registrations autodiscover() File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/modeltranslation/models.py", line 26, in autodiscover import_module(module) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/taha/Desktop/myproject/myproject/home/translation.py", line 26, in <module> class HomePageTranslation(BaseTranslationOptions): File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/modeltranslation/decorators.py", line 23, in wrapper translator.register(model_or_iterable, opts_class, **options) File "/home/taha/Desktop/virtualenvs/venv/lib/python3.7/site-packages/modeltranslation/translator.py", … -
Add buttons in windows notification
I am creating 'talking reminder'. Currently its run in web browser. Now, I want to send notification with buttons when alarm ring. Hopefully, send notification work successfully using below code: notification.notify(title=msg, message=" ", timeout=10) But I am getting trouble to add button 'snooze' in this notification. I already tried win10toast but it given an error during download win10toast. Is there any solution for this? -
Can't find path todolist_app / index.html Hey, does anyone know ? #TemplateDoesNotExist
**TemplateDoesNotExist error on server. Django version 3.1 is installed and cannot find the path to index.html. I added the extension. INSTALLED_APPS = I have added an app. But I'm not sure about that; 'DIRS': [BASE_DIR / 'templates / todolist_app']** TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR /'templates/todolist_app'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]