Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix this Exception and Type Error? (Django)
I was following this tutorial by Tech with Tim, but suddenly after adding a few lines of code I only gett type errors or exception errors when I try to see my webpage. My code: views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Item, ToDoList from .forms import CreateNewList # Create your views here. def index(response): return HttpResponse("<h1>Hello, world!</h1>") def item_by_id(item_id, id=None): item = Item.objects.get(pk=item_id) return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}") def home(response): return render(response, "myapp/home.html", {}) def base(response): return render(response, "myapp/base.html", {}) def itemlist(response, list_id): ls = ToDoList.objects.get(id=list_id) return render(response, "myapp/itemlist.html", {"ls": ls}) def create(response): if response.method == "POST": form = CreateNewList(response.POST) # Takes POST and uses data for form if form.is_valid(): # is_valid() checks class-fields for valid input n = form.cleaned_data["name"] # Clean and un-enc data, specify field "name" t = ToDoList(name=n) # Use data to create new ToDoList t.save() return HttpResponseRedirect("itemlist/%i" % t.id) # Redirect to page that shows the list else: form = CreateNewList() return render(response, "myapp/create.html", {"form": form}) models.py from django.db import models from django.forms import model_to_dict from django.utils.timezone import now class Item(models.Model): title = models.CharField(max_length=200) # Short description of the item datetime_found = models.DateTimeField(default=now, blank=True) # Date and time … -
Need help rendering a view
I am making a blog like app to help record what I did for a certain project for work. I am able to successfully make a list of the projects I am currently working on and I can successfully render the one I want to edit. However, once I open the project I want to edit it and I click the submit button, I am unable to redirect it back to the view for that one project. This is the project I want to edit. I try to update it like the following. When I click the update button it just refreshes the page and the update doesn't take effect. Any ideas as to why this is happening? Here is my code. views.py from django.shortcuts import render,redirect from .models import CR,GC from .forms import CrForm,GcForm # Create your views here. def Home(request): return render(request,'base.html') def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) def CreateCr(request): form = CrForm() if request.method == 'POST': form = CrForm(request.POST) if form.is_valid(): form.save() return redirect('crlist') context = {'form':form} return render(request,'cr_form.html',context) def UpdateCr(request,pk): cr = CR.objects.get(id=pk) form = CrForm(instance=cr) context = {'form':form,} if request.method == 'POST': form = CrForm(request.POST,instance=cr) if form.is_valid(): form.save() return redirect('crlist') return … -
No filter named 'linebreaks'
I am using Jinja2 and Django's template system. When I try to use linebreaks or linebreksbr template filter, I get an Exception: jinja2.exceptions.TemplateAssertionError: No filter named 'linebreaksbr'. Example: <div> {{ object_instance.text_content|linebreaksbr }} </div> Other default filters like capfirst are working as they should. -
Error "This field is required" when setting forms initial data to user data
I'm creating a signup feature for my website. When a person sign-up, a new user is created and then they are redirected to a view where a doctor is created (a user is a doctor in my case). The login works fine, but when I try submit the form to create the doctor using the users name and surname, I get an error saying the fields are required - but the form fields have been populated - and my cleaned_data dictionary is empty. Any idea as to what I am doing wrong? Here is my view.py: def createDoctor(request): # user = None # name = None # surname = None # if request.user.is_authenticated: # user = request.user # name = user.first_name # surname = user.last_name if request.method == 'POST': user = get_user(request) doctor_form = DoctorCreationForm(data=request.POST, prefix='docForm') if doctor_form.is_valid(): doctor_form.save() return redirect('medical:doctors-list') else: print(doctor_form.errors) else: user = get_user(request) doctor_form = DoctorCreationForm(initial={'doctor_name': request.user.first_name, 'doctor_surname': request.user.last_name}) context = {'doctor_form': doctor_form} return render(request, 'medical/create_doctor.html', context) -
Django: Socialapp matching query does not exists
É simple e facil de resolver este erro. caso vc não tenha um usuario no projeto, é necessario criar um com: python manage.py createsuperuser logo apos é necessario realizar o login na pagina administrativa do seu site. para isso primeiro inicie o servidor: python manage.py runserver e entre na url de admin, exemplo: localhost:8000/admin ou 127.0.0.1:8000/admin apos a autenticação no sistemas, você deve ir para sessao de aplicações socias, e cadastrar sua app, informando sua secret_key e id_client depois de realizar esses passos seu sistema deve funcionar -
Django showcasing videos being sent to users
I have a Django application where a user can submit a form and send an email to someone with a file attached to it (usually a video). My question is, is it possible to grab that attachment and showcase it somewhere on the dashboard I have set up? I'm trying to make it look like this: my send mail view looks like this: def send_mail_plain_with_file(request): if request.method == "POST": message = request.POST.get('message', '') subject = request.POST.get('subject', '') mail_id = request.POST.get('email', '') email = EmailMessage(subject, message, request.user.username, [mail_id]) email.content_subtype = 'html' file = request.FILES['file'] email.attach(file.name, file.read(), file.content_type) email.send() messages.success(request, "Your message has been sent.") return redirect('dashboard') return render(request, 'sendattachments.html') the HTML file that holds the form is in sendattachments.hmtl and looks like this: {% extends 'base_generic.html' %} {% load static %} {% block content %} <div class="container border py-4 my-4 w-75"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label">Send to Email:</label> <input type="text" name="email" class="form-control" id="title"> </div> <div class="mb-3"> <label class="form-label">Subject:</label> <input type="text" name="subject" class="form-control" id="title"> </div> <div class="mb-3"> <label for="desc" class="form-label">Message:</label> <textarea name="message" class="form-control" rows="5">Coming from: {{user.first_name}} {{user.last_name}}</textarea> </div> <div class="mb-3"> <label for="filename" class="form-label">Select File:</label> <input type="file" name="file" class="form-control"> </div> <button type="submit" class="btn btn-primary">Send Mail</button> </form> </div> {% … -
How to fix: TypeError: a bytes-like object is required, not 'str'
I have recently started programming. I am trying to simulate an ethereum transaction with the help of Ropsten. When I try to run the function (sendTransaction ("message")) with the Django's shell I get this error: TypeError: a bytes-like object is required, not 'str'. The full errors track is the following: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Francesco\bakeka\bloggo\utils.py", line 18, in sendTransaction tx = w3.eth.sendTransaction(signedTx.rawTransaction) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 577, in send_transaction return self._send_transaction(transaction) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\module.py", line 53, in caller (method_str, params), response_formatters = method.process_params(module, *args, **kwargs) # noqa: E501 File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 179, in process_params params = self.input_munger(module, args, kwargs) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 168, in input_munger root_munger(module, *args, **kwargs), File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 120, in send_transaction_munger if 'from' not in transaction and is_checksum_address(self.default_account): TypeError: a bytes-like object is required, not 'str' (Francesco is my username, bakeka is my project, globale is my venv) from web3 import Web3 def sendTransaction(message): w3 = Web3(Web3.HTTPProvider('My Ropsten Ip')) address = 'my addres' privateKey = 'my private key' nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gasPrice value = w3.toWei(0, 'ether') signedTx = w3.eth.account.signTransaction(dict( nonce = nonce, gasPrice = gasPrice, gas = 10000, to = '0x0000000000000000000000000000000000000000', value = value, data = message.encode('utf-8'), ), privateKey) … -
django get method with argument not working
I am trying to make a get request with an ID argument in django as the doc says in https://docs.djangoproject.com/en/3.2/topics/class-based-views/ but I can't seem to make it work. The request is arriving in the backend as expected. "GET /api/acordo-parcela/1/ HTTP/1.1" 200 348 where 1 is my ID. but even after creating a new urlpattern it does not reach the view class The urlpattern: path('/acordo-parcela/<int:clienteId>/', GetParcelas.as_view()), The GetParcelas class: class GetParcelas(APIView): print("test") def get(request, clienteId): print("inside") I have read the docs on https://docs.djangoproject.com/en/3.2/topics/http/urls/ and tried with views.AcordoParcelaViewSet (a viewset I created accordingly) but keep getting a 'has no attribute' error. What is the easyer way to make this get request with an argument? -
Django form data not saving to database
I have a views.py that combined three forms from different models into one form on the template. The code seems to be operational and the print statements in the views.py doc suggest that the form is valid and all the relevant data is available. However, only data from form1 and form2 get saved to the database. I've read (what feels like) dozens of threads on this website, but the print statements and purging the database were the last productive debug idea that I had and now I'm at a loss for how to debug this further. Pls come with the suggestions! views.py def consent(request): context = { 'title': 'Consent', } print(Author) try: UD = UserDetails.objects.get(user_id=request.user.id) consent = UD.participate_consent if consent == True: username = request.user.username messages.warning(request, f'Hej, {username}, you already did that.') return redirect('profile') except: context['form1'] = None context['form2'] = None context['form3'] = None if request.method == 'POST': form1 = UserDetailsForm(request.POST) form2 = GetUserFirstLast(request.POST, instance=User.objects.get(id=request.user.id)) form3 = GetAuthorInfo(request.POST, instance=User.objects.get(id=request.user.id)) context['form1'] = form1 context['form2'] = form2 context['form3'] = form3 if form1.is_valid() and form2.is_valid() and form3.is_valid(): print(form1.cleaned_data) print(form2.cleaned_data) print(form3.cleaned_data) form1.save() form2.save() form3.save() username = form1.cleaned_data.get('username') messages.success(request, f'Thanks for consenting, {username}! \nNow we can get started.') return redirect('profile') else: print("a form is not … -
How to identify and authenticate the right "user" when we use Django (Existing proj) for authentication and FastAPI (new feature) for API's?
Hello guys I have an existing Django project which has certain features and also has user data. For certain features, users use the API served through Django, but since there is a need for new feature which needs to be implemented through FastAPI, I need to have the same users authenticate or to be recognized by FastAPI (as this is the same user in Django) to save an action corresponding to user in the db. How to achieve that? How do I store the user data, like user_id and username for each user safely? How to properly design the database table? Please do let me know, how to start. Thank you. -
No module named 'ecommerce.store' in django
I run command python3 manage.py runserver It throws an error showing that no module named ecommerce.store but it is. This is my ecommerce.store.views file from ecommerce.store.models import Product from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) This is my ecommerce.store.admin file from django.contrib import admin from .models import * admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(OrderItem) admin.site.register(ShippingAddress) This is my ecommerce.store.models file from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import ForeignKey class Customer(models.Model) : user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self) : return self.name class Product(models.Model) : name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=True) def __str__(self) : return self.name class Order(models.Model) : customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self) : return str(self.id) class OrderItem(models.Model) : product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model) : customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, … -
Creating multiple test databases in Django TestCases
I wanted to create multiple test databases, so I could check if my synchronizing script is working properly. I have added them to Django settings like this: DATABASES = { "default": { "ENGINE": env.str("DB_ENGINE"), "NAME": env.str("name[1]"), "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": 'name[1]', } }, "name[2]": { "ENGINE": env.str("DB_ENGINE"), "NAME": "[name1]", "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": "name[2]", } }, "name[3]": { "ENGINE": env.str("DB_ENGINE"), "NAME": "name[3]", "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": "name[3]", } }, } This is how my test for sake of testing looks like: class SyncTestCase(TestCase): def setUp(self) -> None: self.client = Client() def test_func_tester_client(self): bitbucket_db_setup.main() response = self.client.get("/v1/devices/?name=a", SERVER_PORT=8000) print(response.content) self.assertEqual(200, 200) But when I run it, it only creates DB for 'default' alias: Creating test database for alias 'default'... *DB_SMTH are imported names from environment and name[x] are just names -
unable to use db.sqlite3 db when I am pushing it to Heroku server
what I am doing...! I have made a django project and I am trying to to host the website on heroku what is not a problem. the website is being deployed successfully when I push it to Heroku using heroku CLI . while I am trying to run the website on localhost it's working fine - I am able to upload data on sqlite3 db, I found that UI is appearing properly. my problem I am getting following error when I login as admin Environment: Request Method: POST Request URL: https://obscure-lake-92881.herokuapp.com/admin/login/?next=/admin/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['blogs.apps.BlogsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', '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') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 414, in login return LoginView.as_view(**defaults)(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view … -
How CSRF token works in Django and how to use it in Postman
I am a newbie in Django, I understand that Django has inbuild csrf middleware for protection. Could someone explain how including {% csrf_token %} in the template generates the csrf token behind scenes. I would also like to test my APIs from Postman, but I would need to pass the csrf token also in the request, any suggestions on how to generate the csrf token so that I can use in my API testing? Any help is much appreciated. -
how to assigned user preferred size with it item id in django
I want to fetch user selected size with the quantity and product but I don't understand how to do that any how idea to achieve that i try to look documentation but didn't find one any idea how to do that right now I am only able to fetch its item id and quantity any idea how to assign size with is id using dictionary to achieve that my views.py for add to cart class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code for that <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> any suggestion will … -
How to remove the name "Queryset" from queryset data that has been retrieved in Django Database?
we all know that if we need to retrieve data from the database the data will back as a queryset but the question is How can I retrieve the data from database which is the name of it is queryset but remove that name from it. maybe I can't be clarified enough in explanation so you can look at the next example to understand what I mean: AnyObjects.objects.all().values() this line will back the data like so: <QuerySet [{'key': 'value'}] now you can see the first name that is on the left side of retrieving data which is: "QuerySet" so, I need to remove that name to make the data as follows: [{'key': 'value'}] if you wonder about why so, the abbreviation of answer is I want to use Dataframe by pandas so, to put the data in Dataframe method I should use that layout. any help please!! -
applying filter to other pages
i've got sort on main page of shop, it works , but in other pages it doesn't works. How could i apply this sort to other pages? at the url address it updates but no result, it just shows items in default order.i tried to find any answer but couldn't view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() collections = Collection.objects.all() brands = Brand.objects.all() context['brands'] = brands context['categories'] = categories context['collections'] = collections return context def get_ordering(self): return self.request.GET.get('orderby', ) class ShopCategory(Shop, ListView): def get_queryset(self): return Item.objects.filter(category__slug=self.kwargs['slug']) def get_ordering(self): return self.request.GET.get('orderby', ) template <div class="product-sorting d-flex"> <p>Sort by:</p> <form name="selectForm" action="{{request.get_full_path}}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> </select> <input type="submit" class="d-none" value="submit"> </form> </div> urls urlpatterns = [ path('shop/', Shop.as_view(), name='shop'), path('shop/subcategory/<slug:slug>', ShopBySubCategory.as_view(), name='shop_subcategory'), path('shop/category/<slug:slug>/', ShopCategory.as_view(), name='shop_category'), path('shop/on-sale', ItemsOnSale.as_view(), name='on_sale'), path('shop/brand/<slug:slug>', ShopByBrand.as_view(), name='shop_brand'), path('shop/<slug:slug>/', ItemDetail.as_view(), name='single_product') ] -
Why can I access Django Development Server from localhost (vscode)?
Okay so I've just started to learn Django and I've been using vscode to SSH connect to my remote development machine and I save my changes on the remote machine. But when I run the development server, I access it on my localhost network, not from the remote IP. How is this possible given I ran the command manage.py runserver 9000 from the remote machine? Is this something to do with VSCode? Cheers -
Django charfield choices compatibility
I've a model which has field choices. In the saving case i wanna make sure that value is in that choices list. class Foo(models.Model): GENDER_CHOICES = ( ('M', 'Male'),('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) But when i try to save with value out of choices , it saves that value. foo = Foo(gender = "A") foo.save() Yes i can control it in code like if value in genderlist: but in my project that will take so time to add this control in every usage of choices saves. Is there any chance to control it in MODEL ( overriding save method or some option for field or etc ) ? -
Django how to test whether password validators are being used
My Django settings file contains the following password validators: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] I am using django allauth and django restauth to set up authentication endpoints. If I post to the registration endpoint with a password that is too short, too common, or only numeric, I receive and appropriate error message. Here's an example with all three: { "email": "toasterffs@gmail.com", "password1": "1223", "password2": "1223" } { "password1": [ "This password is too short. It must contain at least 8 characters.", "This password is too common.", "This password is entirely numeric." ], } When I post to the registration endpoint with a password that is the same as the email address, I receive no error. I need to debug this but where to even start? I there somewhere I can inspect which validators are actually called? Can I monkey patch the validator and put some logging in to see where things are going wrong? Is there a signal? some other hook? Thanks -
How to deploy django crm on cpanel (shared hosting fastcomet)
KINDLY REFER TO IMAGE AND LINKS.. I did once, basically application startup file would be manage.py and entrypoint would be entrypoint.sh right? log file error: App 660 output: /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 660 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno App 660 output: Traceback (most recent call last): App 660 output: File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in App 660 output: app_module = load_app() App 660 output: File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app App 660 output: return imp.load_source('passenger_wsgi', startup_file) App 660 output: File "/home/vendscon/virtualenv/crm.vendscon.com/3.7/lib64/python3.7/imp.py", line 171, in load_source App 660 output: module = _load(spec) App 660 output: File "", line 696, in _load App 660 output: File "", line 677, in _load_unlocked App 660 output: File "", line 728, in exec_module App 660 output: File "", line 219, in _call_with_frames_removed App 660 output: File "/home/vendscon/crm.vendscon.com/passenger_wsgi.py", line 8, in App 660 output: wsgi = imp.load_source('wsgi', 'manage.py') App 660 output: File "/home/vendscon/virtualenv/crm.vendscon.com/3.7/lib64/python3.7/imp.py", line 171, in load_source App 660 output: module = _load(spec) App 660 output: File "", line 696, in _load App 660 output: File "", line 677, in _load_unlocked App 660 … -
How and in which module do I reference a Django user uploaded file in python backend business logic?
The aim of this application it to receive a user uploaded file and do some transformations on it using python. It is very, very basic. After reading many similar questions, I still have not found the solution. The relevant modules are: models.py from django.db import models import pandas as pd import numpy as np # Create your models here. class M_input(models.Model): m_input_description = models.CharField(max_length=255, blank=True) m_input_file = models.FileField(upload_to='m_input') m_sold_to = models.CharField(max_length=20) m_ship_to = models.CharField(max_length=20) def delete(self, *args, **kwargs): self.m_input_file.delete() super().delete(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.views import generic from django.urls import reverse_lazy import pandas as pd import numpy as np import os from django.conf import settings # Create your views here. from .models import M_input def index(request): """View function for home page of site.""" context = { # 'file_path': Document.file_path, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class M_inputListView(generic.ListView): model = M_input class M_inputCreate(generic.CreateView): model = M_input fields = ('m_input_description', 'm_input_file', 'm_sold_to', 'm_ship_to') success_url = reverse_lazy('m-list-input') #f = M_input.objects.filter(id=1).first() f = M_input.objects.get(id=1) forecast_dict = pd.read_excel(f.m_input_file.name, sheet_name=['F'], skiprows=1) def delete_m_input(request, pk): if request.method == 'POST': m_input = M_input.objects.get(pk=pk) m_input.delete() return redirect ('m-list-input') urls.py from django.urls import path … -
How to read headers from request
I have an API, those who would access this API would have to pass an authorization token, so my question is how can I get that auth token from headers? class RealTimeAPI(APIView): def post(request): pass -
django-admin runserver error (DJANGO_SETTINGS_MODULE not set )
I'm getting the following error when trying to run django-admin runserver PS C:\Users\gasgu\PycharmProjects\djangodennisproj\devsearch> django-admin runserver Traceback (most recent call last): File "C:\Users\gasgu\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\gasgu\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\gasgu\PycharmProjects\djangodennisproj\venv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have done a clean installation with a virtualenv, then I didi pip install django, created the project and do the runserver. I'm running this from pycharm community and I read that I should also set an enviroment variable called DJANGO_SETTINGS_MODULE and I should put my project.settings as value. I did that and I still get the error. I've also tried the same process from outside … -
Poll's choices are not showing while accessing from view in template
I am building a Poll App and I am stuck on an Problem. What i am trying to do :- I am trying to access all three choices of poll from view in template BUT only one choices is showing. BUT when i access Poll object in view and access choice model from template then all three choices are successfully showing. models.py class Poll(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) title = models.TextField() def get_absolute_url(self): return reverse('detail_poll', kwargs={'pk': self.pk}) class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=30) forms.py class PollAddForm(forms.ModelForm): choice1 = forms.CharField(label='Choice 1',max_length=100,min_length=2) choice2 = forms.CharField(label='Choice 2',max_length=100,min_length=2) choice3 = forms.CharField(label='Choice 3',max_length=100,min_length=2) class Meta: model = Poll fields = ['title','choice1', 'choice2', 'choice3'] I am increasing choices from forms. views.py def detail_poll(request,poll_id): poll = get_object_or_404(Poll, id=poll_id) for choice in poll.choice_set.all(): printChoice = choice.choice_text context = { 'printChoice ':printChoice , } return render(request, 'detail_poll.html',context) In view i am accessing all the choice from choice_text of the poll. I am accessing three choices for vote with the same (choice_set) method in template. AND When i create poll then poll is successfully saving with all three choices. When i vote then poll is successfully voting with choices. BUT when i accessing the choices to …