Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: How to call all objects of a class with their attributes in Django?
For some context, the class is meant to hold the metadata of the products, which are objects. Now, I would like to pass the objects to my template, in order to call its attributes. Here's my code in views.py: def prices(request): @attr.s class ProductMetadata: """ Metadata for a Stripe product. """ stripe_id = attr.ib() name = attr.ib() features: list = attr.ib() monthly_price = attr.ib() yearly_price = attr.ib() standard = ProductMetadata( stripe_id='example', name='Standard', features=[(True ,"Up to 1000 DMs"), (False, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month1", yearly_price = "year1" ) premium = ProductMetadata( stripe_id='example2', name='Premium', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month2", yearly_price = "year2" ) business = ProductMetadata( stripe_id = "example3", name = 'Business', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (True, "Premium Support")], monthly_price = 'month3', yearly_price = 'year3' ) return render(request, 'instagram_prices.html', {'products': ProductMetadata.all()}) How can I achieve this? Thanks! -
django api using generic views for deleting multiple objects
i'm trying to use django generic view. and i want to be able to delete multiple objects at the same time using the same view.for example delete all the 'femail' Employees in my model. i used the following code: from ..models import Employee from . import serializer from rest_framework import generics, status from rest_framework.response import Response from django.shortcuts import get_list_or_404, get_object_or_404 class EmployeeDeleteandUpdate(generics.UpdateAPIView): queryset = Employee.objects.filter(gender__startswith='femail') serializer_class = serializer.PostSerializer def delete(self, request, *args, **kwargs): myobj = get_object_or_404(Employee, gender=kwargs['gender']) myobj.delete() return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT) and heres my url code: path('mydel/<str:gender>/', view.EmployeeDeleteandUpdate.as_view()), and also my model: class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) gender = models.CharField(max_length=10) national_code = models.CharField(max_length=11) personal_code = models.CharField(max_length=15) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=50) married = models.BooleanField() age = models.IntegerField() wage = models.IntegerField() def __str__(self): return self.first_name but when i use delete method with following url in my django rest framework: http://127.0.0.1:8000/mydel/femail/ i get this error: client.models.Employee.MultipleObjectsReturned: get() returned more than one Employee -- it returned 2! can somebody help me with this problem please?? -
Limit access to views in Django based on account type
How to limit access to views in Django? My Account model is like this: class Account(AbstractBaseUser): ... account_type = models.PositiveSmallIntegerField(default=0, choices=ACCOUNT_TYPE_CHOICES) I want to use a custom decorator to all my views based on account type but I don't know where to start. Currently on my views, this is what I have done: @login_required(login_url='/login/') def dashboard(request, *args, **kwargs): if request.user.is_authenticated: if request.user.account_type == 1: return redirect('admin_page') else: .... But this one is very repetitive. -
Can't display images from models when debug=false
I have asked another question about the issue of displaying images from models. and It was because I didn't add media url to urlpatterns. But it turns out that it only works when I set debug=true in settings file, when I set debug=false, I got 404 error again, any expert here to help ? I need to set debug=false for production here my urls.py file from django.contrib import admin from django.urls import path from home import views as HomeViews from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings import os urlpatterns = [ path('admin/', admin.site.urls), path('',HomeViews.index,name='home') ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my settings file from pathlib import Path import os import django_heroku import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE … -
Django filter queryset only if variable is not null
I have a queryset it filter by 2 variables family = ModelsClass.objects.filter(foo=var1).filter(bar=var2) If var1 and var2 are not null everything work but var1 and var2 can be Null. In this case i need to exclude the Null one. For example, if var1 is Null it must filter only by var2 and the other way around. There is a way to insert an if condition inside the filter queryset or something else? TY -
Model method to generate the value for a parameter of an attribute
I want to create a method inside a model which can be called on a parameter of an attribute to populate it. I thought of doing it this way but it gives me an error NameError: name 'self' is not defined. class Host(User): class Meta: verbose_name = "Host" verbose_name_plural = "Hosts" def gen_path(self): path = 'static/{userdir}'.format(userdir=self.email) os.mkdir(path) return path hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=self.gen_path(), null=True) What could be a workaround for this? -
django.db.utils.DatabaseError: Error while trying to retrieve text for error ORA-01804
Q1. What versions are we using? Ans. Python 3.6.12 OS : CentOS 7 64-bit DB : Oracle 18c Django 2.2 cx_Oracle : 8.1.0 Q2. Describe the problem Ans. While running server with "python3 manage.py runserver" application is able to contact Oracle DB and show the Django Administration page and login also works. But when we access the application using the Apache (HTTPD) based URL over secure SSL port, we do see the Django page and the admin page as well but Login to Admin page with Internal server error. In the logs, we see "django.db.utils.DatabaseError: Error while trying to retrieve text for error ORA-01804" cx_oracle is otherwise able to connect to the database properly, another application is also using the same database behind the same httpd proxy and works fine Q3. Show the directory listing where your Oracle Client libraries are installed (e.g. the Instant Client directory). Is it 64-bit or 32-bit? Ans. 64-bit Q4. Show what the PATH environment variable (on Windows) or LD_LIBRARY_PATH (on Linux) is set to? LD_LIBRARY_PATH=/srv/vol/db/oracle/product/18.0.0/dbhome_1/lib:/lib:/usr/lib PATH=$ORACLE_HOME/bin:/srv/vol/db/oracle/product/18.0.0/dbhome_1/lib:$PATH Q5. Show any Oracle environment variables set (e.g. ORACLE_HOME, ORACLE_BASE). ORACLE_HOME=/srv/vol/db/oracle/product/18.0.0/dbhome_1 TNS_ADMIN=$ORACLE_HOME/network/admin NLS_LANG=AMERICAN_AMERICA.AL32UTF8 ORACLE_BASE=/srv/vol/db/oracle CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/lib Any suggestions/help is highly appreciated. Thank you -
Django: How to get total cart item in ecommerce
I am trying to add the total item in the cart, but I am getting <property object at 0x000001CFFDED8228>: could anybody help? View.py class checkout(ListView): model = OrderItem template_name = 'product/checkout.html' def get_context_data(self, **kwargs): context = super(checkout, self).get_context_data(**kwargs) context['orderQty'] = Order.get_cart_items return context model.py 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=False) transaction_id = models.CharField(max_length= 200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum(item.quantity for item in orderitems) return total size_choices = (('small', 'S'), ('medium', 'M'), ('large', 'L')) 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) date_added = models.DateTimeField(auto_now_add=True) quantity = models.IntegerField(default=0, blank=True, null=True) size = models.CharField(max_length= 200,choices= size_choices, default=0) @property def get_total(self): total = self.product.price *self.quantity return total template.html: <div class="row-1"> <div style="flex:2;"><strong>Total Items</strong>:<span style="float: right;">{{orderQty}}</span></div> <hr> <div style="flex:2;"><strong>SubTotal</strong>:<span style="float: right;">$387</span></div> <hr> <div style="flex:2; margin-top:10px"><strong>Shipping</strong><span style="float: right;">$54</span></div> <hr> </div> <div> <div style="flex:2; text-align:center"><h6>Total: $387</h6></div> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Pay"> </div I believe these files contain the problem but from researching online I can't seem to pinpoint exactly what it is. The function based view of my website was working fine until I moved to class-based … -
image not uploading Django for loop and Bootstrap Card
I trying to upload image. I used Django for loop and inside it placed Bootstrap Card. Products {% for product in products %} {{product.name}} ${{product.price}} ORDER NOW {%endfor%} -
Show some readonly fields and a preview (not a field)
Django 3.1.6 class SvgFile( CreatedMixin, AltMixin, CommentMixin, models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Creation date")) file = models.FileField(upload_to=svg_upload_to, verbose_name=gettext_lazy("SVG file"),) def preview(self): return mark_safe('<img width="100" src="{}" />'.format(self.file.url)) preview.short_description = gettext_lazy('Preview') preview.allow_tags = True class Meta: verbose_name = gettext_lazy("SVG file") verbose_name_plural = gettext_lazy("SVG files") class SvgFileForm( ModelForm): class Meta: model = SvgFile exclude = [] Could you help me understand how to show id, created and preview in edit view of Django admin site? -
How to configure django-db-multitenant?
I am trying to use django-db-multitenant and I am doing something wrong. I am getting error ('%s does not subclass db_multitenant.mapper.TenantMapper', 'demo.mapper.TenantMapper'). It would be great help if anyone can help me regarding this. -
Django : matching query does not exist
I am getting error while creating an instance of ModelForm in DJango. I am not always facing the issue but sometimes it work fine and sometimes it gives me error. ModelFOrm code : class ClientinfoForm(ModelForm): Account_Name = forms.CharField(disabled=True) class Meta: model = AccountDescription fields = ['Account_Name','short_Name','group_Master_Project_Code','account_Logo','vertical','client_Website','client_Revenue','Employee_Count','client_Industry_Segment','delivery_Manager_Mail','project_Manager_Mail'] labels = {'client_Revenue':'Client Revenue(in USD Billion)','vertical':'Industry Vertical'} help_texts = {'client_revenue' : '(In Billion USD)' } views.py code def save_client_info(request): fm = ClientinfoForm(request.POST, instance = AccountDescription.objects.get(Account_Name = acc_name),files = request.FILES or None) save_form(request,fm) def clientinfo(request): if request.user.is_authenticated: if request.method == 'POST': print("inside form") save_client_info(request) global s4_option s4_option = AccountDescription.objects.filter(Account_Name = acc_name).values('s4_data') s4_option = s4_option[0]['s4_data'] accdata = AccountDescription.objects.filter(Account_Name = acc_name) clientdata = ClientinfoForm(instance = AccountDescription.objects.get(Account_Name = acc_name)) return render(request, 'AccountData/ClientInfo.html',{'name' : 'clientinfo','form':clientdata,'acntdata':accdata,'content':editoption}) Sometimes, when I save it works perfectly fine but sometimes it give matching query doesn't exist. Let me know if more information is required. -
'CreateView' object has no attribute 'render_to_response'
I have this create view and it throws the error 'CreateView' object has no attribute 'render_to_response' urls.py path( "p/<int:id>/food/create", views.FoodCreateView.as_view(), name="food-create", ), views.py class FoodCreateView(BaseCreateView): template_name = "food_form.html" form_class = forms.FoodForm success_message = "successfully created" def get_queryset(self): return Food.all(#####) def get_success_url(self): return reverse( "food_list" ) am I lacking anything with the code? -
Django AttributeError at /upload/
When I'm trying to run my view.py, I get this error: 'list' object has no attribute 'name' at the fourth line of view.py that I have attached below. My app basically allows users to upload photos and save them after they are edited automatically. This error happens right after I click upload. forms.py class PhotoForm(forms.ModelForm): image = MultiImageField(min_num=1, max_num=20) class Meta: model = Post fields = ['name'] widgets = {'name': forms.HiddenInput()} views.py def photoform(request, *args, **kwargs): if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): a = form.save() models.py class Post(models.Model): name = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) I don't know if this helps, but here is what the error shows. -
How to store filtered data in excel in Django?
Made a view that pulls data from the model. Based on this data, the table in the template is filled. For each field of the table (model) added filtering based on django-filters. Faced the following problem, I need to save filtered data to excel. The problem is precisely in getting the filtered data, saving in excel is not a problem. My class based view: class RequestList(FilterView): template_name = 'MQueryboard/Requests/RequestList.html' filterset_class = Filter_Adjustments_view model = Adjustments paginate_by = 3 def get_queryset(self): filterset_class = Adjustments.objects.order_by('-dateadjustment') return filterset_class def get_context_data(self, *args, **kwargs): _request_copy = self.request.GET.copy() parameters = _request_copy.pop('page', True) and _request_copy.urlencode() context = super().get_context_data(*args, **kwargs) context['parameters'] = parameters return context def post(self, request): if request.method == 'POST': response = adjustments_to_excel(Adjustments.objects.all()) return response else: return render(request, 'MQueryboard/Requests/RequestList.html', {}) The adjustments_to_excel function - in order not to load the view, data is sent to the script to generate an Excel file. Here I do not understand how I can get the filtered queryset in the post function. Now, as a "stub" is the selection for all fields of the model. Please tell me how you can do this. I've been struggling with this question for a week, nothing has been working out yet. Thanks in … -
Can't display images from models of django
Since I have faced this problem many times and couldn't find a solution, I need help Here's my settings file. I've configured media root from pathlib import Path import os import django_heroku import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'testimage.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'testimage.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-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', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = … -
django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name
I am trying to create a url-shohrtener and it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('shorturl.urls')), ] here is my apps urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:id>/', views.redirect_url, name='redirect'), ] these are the views.py: from django.shortcuts import render, redirect from .models import Url import random import string def redirect_url(request, id): urls = Url.objects.filter(short=id) link = "" for i in urls: link = i.url return redirect(link) def index(request): if request.method == "POST": link = request.POST.get("link") short = "" if Url.objects.filter(url=link).exists(): urls = Url.objects.all() for i in urls: if i.url == link: short = i.short break else: short = get_short_code() url = Url(url=link, short=short) url.save() new_url = request.get_host() + "/" + short return render(request, 'shorturl/index.html', {"new_url":new_url}) return render(request, 'shorturl/index.html') def get_short_code(): length = 6 char = string.ascii_uppercase + string.digits + string.ascii_lowercase while True: short_id = ''.join(random.choice(char) for x in range(length)) if Url.objects.filter(short=short_id).exists(): continue else: return short_id just in case it is important this is the template: <!doctype html> <html lang="en"> <head> <!-- Required … -
Filter Django queryset using dropdown box and ajax
I have the following view and template. I would like to filter (current_state is the variable I'm using) the query set using the dropdown list and jquery or ajax to reload the data on the page. Views.py def dashboard(request): records = Employee.objects.filter(owner_id__profile__state=current_state) #my queryset return render(request, "dashboard.html", {"records" : records}) Template.html <form method="POST"> <select name="stateddl" id="stateddl"> <option value="AL" selected>Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> ... </select> </form> ... <table> <thead> <tr> <th>Name</th> <th>State</th> <th>Phone</th> </tr> </thead> <tbody> {% for r in records %} <tr> <td>{{ r.name }}</td> <td>{{ r.state }}</td> <td>{{ r.phone }}</td> </tr> {% endfor %} </tbody> </table> -
ImportError: cannot import name 'employees' from 'rest_framework'
from rest_framework import employees ImportError: cannot import name 'employees' from 'rest_framework' (C:\Users\SONY\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework_init_.py) how to solve this error? -
Can I put custom settings in Django's settings.py
I have several custom settings I'd like to define in my Django app. Up to this point, I've put them in a constants.py file in each individual app. myapp/constants.py HOURS_PER_EVENT = 4 MAX_MEMBERS_PER_EVENTS = 150 MAX_EVENTS_PER_YEAR = 10 ... It just occurred to me I may be able to put these in settings.py and after a quick test everything seems to work fine. Is this allowed or is settings.py reserved for core django settings defined here? If it's not allowed, is there a better place to put these. -
Is there a way to create an endpoint (and subsequently view) for a choice field in a Django backend?
In my Django models.py file, I have a variable ColourChoices = ((0, "GREEN"), (1, "YELLOW"), (2, "RED"), (3, "GREY")) where in the same file, ColourChoices is used in class class Rainbow(models.Model): colour = models.IntegerField(choices=ColourChoices) I was wondering if there is a viable way to create a view for ColourChoices (i.e. some JSON endpoint), such that you can get all the existing values for it (GREEN, YELLOW, RED, GREY) without creating a new table in the underlying database and adding those values to it? That is, in such a way that if I were to add a new colour (e.g. BLUE), or remove one colour from the choices, that doing it once in the code would do the trick (i.e. change what you see in the view). -
what is the most optimal way of using location in django
If I am trying to create a location based recommender system in Django and where to start, Thanks in advance for answering this silly question -
django: prefetch with only() is causing many queries
If i am using only() in prefetch then its causing lot of sql queries queryset = SymbolList.objects.prefetch_related( Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in= [1,....,200]).only('close','volume').order_by('datetime') ) for symbolObject in querset: querysetDaily = symbolObject.stock_dailypricehistory_symbol.all() for daily in querysetDaily: print(daily.volume,daily.close) this is causing sql query which is accpeted SELECT `daily_price_history`.`id`, `daily_price_history`.`volume`, `daily_price_history`.`close` FROM `daily_price_history` WHERE (`daily_price_history`.`id` IN (SELECT U0.`id` FROM `daily_price_history` U0 WHERE (U0.`datetime` >= 1604718922708 AND U0.`symbolId_id` = `daily_price_history`.`symbolId_id`)) AND `daily_price_history`.`symbolId_id` IN (1, 2, .. .. 200)) ORDER BY `daily_price_history`.`datetime` ASC but also many queries like which is not supposed to SELECT `daily_price_history`.`id`, `daily_price_history`.`symbolId_id` FROM `daily_price_history` WHERE `daily_price_history`.`id` = 11346597 LIMIT 21 I found the traceback causing the above sql to: File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1710, in prefetch_related_objects obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1823, in prefetch_one_level prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level))) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 637, in get_prefetch_queryset instance = instances_dict[rel_obj_attr(rel_obj)] File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 647, in get_local_related_value return self.get_instance_value_for_fields(instance, self.local_related_fields) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 667, in get_instance_value_for_fields ret.append(getattr(instance, field.attname)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\base.py", line 635, in refresh_from_db db_instance = db_instance_qs.get() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 53, in __iter__ … -
How to make a Python html implementation of Battleship(Flask or Django)?
Would it be easier for the program to get inputs from the terminal or from somewhere else? Why do you need flask/django and which one would be better? -
Exception Value: No module named 'PIL' - in Django
Django Version: 3.1.6 Python Version: 3.6.9 I'm trying to use the ImageField in my django admin page to upload an image. When I try to upload it from my NGinx/Gunicorn server I get this error. However when I run it from port 8000 using manage.py runserver 0:8000 from the SAME server, it works. I don't understand this error. I have Pillow installed. Environment: Request Method: POST Request URL: http://54.188.59.209/admin/core/employee/add/ Django Version: 3.1.6 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core'] Installed Middleware: ['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 "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, …