Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Type Error 'NoneType' object is not subscriptable
im making a product checkout page and im trying to access my cart items from the following util.py file. I have seen that lot of sites saying that the 'NoneType' object is not subscriptable error, means that i attempted to index an object that doesn't have that functionality. But i cant figure out what is wrong. The error occurs in the cartData function views.py from .utils import cartData def checkout(request): #call method from utils.py data =cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = { 'items': items, 'order': order, 'cartItems': cartItems } return render(request, 'store/checkout.html', context) utils.py def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: # check if product exists try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product': { 'id': product.id, 'name': product.name, 'price': product.price, 'imageURL': product.imageURL, }, 'quantity': cart[i]['quantity'], 'get_total': total } items.append(item) if product.digital == False: order['shipping'] = True except: pass return{'cartItems': cartItems, 'order': order, 'items': items} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, … -
Filter unique data in Django
Im having a trouble how to filter unique value in Django, let say I have this data from my database and I just want to filter the unique value Expected output should like this, and to filter this data to my select option China Denver Manila Tokyo Japan Usa Australia Brazil views.py def sample(request): country= Country.objects.all() formats = {'filter':country} return render (request,'sample.html',formats ) Is there any expert know about this? -
How to get and return a model instance by id using Django ModelForm when there is too many instances?
I have a ModelForm for an Inline and I am trying to accept an id of an instance and then get the instance and 'return it to the field' as the field is a ForeignKey field. I cannot use (Model)choicefield as there are thousands of instances which means it takes ages to load. Neither I can take for example a slice of the most recent objects and choose from those as it results in a cannot filter the queryset once a slice has been taken error. I have tried working around with the save method but I couldn't make it so far. (but it is my bet that this will be the way to go) I would like the form to take three ids and then get those instances by model.objects.get(id=id) and then somehow create a new instance. the code looks as follows; class AgregatorCrossSaleProductForm(forms.ModelForm): IsShown = forms.BooleanField(required=False) ParrentProductId = forms.IntegerField() ChildProductId_id = forms.IntegerField() CrossSaleProductTypeId = forms.IntegerField() class Meta: model = AgregatorCrossSaleProduct exclude = [] class AgregatorCrossSaleProductInline(admin.TabularInline): model = AgregatorCrossSaleProduct form = AgregatorCrossSaleProductForm ... Any tip would be much appreciated. Thank you in advance -
AttributeError 'tuple' object has no attribute 'get'
I have a Django application. But i have an error which i have been struggling with for some time now. Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response Traceback django has provided me : File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: My View File : https://hasteb.in/ayafusug.py -
Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance
I am building an e-commerce website using django.Whenever i try to fill the checkout form and submit the form it shows me this error: "Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance." I am really confuse here I got stuck here Here is my Views.py for checkout : class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) #print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Here is my Models.py: from django.db import models import datetime # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @staticmethod def get_categories(): return Category.objects.all() class Brand(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name def get_brands(): return Brand.objects.all() class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') price = models.FloatField() @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_products_by_category(category_id): if category_id: return Product.objects.filter(category=category_id) else: return Product.get_all_products() @staticmethod def get_brands_by_products(brand_id): if brand_id: return Product.objects.filter(brand=brand_id) else: return Product.get_all_products() @staticmethod def get_products_id(ids): return Product.objects.filter(id__in=ids) class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100, default=1) … -
Why js script does not load ajax response? [duplicate]
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found), -
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
unable to find some .py files of apps in django project
I want to ask about how can I access all ".py files" of all apps in my Django project. Actually, my developer is not responding to me I don't know why the last time he gave me my Django project in zip file. I have installed it successfully in my mac but now he is not responding to me but I have to work on the project by myself so I am worried about my Project. I have taken a screenshot of my project directory structure enter image description here installed apps portion of base.py file of settings looks like this. DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', ] THIRD_PARTY_APPS = [ 'rest_framework', 'polymorphic', #'django_extensions', 'apps.cabinet_extension.apps.CabinetConfig', #'cabinet', 'imagefield', 'easy_thumbnails', 'ckeditor', 'ckeditor_uploader', 'nested_inline', ] PROJECT_APPS = [ 'apps.core', 'apps.blog', 'apps.faq', 'apps.carty', 'apps.cart', 'apps.accounts.apps.UserConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS And the URL pattern of urls.py file of azapp looks like this path('super-admin/', admin.site.urls), path('accounts/login/', auth_views.LoginView.as_view()), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('apps.core.urls')), path('blog/', include('apps.blog.urls')), path('faqs/', include('apps.faq.urls')), path('product/', include('apps.carty.urls')), path('cart/', include('apps.cart.urls')), please help me I am so worried about it Thanking in advance! -
Django unit-Testing authorization for API
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 django-oauth-toolkit==1.3.2 I already write my rest APIs . Now I want to write my Unit Test case but while writing test cases it showing unauthorized error Here my code tests.py import unittest from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse # Models imported from django.utils import timezone from end_device.models import Employee from oauth2_provider.models import Application, AccessToken, RefreshToken from rest_framework import status from django.test import Client class MyTestCase(TestCase): def setUp(self): self.client = Client() self.create_employee = Employee.objects.create(EmployeeName="Testcase2", EmployeeCode="1005", Security=0) self.user = User.objects.create_superuser(username="fdp", password="user12345") self.user_staff = User.objects.create_user(username="user", password="user12345") self.application = Application.objects.create( name="Test Application", user=self.user, client_id="123", client_secret="12345abc", client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, ) self.access_token = AccessToken.objects.create( user=self.user_staff, scope="read write groups", expires=timezone.now() + timezone.timedelta(seconds=3000), token="123efrwasdd", application=self.application ) self.refresh_token = RefreshToken.objects.create( user=self.user_staff, token="refresh_token", application=self.application, access_token=self.access_token ) def test_employee(self): inputData = { "EmployeeName": "TestEmp", "EmployeeCode": "1007", "Security": 0 } header = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + format(self.access_token.token), } url = reverse('employee_entry') resp = self.client.post(url, data=inputData, headers=header) self.assertEqual(resp.status_code, status.HTTP_200_OK) My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data employee = Employee( EmployeeName=emp_data["EmployeeName"].strip(), EmployeeCode=emp_data["EmployeeCode"].strip(), Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) … -
Paginator in a view function Django
I'm trying to add the paginate option on my posts page from my blog website. I want to implement the paginator on my view function that renders the page and I found this exemple from Django's doc but it doesn't work. Any help ? view function: def blog(request): posts = Post.objects.all().order_by('-date_posted') paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) html rendering <nav class="blog-pagination justify-content-center d-flex"> <ul class="pagination"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="ti-arrow-left"></span> </span> </a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item active"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="ti-arrow-right"></span> </span> </a> </li> {% endif %} {% endif %} </ul> </nav> the url route path('blog/', blog, name='blog'), -
Django createview m2m not saving
Trying to add the creator of team to the members automatically. Team model has a m2m relationship with UserProfile as members, here is the code: class CreateTeamView(generic.CreateView): model = Team template_name = 'team_create.html' fields = ('title', 'code', 'coordinator', 'description', 'members') success_url = '/teams' def form_valid(self, form): instance = form.save(commit=False) if not instance.creator: instance.creator = self.request.user.userprofile instance.save() instance.members.add(instance.creator) form.save_m2m() return super().form_valid(form) But it doesn't work. Team gets created and also the creator is assigned but doesn't get added to members. Please enlighten me. -
Django-admin start project <name> creates old version django project
I created a directory "DjangoProject1" and in it created django project through the terminal with the line $ django-admin startproject project As I was expected, there were created two things in the directory "project": file "manage.py" and another directory "project". The problem is that in that directory "project" there were: {init, setting, urls, wsgi}.py, but there wasn't file "asgi.py". From there I understood that there was created an old version django project. Again! I checked it one more time in "urls.py" file and I saw this: urlpatterns = [ url(r'^admin/', admin.site.urls), ] instead of this: urlpatterns = [ path('admin/', admin.site.urls), ] So it is definitely an old version of django project. I don't know why this problem occurs, as I installed a new version of django, and I was able to create new version django project, though I don't remember how I was doing that. Can anyone help me to liquidate this problem so that only new version django projects would be created? (PS before new version maybe I installed an old version, and probably in my computer now there are both: new and old versions of Django) -
Django Rest Framwork - Put FileField value into response
in my Django Rest Framwork project, I have the following view: class RegistrationView(APIView): def post(self, request, format=None): data = {} # check if email exists ... # check if username exists ... # at this point, we know everything is ok -> the serializer can do its work serializer = RegistrationSerializer(data = request.data) if serializer.is_valid(): account = serializer.save() data['response'] = 'registered new user' data['id'] = account.id data['email'] = account.email data['username'] = account.username data['profile_pic'] = account.profile_pic <--- HERE the problem occurs!! data['date_joined'] = account.date_joined token = Token.objects.get(user=account) data['token'] = token.key else: data = serializer.errors return Response(data) I tried to put the result of the registration process into data dictionary which is then returned as response to the user. But in the line where I have data['profile_pic'] = account.profile_pic an exception occurs stating this: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte The profile_pic field of the Account model is a FileField as you can see in the following: class Account(AbstractBaseUser): ... profile_pic = models.FileField(upload_to='Images/',default='Images/None/placeholder.jpg') How can I get the value of the FileField which basically points to the profile picture of the Account. -
Will there be any performance improvement when accessing objects this way in django ORM?
I have two models which contain ForeignKey from one to another. class M1(models.Model): name = models.TextField() class M2(models.Model): name = models.TextField() parent = models.ForeignKey(M1, related_name='children') I'm refactoring the code to improve performance. Will there be any performance difference between these 2 ORM queries. m1 = M1.objects.get(id=1) children = m1.children.all() and children = M2.objects.filter(parent_id=1) -
Django form with variable type
How would you make a price field in Django form? The input could be either price (float) or value from select (for free, offer, by agreement, etc). In database, it's stored in FloatField (negative values has special meaning). Is there a way to make it through Django form model? -
django passing a csv to another function that downloads this csv
i'm trying to pass a pandas dataframe (changed to csv file) to another fucntion(the download function) in django. the user should push a button and the dataframe(in csv format) should be ready to download for the user. i'm getting a missing 1 required positional argument: 'x' error. i've looked around on Stack but could not find an answer for this question. I think the problem is located in the def export because of the error I've got. but i've no idea how to fix it. views.py def result(request): if request.method =='POST': # some code to create the dataframe def process_file(file): data = file return data.to_csv x = process_file(df) #df for the dataframe created above return render(request, 'results.html', {'somedata':somedata,}), x def export(request, x): csv = x response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' return response -
Django Log to Telegram is not working and not creating model table
So, I have been working on utilizing this package: https://pypi.org/project/django-log-to-telegram/ I went through the exact steps the manual has: pip installing django log to telegram package, Added the telegram bot token after creating the telegram bot LOG_TO_TELEGRAM_BOT_TOKEN = '1489551033:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' And adding LOGGING onto the settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'handlers': { 'telegram_log': { 'level': 'ERROR', 'filters': [], 'class': 'django_log_to_telegram.log.AdminTelegramHandler', 'bot_token': LOG_TO_TELEGRAM_BOT_TOKEN, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['telegram_log'], 'level': 'ERROR', 'propagate': True, }, }, } Then I ran 'python manage.py migrate' to create the django-log-to-telegram models. It's supposed to create the django-log-to-telegram table in the database. However, I do not see any new database. -
Exclude by table name - django
I have raw query: select n.nspname as table_schema, c.relname as table_name from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind = 'r' and n.nspname not in ('information_schema','pg_catalog') and c.reltuples = 0 order by table_schema, table_name; which return all empty tables and I saved table names to models array. Now I would like exclude models from queryset: ContentType.objects.all().exclude(table_name__in=models) but I havn't access to table name in queryset. How can I do it? -
use django model's field value inside href tag in template
Here the issue that I am facing. Let's say I have a model with two field. Field1 is a string value and Field2 one contains a url link. I want to render Field1 and the user can click on Field1 and gets redirected to template at Field2 url. Here is what I have been trying: <td>{{class.Class}}<a href="{{ class.extra_details_view }}"></a></td> #class = Field1 #extra_detail_view = Field2 (link) this renders Class values just fine but does not let me click it. I don't know what else to try to get the desired output. -
My code fail to loop the single card on the template but the entire thing works fine
Hi there! this code fail to for loop in </d {% for user in userprofile %} {{ user.userprofile.title}} R{{ user.userprofile.price }} Mobile Phones » Brand {{ user.userprofile.publish_date}} {{ user.userprofile.City }} {% endfor %} my views class ClassifiedsView(ListView): model = UserProfile paginate_by = 10 # if pagination is desired template_name = 'all_classifieds.html' def get_context_data(self): context = super().get_context_data() objects = UserProfile.objects.all() context['object'] = objects return context then temple i call it a temple it work but can't for-loop and on my urlemphasized text class UserProfile(models.Model): user = models.OneToOneField(User, null='True', blank='True',related_name='userprofile' ,on_delete=models.CASCADE) title = models.CharField(max_length=120, blank=True,)path('<all_classifieds>/', ClassifiedsView.as_view(), name='all_classifieds'), any suppurt -
Error with Django Class 'City' has no 'objects' member
I'm learning Django and having a blast, I'm trying to build a weather app using Django and the Open Weather API. I seem to have run into an error that's making my head spin and I can't figure it out, I am trying to return a list of all the data in the database but I get this error Class 'City' has no 'objects' member" Here is my models.py file from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name And here is my views.py file import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q{}&units=imperial&appid=YOUR_API_KEY' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weather/weather.html', context) Any help will be greatly appreciated! -
Django RecursionError: maximum recursion depth exceeded while building a query
I am trying to build complex query this way: q = Q() if contacts: for contact in contacts: q |= Q(phone__icontains=contact) for contact in contacts: q |= Q(email__icontains=contact) if name: q |= Q(full_name__icontains=name) duplicates = Candidate.objects.filter( q ).values_list('pk', flat=True) But I get RecursionError: maximum recursion depth exceeded on this area. Not sure, what part of these code is recursive, and have no idea where to look for answer. -
Where is this self.add_error adds the error to?
I'm having a hard time trying to figure out the following code: from django import forms from django.contrib.auth.hashers import check_password class CheckPasswordForm(forms.Form): password = forms.CharField(label='password_check', widget=forms.PasswordInput( attrs={'class': 'form-control',}), ) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') confirm_password = self.user.password if password: if not check_password(password, confirm_password): self.add_error('password', 'password is wrong') here, I don't get the self.add_error('password', 'password is wrong') part. In the documentation, it says that the password here is the field in add_error('field', 'error'). So, is the error being added to the password field? or is it being added to the following part? def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user because if I have to access this error in the html template, I would have to do something like this, {% if password_form.password.errors %} and if it means accessing errors from password field, it should mean that the error is added to the password field... but the self.add_error part confuses me -
I am not able to link pages in Django
I believe I have linked my urls, views and templates very well but I don't why I am getting the error. urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('legal/', legal, name='legal') ] views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'base/base.html') template <nav class="nav-menu d-none d-lg-block"> <ul> <li><a href="{% url 'home' %}">Inicio</a></li> <li><a href="{% url 'about' %}">Quienes somos</a></li> </ul> </nav>