Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get selected value from checkbox into views.py and convert into excel?
index.html <form method="GET"> <div class="form-row"> <div class="custom-control custom-checkbox mb-10 popup-sec-chk"> <input class="custom-control-input form-control inputfld" type="checkbox" id="date_inquiry" name="excelfields[]" value="dateofInquiry"> <label class="custom-control-label" for="date_inquiry">Date of Inquiry</label> </div> <div class="custom-control custom-checkbox mb-10 popup-sec-chk"> <input class="custom-control-input inputfld" type="checkbox" id="callers_name" name="excelfields[]" value="Callers name"> <label class="custom-control-label" for="callers_name">Caller's Info</label> </div> </div> <div class="modal-footer"> <a type="submit" href="{% url 'excelExport' %}" class="btn btn-primary" >Select</a> </div> </form> views.py def excelExport(request): try: if request.method == 'GET': checkedField = request.GET.getlist('excelfields[]') print("Checked list data ====== ", checkedField) return HttpResponseRedirect('home') except Exception as e: print("Exception =", e) return render(request, 'home.html') Print Output:- Checked list data ====== [] I'm working on a Django project where i want to do export in excel the selected data from checkbox. Right now I'm able to do export into excel but getting all the data, instead i want the selected data which i will select from the checkbox. -
How to change media url in django?
I have a website in production that serves media files properly. Media Setting in settings.py file : MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I have created a media folder inside my project where my all media are being stored. Due to the media URL it severs media files as https://domain_name/media/file_name. I want to serve my media files as https://domain_name/images/file_name. I try to change the MEDIA_URL setting in settings.py file, but it shows 404 error for the images. Updated settings.py file MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Django Templates avoid loop
I am working on a project and jhave a slight confusion. The Djago Template index.html has following code: <div class="carousel-item active"> {% for i in products|slice:"0:"%} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 17rem;"> <div class="card-body"> {% for img in i.images.all %} {% if forloop.counter == 1 %} <img src={{img.img_url}} class="card-img-top" alt="..."> {% endif %} {% endfor %} <h6 class="card-title">{{i}}</h6> {% for skus in i.skus.all %} {% if forloop.counter == 1 %} <h6 class="card-price">{{skus.price}} {{skus.currency}}</h6> {% endif %} {% endfor %} <a href="#" class="btn btn-primary">Add to Cart </a> </div> </div> </div> {% endfor %} </div> In this code , Is there a way to eliminate the {% for skus in i.skus.all %} The all tag is getting all objects but I am restricting the loop to run only one time through if condition so that I can only get the first item. Is there a way to eliminate the loops that have .all in them and restrict the statement to run only one time though any other way. -
Django not loading static files from React build folder
I am not able to load CSS and JS files in React frontend. Django setting file STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), **os.path.join(BASE_DIR, '../frontend/build/static')** ] After I run npm run build and check the django its not loading the static files. -
unable to set value using useState Hook in reactjs
function App() { const [LinkList, setLinkList] = useState([]); const [categories, setCategories] = useState({id:[], cat:[]}); var catArray = []; useEffect(() => { fetch("http://127.0.0.1:8000/api/service/category-list/") .then((response) => response.json()) .then((data) => { for (var i = 0; i < data.length; i++) { catArray.push({id:data[i].id, cat:data[i].category}); } setCategories(catArray); console.log(categories); //this line displays empty array console.log(catArray)//this line literally displays the date fetched. if( setCategories(catArray)){ console.log(true); //it rejects this line of code }else{ console.log("false");//this line is executed } }); }, []); I've put the issue in the comment of code -->{id: Array(0), cat: Array(0)} the above line is displayed when I try to log "categories" to the console please share me your Idea on this problem. code is literally correct, but it still throwing error to the console -
SMTPSenderRefused at /password-reset/ - Django
settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('USER_EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('USER_PASS') Error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 4.1.1 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\smtplib.py, line 887, in sendmail Raised during: django.contrib.auth.views.PasswordResetView Python Executable: D:\Django\Tutorial\env\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\\Django\\Tutorial\\django_project', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\Django\\Tutorial\\env', 'D:\\Django\\Tutorial\\env\\lib\\site-packages'] Server time: Fri, 16 Sep 2022 06:10:41 +0000 I am trying to set an email password reset in my django app but get this unexpected error. can you help me with this or provide me with some links so I can reach to the core of this error. -
I want to return the response without disturbing the data coming from subscription of node in django
async def get_event(self,address): infura_ws_url = 'wss://ropsten.infura.io/ws/v3/7c074579719748599c087f6090c413e2' address_checksumed = self.w3.toChecksumAddress(address) async with connect(infura_ws_url) as ws: await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}') # print("HERE") subscription_response = await ws.recv() print(subscription_response) while True: try: message = await asyncio.wait_for(ws.recv(), timeout=15) response = json.loads(message) txHash = response['params']['result'] tx =self.w3.eth.get_transaction(txHash) if tx.to == address_checksumed : print("Pending transaction fincoming:") print({ "hash": txHash, "from": tx["from"], "value": self.w3.fromWei(tx["value"], 'ether') }) transaction_receipt_json = { "transaction_hash": txHash, "from": tx["from"], "value": self.w3.fromWei(tx["value"], 'ether') } return transaction_receipt_json # return Response(transaction_receipt_json) pass except Exception as e: print("Exception") print(e.args) print(e.__str__) pass @action(detail=False, methods=['GET'], url_path='subscribe-deposit') def subscribe_deposit_address(self, request): address = self.request.query_params.get('address') # get_event.delay(address,) # return Response('Address subscribed') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) while True: resp = loop.run_until_complete(self.get_event(address)) return Response(resp) when I call this API from postman it subscribe the pending tx and returns when any transaction pending contains my address as destination but immediately after returning the response on postman my request ends and I don't want it that my request get end I want my request don't end and whenever any pending tx comes which contains my address as destination it returns the tx in response -
I created a view that add stops to route and they are not appearing by parameter order from models
I created view where i add stops to route, its working fine, but stops are not appearing in order when i add them, and i have no idea why. Please tell me where i'm making a mistake Here's my code: Models: class Port(models.Model): name = models.CharField(max_length=128) description = models.TextField(default='') lattitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) amenities = models.ManyToManyField(Amenity, blank=True) def __str__(self): return f'{self.name}' class Route(models.Model): name = models.CharField(max_length=128, default='') user = models.ForeignKey(User, on_delete=models.CASCADE) stop_list = models.ManyToManyField(Port, through='RoutePort') def __str__(self): return f'{self.name}' class RoutePort(models.Model): port = models.ForeignKey(Port, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ['order'] the order i intend them to appear is set by 'order' parameter from class routeport form: class AddRoutePort(forms.ModelForm): class Meta: model = RoutePort fields = ['port', 'order'] form is short and i dont know if i didnt forget something there View, get is working correctly, post works almost ok. New ports are correctly added to new route from list, but they appear in order of being added, not the one i wanted them to. class RouteCorrectView(View): def get(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort() return render(request, 'route_correct.html', {'route':route, 'form':form}) def post(self, request, pk): route = Route.objects.get(pk=pk) form … -
Why does Django Money show 3 decimals with decimal_places=2?
I'm very confused by this: >>> from djmoney.models.fields import Money >>> Money("0.129", "EUR", decimal_places=2) Money('0.129', 'EUR') I've expected to see Money('0.12', 'EUR') or Money('0.13', 'EUR'). I know I can use round(2) to get the expected result, but what influence does decimal_places have? If it stores the data anyway, why/when should I use the parameter? The docs are not helpful. -
Error loading MySQLdb Module in django project when mysql setup
I have a problem with my project, I installed the "pymysql", but i am trying to use the "pymysql", but i try to use and gives the following error: ModuleNotFoundError: No module named 'pymysql' pip install pymysql import pymysql ModuleNotFoundError: No module named 'pymysql' Collecting MySQL-python Using cached MySQL-python-1.2.5.zip (108 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [19 lines of output] Traceback (most recent call last): File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in main() File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 338, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 320, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 482, in run_setup super(_BuildMetaLegacyBackend, File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 335, in run_setup exec(code, locals()) File "", line 13, in File "/tmp/pip-install-atvcbcg9/mysql-python_60be5e09ce744d36b68b98258534b6a2/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for … -
MultiValueDictKeyError in crud
def editproduct(request,pk): #editproduct/4 pk=4 prod=Item.objects.get(id=pk) if request.method=='POST': if len(request.FILES)!=0: os.remove(prod.image.path) prod.image=request.FILES['image'] prod.name=request.POST.get('name') #iphone prod.description=request.POST.get('description') #offers prod.price=request.POST.get('price') #200000 prod.save() return redirect(index1) context={'prod':prod} return render(request,'edit_item.html',context) -
Celery crontab to schedule 1 of the month and quarterly in year
I have a celery task which executes quarterly on 1 of the month how can my month_of_year can be written { 'task': 'mytask', 'schedule': crontab(day_of_month='1', month_of_year='') }, -
VSCode unable to autoimport python functions
I am currently able to auto-import python functions from external typings such as from typing import List. However, I am unable to detect local functions for import. For example: If I have the data class SomethingData in dataclasses.py, and I reference it in a function in do_something.py, VSCode is unable to detect it and I have to manually type out the import path for the dataclass. I have the following extensions enabled: Python Pylance Intellicode My settings.json includes: { "python.envFile": "${workspaceFolder}/.env", "python.languageServer": "Pylance", "python.analysis.indexing": true, "python.formatting.provider": "black", "python.analysis.autoImportCompletions": true, "python.analysis.autoSearchPaths": true, "python.autoComplete.extraPaths": ["~/Development/<django repo name>/server"], "python.analysis.extraPaths": ["~/Development/<django repo name>/server"], "vsintellicode.features.python.deepLearning": "enabled", } I am using poetry for my virtual environment which is located at ~/Development/<django repo name>/.venv Is there something that I'm missing? -
Question regarding uploading files to the internal website
I am encountering a problem on my internal website. Everything was working fine until someone turned the server off, so I had to turn on the server via Docker. The site was up and running fine after that. However, my colleagues quickly realized that they could not add files to the website, i.e. you first upload files to the site, select save and then it will save the uploaded file. Upon further inspection, I found out that you could upload files from some pages only, i.e. both pages 1 and 2 allow you to upload documents, but only page 2 accepts the upload request and successfully uploads it to the site; page 1 will attempt to upload and return saved successfully, but the files will not have been uploaded. To provide some context to the situation, I inputted "sudo pkill -f uwsgi -9" before running the server again using Docker. More importantly, the internal website is vital for everyday operations and cannot be down under any circumstances, so I am a bit reluctant to mess with the server in fear of destroying whatever that can still be used. My colleagues are still getting by because they can upload from another … -
Cannot log in the django admin site with nginx
I have an issue with logging into django admin site which is almost the same question five years ago. Unfortunately, there is no specific answer until now. Here is the brief introduction for the question. My nginx serves the 80 port and it will proxy all the URL starts with prefix to 8000 port which Django is listening. location /prefix/ { proxy_pass http://0.0.0.0:8000/; } access /prefix/admin/, it gives me a 302 and redirect to /admin/login/?next=/admin/. However, if we access /prefix/admin/login, it works and we have the Django Administration login page as below. However, if we are trying to login(url is /admin/login/) with username and password, it gives me a 404. Let me make a summary, here we have two issues in total. prefix/admin not working, prefix/admin/login works. Logging into the admin site(admin/login) not working. The first issue has been solved by location /prefix/admin/ { proxy_pass http://0.0.0.0:8000/admin/login/; } The second issue, however, not working by the following. location = /admin/login { proxy_pass http://0.0.0.0:8000/admin/; } It told me that I have too many redirects. How can I fix this? Thanks in advance. -
django @swagger_auto_schema properties
my json data { "User": { "login_id": "admin", "password": "qwer1234" } } I want to put this response in swagger doc too! I use drf_yasg app in django. I've written this code: @swagger_auto_schema(method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'login_id': openapi.Schema(type=openapi.TYPE_STRING, description='ID'), 'password': openapi.Schema(type=openapi.TYPE_STRING, description='password'), } )) I don't know how to provide json data -
How to update/insert query database automatic in django
This is a digital library system. When borrow end_date has expired, borrow status will be updated automatically to 1 (End), table book column stock will be updated adding one stock, and automatically inserting new content value in table notification. class Borrow(models.Model): status = models.CharField(max_length=1, choices=[('0', 'Process'),('1', 'End')], default=0) book = models.ForeignKey('models.Book', on_delete=models.CASCADE, related_name='borrow_book') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) end_date = models.DateTimeField() class Book(models.Model): stock = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Notification(models.Model): content = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How to make an automatic update query in table borrow column status, table book column stock, and insert in table notification when end_date > DateTime.now() ? -
Django domain and webhosting
I have a django web application and my database is postgresql. I am thinking of buying the hosting and domain in godaddy. Is it recommended or cheaper? If godaddy which should I buy should I buy the shared hosting? Thanks -
Django Ignoring invalid foreign key with migrate?
When I do the migrate I get the below error. can I ignore it to continue the migration. django.db.utils.IntegrityError: The row in table 'pages_dataupload' with primary key '15734098' has an invalid foreign key: pages_dataupload.Customer_Address_id contains a value '' that doesn't have corresponding value in pages_bo -
Cannot assign "'Sample Category'": "Product.category" must be a "Category" instance
While creating new products I'm getting such kind of error. Can someone help me? class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name_geo = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name_geo class Category(models.Model): _id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @api_view(['POST']) def createProduct(request): user = request.user product = Product.objects.create( user=user, name_geo="Sample Name", category="Sample Category", price=0, brand='Sample Brand', countInStock=0, ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category -
How do I get an error message from an object
I'm trying to create an authentication in my project after signing in. I created my models and form. I want the user to get an error message if he doesn't get the correct pin in the models and successful if he puts in the right pin. I create the pin in my models already class Data(models.Model): name = models.CharField(max_length=100) body = models.CharField(max_length=1000000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) other_name = models.CharField(max_length=200) email = models.EmailField() profile_image = models.ImageField(blank=True) city = models.CharField(max_length= 100) title = models.TextField(null=True, blank=True) middlename = models.TextField(null=True, blank=True) adreess = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) state = models.TextField(blank=True, verbose_name="Biography (Age, Language, Location...)") pin = models.IntegerField() available = models.TextField(null=True, blank=True) checkings = models.TextField(null=True, blank=True) savings = models.TextField(null=True, blank=True) phone_number = models.TextField(null=True, blank=True) first_his = models.TextField(null=True, blank=True) second_history = models.TextField(null=True, blank=True) third_history = models.TextField(null=True, blank=True) last_history = models.TextField(null=True, blank=True) newstate = models.TextField(null=True, blank=True) def __str__(self): return self.first_name this is my HTML file <style> h5{ color: red; } </style> {% for message in messages %} <h5> {{message}}</h5> {% endfor %} <form action="portfolio" method="POST" class="row g-3"></form> {% csrf_token %} <div class="col-md-12"> <label for="validationDefault02" class="form-label"></label> <input type="text" name = 'pin' class="form-control" id="validationDefault02" value="" required> </div> <div class="col-12"> <button class="btn btn-primary" type="submit">Send</button> </div> </form> … -
Search template page not Found
I am trying to implement search in my project so that users can search for anything with ease but I keep getting Page not Found error.The errors seems like it's coming from my urls.py but I don't know where exactly. Below are my codes urls.py from .import views app_name = 'app' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_category'), path('search/', views.search_list, name='search_list'), path('<int:id>/<slug:slug>/', views.product_details, name='product_details'), ] views.py from .models import Category, Product from cart.forms import CartAddProductForm from django.db.models import Q # Create your views here. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products}) def product_details(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'products/detail.html', {'product': product, 'cart_product_form': cart_product_form}) def search_list(request): search_post = request.GET.get('q') search_query = Product.objects.filter(Q(name__icontains=search_post) | Q(category__name__icontains=search_post)) return render(request, 'products/search.html', {'search_post': search_post, 'search_query': search_query, 'category': category, 'categories': categories}) -
how to get variation in a product id
I'm not getting a return on the color and size, only the product name is coming. And yes my request.POST['color'] and request.POST['size'] are receiving the values, but in the form of names and not in id. def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) variation_list = [] if request.method == "POST": color = request.POST['color'] size = request.POST['size'] try: variation = Variation.objects.get(product=product, color__name__exact=color, size__name__exact=size) variation_list.append(variation) except: pass return HttpResponse(variation_list) HttpResponse -
DRF function based view HTTP 405 Method Not Allowed
I'm trying to use function based view to create a new object, but keeps shows this error: HTTP 405 Method Not Allowed Allow: GET, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "POST" not allowed." } I've read alot stackoverflow questions, but none of them worked for me, here is my code: @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def todo_create(request,format=None): if request.method == 'POST': serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.owner = request.user serializer.save() return Response(serializer.data) return Response(serializer.errors) urls urlpatterns = [ path('',todo_links,name='todo_links'), path('lists/',todo_lists,name='todo_lists'), path('create/',todo_create,name='todo_create'), path('lists/<int:pk>/',todo_detail,name='todo_detail'), path('lists/<int:pk>/update',todo_update,name='todo_update'), path('lists/<int:pk>/delete',todo_delete,name='todo_delete'), path('data',template,name='template'), ] main url from snippet.views import api_root urlpatterns = [ path('admin/', admin.site.urls), path('auth/',include('django.contrib.auth.urls')), path('posts/',include('post.urls')), path('api-auth/',include('rest_framework.urls')), path('',include('snippet.urls')), path('todo/',include('todos.urls'),name='todos-app'), ] my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE':1 } serializers.py class TodoSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.HyperlinkedIdentityField(view_name='user-detail',format='html') class Meta: model = Todo fields = ['id','owner','title','describe','complete'] my models.py class Todo(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name='todos') title = models.CharField(max_length=255) describe = models.TextField(null=True,blank=True) complete = models.BooleanField(default=False) def __str__(self): return self.title i know how to implement it with class based view, i'm not sure why it shows that error with function based view. thank you in advance -
how to fix raise ImproperlyConfigured("settings.DATABASES is improperly configured. in django
so i'm having issue deploying my django on railway but once the deployment is complete the app crash with this err raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. and below is my django settings and railway setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('PGHOST'), 'NAME': os.environ.get('PGDATABASE'), 'USERNAME': os.environ.get('PGUSER'), 'PASSWORD': os.environ.get('PGPASSWORD'), 'PORT':os.environ.get('PGPORT') } } can anyone help out pls