Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recommended database administrator for Django and PostgreSQl
Having a web based in Django with PostgreSQL : django.db.backends.postgresql_psycopg2 I used to work in other framework with database administrators, such as PhPmyAdmin, SequelPro for MySQL DBs. I liked to see all rows, run some queries... Now, the django admin allows me to see some info, but I would like to run some queries and get some KPIS. Is there a similar database manager for postgreSQL? Is possible to install that or should use Django admin? Web info: Django 2.1.7 DB: django.db.backends.postgresql_psycopg2 Hosted in a Docker container with Ubuntu 20.04 -
QuerytSet raised: related field got invalid lookup :iexact
I am trying to filter my foreign key and obtain the query set of PhoneOtp model . class User(AbstractBaseUser,PermissionsMixin): phone_regex=RegexValidator(regex = r'^[6-9]\d{9}$',message='please enter the correct phonenumber') phone=models.CharField(validators=[phone_regex],max_length=15,unique=True) name=models.CharField(max_length=15,blank=True) class PhoneOtp(models.Model): phone = models.ForeignKey(User,on_delete=models.CASCADE,default=None) otp = models.CharField(max_length=9,blank=True,null=True) Above are two my models I am trying the below query:- old = PhoneOtp.objects.filter(phone__iexcat=phone) I want to have the query set of PhoneOtp model filtering with the phone number , but it is giving me error for related field got invalid lookup :iexact. I have searched a lot but not able to rectify this. I am using foreign key lookup for the first time in django ORM. -
Django-Rest All Auth custom JWT token
As login I get a key in Django rest all auth . I want to customize that key or token so that I can make my own JWT token with user details. -
django smart-select security issue
I have implemented django smart-select successfully, but it has problem with security. The endpoint is readable without any permissions. I also found a warning from smart-select document but I don't know how to use django-autocomplete-light. Does django-autocomplete-light support the same feature with smart-select? Is there anybody know how to fix this security issue. Warning: The AJAX endpoint enforces no permissions by default. This means that any model with a chained field will be world readable. If you would like more control over this permission, the django-autocomplete-light package is a great, high-quality package that enables the same functionality with permission checks. -
Facing MYSQL-python error while running requirements.txt in django
hi im trying to clone a project (which I have successfully) now im installing all the packages required using requirements.txt file, most of the packages have been installed correctly but while installing MyqSQL-python package it is throwing an error. Collecting MySQL-python==1.2.5 Using cached MySQL-python-1.2.5.zip (108 kB) Building wheels for collected packages: MySQL-python Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/apple/pyenvs/slotswise_env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/j8/fqv9vl154_g9zsq6psx988340000gn/T/pip- install-EkYTtZ/MySQL-python/setup.py'"'"'; __file__='"'"'/private/var/folders/j8/fqv9vl154_g9zsq6psx988340000gn/T/pip-install-EkYTtZ/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/j8/fqv9vl154_g9zsq6psx988340000gn/T/pip-wheel-vUemWb cwd: /private/var/folders/j8/fqv9vl154_g9zsq6psx988340000gn/T/pip-install-EkYTtZ/MySQL-python/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.15-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.macosx-10.15-x86_64-2.7 creating build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb creating build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.15-x86_64- 2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.15-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.15-x86_64-2.7 cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -iwithsysroot /usr/local/libressl/include -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -pipe … -
Want to replace the empty list with Not found [closed]
domain_item['content_categories']=each_value.get('content_categories',[]) {% for each_item in item.domains %} {% if len(each_item.content_categories) == 0 %} <td>Not found</td> {% else %} <td>{{each_item.content_categories}}</td> {% endif %} So for some of the content categories its giving []. I want to replace those with Not found. Error:Could not parse the remainder: '(each_item.content_categories)' from 'len(each_item.content_categories)' -
Django3 prefetch_related
I had worked by django 2.X. But i'm gonna use django3.x at my new project. At version2, when I should make outer join.. I used prefetch_related and filtered about model of prefetch_related. In version 2, if i use prefetch_related it was queried by single query. but in version 3, quried by multiple query. If i only use Q() of joined target without prefetch_related, it works single query at version 3. from django.db import models from django.db.models import Q from django.db.models import Prefetch class Member(models.Model): member_no = models.AutoField() member_name = models.CharField() class Permission(models.Model): permission_no = models.AutoField() class MemberPermission(models.Model): member_permission_no = models.AutoField() member_no = models.ForeignKey( Member, related_name='members', on_delete=models.CASCADE, ) permission_no = models.ForeignKey( Permission, related_name='member_permissions', on_delete=models.CASCADE, ) my_permission = Member.objects.prefetch_related('member_permissions').filter(Q(member_permissions__isnull=False))[:1] print(my_permission[0].member_permissions) # member outer join permission, single query at django 2.X # member outer join permission & additional query at django 3.x my_permission = Member.objects.filter(Q(member_permissions__isnull=False))[:1] print(my_permission[0].member_permissions) # member outer join permission, single query at django 3.X my_permission = Member.objects.prefetch_related( Prefetch('member_permissions', MemberPermission.objects.select_related( 'permission_no').all()) ).filter(Q(members__isnull=False))[:1] print(my_permission[0].member_permissions.all()[0].permission_no.permission_no) # member outer join permission & additional query at django 3.x If i don't use prefetch_related, i could get single query. but if i want to get model of joined model (Permission of MemberPermission by Member) it couldn't. I … -
Reverse for 'userprofile' not found. 'userprofile' is not a valid view function or pattern name
When i write in urls.py app_name = 'user_homeview' then occure error in header.html how i solve this error can you tell me i couldn't solve error yet please tell me..in below html file where wrote href="{%url 'userprofile' i.user %}" in code occure error after write app_name='' in urls.py please tell me how i solve head.html {% for i in userpofile %} <img src="{{i.userImage.url}}" href="{%url 'userprofile' i.user %}" class="align-self-start img-responsi img-circle tm-border " alt="..."> <a href="{%url 'userprofile' i.user %}" >{{i.user}}</a>&nbsp {% endfor %} urls.py app_name = 'user_homeview' urlpatterns = [ path('', views.user_home,name='e'), path("user/follow/<str:username>", views.follow, name="follow"), path('postWrite', views.postWrite ,name='post'), path('post', views.post ,name='post'), path('like_dislike', views.likePost ,name='like_dislike_post'), path('slug/comment', views.comment ,name='comment'), path("delete/<int:ID>",views.delpost,name="delpost" ), path("search/", Search_User.as_view(), name="search_user"), path("<str:username>",views.userProfile,name="userprofile" ), path("<str:username>/edit", EditProfile.as_view(), name="editprofile"), -
how to write clean method between parent form and child form django formset
i need to make a validation error between InvoiceModel SelectQuantityModel and ReturnInvoiceModel SelectQuantityReturnModel , whenever i create a new ReturnInvoiceModel with its subform SelectQuantityReturnModel make sure if the selected invoice_number has its product which selected in SelectQuantityReturnModel these is my models which i need class InvoiceModel(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=15) product= models.ManyToManyField(Products,through='SelectQuantityModel') def __str__(self): return str(self.id) class SelectQuantityModel(models.Model): product= models.ForeignKey(Products, on_delete=models.CASCADE) items = models.ForeignKey(InvoiceModel,on_delete=models.CASCADE,default='') quantity= models.IntegerField() price = models.IntegerField() and for returns i also made two models class ReturnInvoiceModel(models.Model): invoice_number = models.ForeignKey(InvoiceModel,on_delete=models.CASCADE,related_name='customer_returns') product = models.ManyToManyField(Products,through='SelectQuantityReturnModel') class SelectQuantityReturnModel(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) item = models.ForeignKey(ReturnInvoiceModel,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() for example i created a new InvoiceModel with multi selected product with different quantities in SelectQuantityModel , and if a customer decided to return a product after buying , we will create another invoice named returns product in ReturnInvoiceModel we select its InvoiceModel number , then with its products which bought in that invoice , but sometimes happen i select a wrong product for that ReturnInvoiceModel so i need to make a validation error if a wrong product selected which not sold for that invoice number ,i decreased quantities in InvoiceModel with its SelectQuantityModel , using signals : def … -
Django queryset filtering out objects with common members
Im creating 2-step form. In first part captain is choosing one of his teams, in second i'm retrieving chosen team from first step and creating queryset based on it. Second form should only filter teams that doesn't have players in common with team from first step. class Team(models.Model): name = models.CharField(max_length=200, null=True, unique=True) captain = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="captain") team_creation_date = models.DateTimeField(auto_now_add=True, null=True) players = models.ManyToManyField(Player, through="PlayerTeam", related_name="players") class PlayerTeam(models.Model): player = models.ForeignKey(Player,on_delete=models.CASCADE) team = models.ForeignKey(Team,on_delete=models.CASCADE) join_date = models.DateField(auto_now_add=True) -
the django object sizes are different
there are two objects with html&django. I just study it. but i have something problem. when I add the 2 objects, then the second object's size is too big. what is the problem of django objects sizes are different? how can I change the django objects sizes make same to first object?? [enter image description here][1] enter code here <section class="jumbotron text-center"> <div class="container"> <h1>드리머리 </h1><br> <p class="lead text-muted">열정과 섬세함의 차이를 만드는 디자이너에게 받는<br>최고의 헤어 서비스, 드리머리 </p> <p> <a href="{% url 'introduce' %}" class="btn btn-outline-danger">드림머리 알아보기</a> </p> </div> </section> <div class="album py-5 bg-light"> <div class="container"> <div class="card-columns"> {% for designer in designers %} <div class="card mb-4 shadow-sm"> <!-- Imange --> {% if designer.image %} <img src="{{ designer.image.url }}" class="card-img-top" alt=" Designer_Image" {% else %} <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"> <title>Dreamary</title> <rect width="100%" height="100%" fill="#55595c" /><text x="50%" y="50%" fill="#eceeef" dy=".3em">Profile</text> </svg> {% endif %} <div class=" card-body"> <h4 class="card-title">{{ designer.name }} </h4> <h6 class="card-title">{{ designer.address }} </h6> <hr> <p class="card-text">{{ designer.description }}</p> </div> </div> {% endfor %} </div> </div> </div> </main> -
How to reduce option from one ForeignKey when there are two different ForeignKey and unique_together is defined?
I have two three models Product, ClothColor and Color. # products/models.py class Product(models.Model): ... class Color(models.Model): ... class ClothColor(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) ... class Meta: unique_together = ('product', 'color',) I wanted to allow only one combination of product and color in ClothColor, so I have used unique_together in Meta class. This constraint work fine. Now, I am using TabularInline to display ClothColor in admin panel, so it would be easier to add a product as well as its colour variations. # products/admin.py class ClothColorInline(admin.TabularInline): model = ClothColor ... class ProductAdmin(admin.ModelAdmin): ... inlines = (ClothColorInline,) And, this is how my admin panel looks. Now, when I add new color to the color field in clothColor, it also displays already used color. img: drop down menu in admin panel. Due to the unique_together constraint it shows me error, thus, it prevents accidently fill same color twice, but I need a way to hide the option altogether if the color is already used. So, how can I reduce the option in color field when I have already used that color? -
How to apply condition in filtering from Mysql using list of values
Db table verystrong strong moderate weak veryweak US aa a ba b caa UK aa a baa b caa Austria a baa ba caa ca Belgium a baa ba caa ca Japan aa a baa b caa UAE ba b b b1 c country='UK' traderow=exporttable.objects.filter(ratio=country).values()[0] traderow output: {'id': 2, 'ratio': 'UK', 'verystrong': 'aa', 'strong': 'a', 'moderate': 'baa', 'weak': 'b', 'veryweak': 'caa'} next i have the list a a=['verystrong','verystrong','strong','strong','strong','strong','strong'] a is rating made for years from 2013 to 2019 e.g 2019 rating is strong , in 2013 is strong. Now i want for each value in the list to match with value in traderow to find trade rating: I can return only one value from the list at a time: value1=a[0] whihc is 'verystrong' (year 2013) value7=a[6] whihc is 'strong' (year 2019) trade_rating2013=traderow[value1] which returns for year 2013 aa trade_rating2019=traderow[value7] which returns for year 2013 a My question is how to implement this operation effectively for the whole list not implemneting for each list seperately ?is that possible to apply lambda ? I am still learning python and would appreciate your help to optimize the code to remove redundancy and make it more effecient. -
Image Kit and ImportError: cannot import name 'six' from 'django.utils'
I'm trying to upgrade to Django 3, and I keep getting errors with 'six' being dropped from django.utils. I understand the fix is to upgrade my modules (ImportError: cannot import name 'six' from 'django.utils'), but Imagekit hasn't been updated for several years. I'm trying to remove imagekit from my project, but one of my migration files utilises it, and is there a way to remove imagekit from my model/migration without getting the error? File "/Users/dantang/Desktop/production/smartschool/core/migrations/0004_student_potrait_picture.py", line 6, in <module> import imagekit.models.fields File "/Users/dantang/anaconda3/envs/kongming/lib/python3.7/site-packages/imagekit/__init__.py", line 2, in <module> from . import conf File "/Users/dantang/anaconda3/envs/kongming/lib/python3.7/site-packages/imagekit/conf.py", line 1, in <module> from appconf import AppConf File "/Users/dantang/anaconda3/envs/kongming/lib/python3.7/site-packages/appconf/__init__.py", line 2, in <module> from .base import AppConf # noqa File "/Users/dantang/anaconda3/envs/kongming/lib/python3.7/site-packages/appconf/base.py", line 4, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (/Users/dantang/anaconda3/envs/kongming/lib/python3.7/site-packages/django/utils/__init__.py) MIGRATION FILE from django.db import migrations import imagekit.models.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20171102_1614'), ] operations = [ migrations.AddField( model_name='student', name='potrait_picture', field=imagekit.models.fields.ProcessedImageField(blank=True, null=True, upload_to='potrait_pictures/'), ), ] -
how I can send sms to user when new record insert
I have model Order class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30, null=True, ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) how I can send SMS to shop when order insert by the customer then shop receive SMS that You have new order by customer.name. the product.name in the quantity customer model class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.CharField(null=True, max_length=10) shop model class Shop(models.Model): user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=200, null=True) Phone = models.CharField(null=True, max_length=10) and my order views.py def CreateOrder(request, shop_id, product_id): customer = request.user.customer shop = Shop.objects.get(id=shop_id) product = Product.objects.get(id=product_id) form = OrderForm() quantity = request.POST.get('quantity') note = request.POST.get('note') if request.method == 'POST': order = Order.objects.create(customer=customer, shop=shop, product=product, quantity=quantity, note=note) return redirect('CustomerOrder') -
CreateView not uploading image and name of the user for a post
I'm making a web app which allows users to register to the site and let them post their posts. For taking in their post I have used the built in CBV: CreateView. In the user post I take in the name of the user using foreignkey with null=True, image, title. The problem is: when I go to the detail page of that post it shows that there is no file associated with the image field, so I made an if statement to check if the post contains an image. But then too, it does not show the image. It shows User:None. I don't know what is happening, I have read that CBV take the self.request automatically and there is no need to link the current user to the post. Following are the screenshots of my code: models.py browser image before clicking submit button browser image after clicking submit button (detail page of the post) post_detail.html views.py -
Objects with several ManyToManyField relation are duplicated in the result page of Django Admin
I have a ManyToManyField relation between two models and I can add a new relation with the code bellow, but then in the admin section of Django the same object (same id) is listed twice. Is it normal that an object with several ManyToManyField relations is duplicated in the result page of the Django Admin and how could I display only unique objects? My models class Exchange(models.Model): name = models.CharField(max_length=12, blank=True, null=True) class Currency(models.Model): code = models.CharField(max_length=100, null=True) exchange = models.ManyToManyField(Exchange, related_name='currency') This is how I update the m2m ex = exchange # This is my Exchange object code = 'ABC' try: Currency.objects.get(code=code, exchange=ex) # here I check a same relation exists except Currency.DoesNotExist: try: curr = Currency.objects.get(code=code) # here I test if the currency object is created with a relation to another exchange curr.save() curr.exchange.add(obj) log.info('New exchange added for currency', code=code, exchange=ex.name) except Currency.DoesNotExist: curr = Currency.objects.create(code=code) curr.save() curr.exchange.add(ex) log.info('New currency added', code=code, exchange=obj.name) else: log.warning('A relation between this currency and exchange is already created') Admin page You can see that Currency objects with id 8, 5 and 3 are duplicated. -
Travello web page not loading properly in django/ pycharm
I am configuring travello webpage using django and pycharm. I have placed all the static files and made the changes in settings.py file. In html i have added load static block at the beginning and added static block to all urls. Now when I run the server, all the static content is loading properly except two blocks having below class What can be the reason. Do we need to make any changes in css or js files as other sections are loading properly? -
duplicate Key violation in Django insert doing after Django update
first i update my model instance, after that i tried to insert a new data but showing "IntegrityError('duplicate key value violates unique constraint "RFIDActivation_ActivationId_key"\nDETAIL: Key ("ActivationId")=(6de9ed9a) already exists.\n',)" Models.py class RFIDActivation(models.Model): RFIDActivationId = models.AutoField(primary_key=True, db_column='RFIDActivationId') Device = models.ForeignKey(Device, on_delete=models.CASCADE, db_column='DeviceId') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') ActivationId = models.CharField(max_length=10, unique=True, default=uuid4().hex[:8]) ActivationStatus = models.CharField(max_length=1)default=None) class Meta: db_table = "RFIDActivation" my serializer.py class RFIDActivationSerializer(serializers.ModelSerializer): class Meta: model = RFIDActivation fields = '__all__' view.py @api_view(["POST"]) @permission_classes([IsAuthenticated]) def rfid_activation_initial(request): RFIDActivation.objects.filter(Employee=request.POST.get("Employee")).update( ActivationStatus='2', ActivationMessage='Abort' ) rfid_activation = { 'Employee': request.POST.get("Employee"), 'Device': request.POST.get("Device"), 'ActivationStatus': "0", 'ActivationMessage': "RFID Activation Initiated" } rfid_serializer = RFIDActivationSerializer(data=rfid_activation) if rfid_serializer.is_valid(): rfid_serializer.save() but rfid_serializer.save() shows exceptionexception Previous ActivationId is using to saving the new data. ActivationId is unique and auto generated. How can i solve this. -
Django PDFkit / wkhtmltopdf error finding the path for static css
I have an error when generating a file with pdfkit: QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root' Loading page (1/2) Warning: Failed to load file:///static/style.css (ignore) ] 0% Printing pages (2/2) ===] 100% Done The PDF is generated using this block of code: import pdfkit import tempfile from django.conf import settings from django.http import FileResponse from django.template.loader import get_template WKHTMLTOPDF_PATH = '/usr/bin/wkhtmltopdf' def generate_pdf(context): filename = str(context['pdf'].uuid) config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_PATH) template = get_template('admin/pdf.html') css_file = settings.BASE_DIR + '/pdf/static/style.css' invoice = template.render(context=context) options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': 'UTF-8', 'custom-header': [ ('Accept-Encoding', 'gzip') ] } with tempfile.NamedTemporaryFile(prefix=filename, suffix=".pdf") as f: pdfkit.from_string(invoice, f.name, css=css_file, configuration=config, options=options) return FileResponse(open(f.name, 'rb'), as_attachment=True, content_type='application/pdf') I don't think this is a python error as a try / catch block won't catch the error. It also seems strange as although an error appears in the terminal the generation of the PDF actually succeeds. I have looked into the XDG_RUNTIME_DIR message and it appears that this is more of a warning than an actual error but this could be the issue. The main error seems to be that it is failing to load a css file that has a different … -
I a getting error 'function' object has no attribute 'model'
I am making a filter and getting the error 'function' object has no attribute 'model' my filters.py class ProductFilter(django_filters.FilterSet): Product_name = CharFilter(field_name='name', lookup_expr='icontains') class Meta: model = Product fields = ['name'] and my views.py def CustomerShopProducts(request, pk): shop = Shop.objects.get(id=pk) product = shop.product_set.all myFilter = ProductFilter(request.GET, queryset=product) product = myFilter.qs context = {'product': product,'myFilter':myFilter} return render(request, 'CustomerShopProduct.html', context) how can create filter of the products -
COPY failed: stat /var/lib/docker/tmp/docker-builder073318368/Pipfile: no such file or directory
This is my Dockerfile. also you can see the image of Dockerfile #Dockerfile Pull base image FROM python:3.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 Set work directory WORKDIR /code Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system Copy project COPY . /code/ #Dcokerfile image [1]: https://i.stack.imgur.com/DvcAD.png When i run this file it gives me error. I run this file of ubuntu 18.04 for the testing simple django project. -
Exception has occurred: ImportError DLL load failed while importing pdftotext: The specified module could not be found
I am new to Python and currently having trouble when importing some libraries. I have install pdftotext via pip install pdftotext and conda install -c conda-forge poppler after following the instruction from this link Unable to install pdftotext on Python 3.6, missing poppler Now I get the following error when I try to import pdftotext using visual studio code; Exception has occurred: ImportError DLL load failed while importing pdftotext: The specified module could not be found. -
Why is Bootstrap 4 locally not loading in a Django Project?
I am using Django to write my first blog project. and using bootstrap 4 in my project works fine until now but suddenly it stops working. I didn't make any changes to my project, especially to the CSS link. here is the code. <link href="{% static 'css/bootstrap.min.css'%}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/main.css'%}"> even I try to use bootstrap.css but not working the server runs correctly there is no error even in the console. -
How to save uploaded image to Model in Django?All fields except the image field is getting saved to Model
HTML CODE::::: <div class="section-top-border" style=" margin-left : 500px "> <div class="row"> <div class="col-lg-8 col-md-8"> <h3 class="mb-30 title_color" style="margin-left : 400px ">Add Products to Sell</h3> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="mt-10"> <input type="text" name="name" placeholder="Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Name'" required class="single-input"> </div> <div class="mt-10"> <input type="email" name="email_address" placeholder="Email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Email address'" required class="single-input"> </div> <div class="mt-10"> <input type="text" name="address" placeholder="Address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Address'" required class="single-input"> </div> <div class="mt-10"> <input type="number" name="contact_number" placeholder="Contact Number" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Contact Number'" required class="single-input"> </div> <div class="mt-10"> <div class="form-select" id="default-select" > <select name="product_category"> <option value="1">Product Category</option> <option value="Home Decor">Home Decor</option> <option value="Paintings">Paintings</option> <option value="Jewellary">Jewellary</option> </select> </div> </div> <div class="mt-10"> <div class="form-select" id="default-select2" > <select name="product_sub_category"> <option value="1">Product Sub-Category</option> <option value="Wall-Hangings">Wall-Hangings</option> <option value="Flower-Vases">Flower-Vases</option> <option value="Oil-Paintings">Oil-Paintings</option> <option value="Glass-Paintings">Glass-Paintings</option> <option value="Earrings">Earrings</option> <option value="Necklaces">Necklaces</option> </select> </div> </div> <div class="mt-10"> <input type="text" name="product_name" placeholder="Product Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Product Name'" required class="single-input"> </div> <div class="mt-10"> <textarea class="single-textarea" name="product_description" placeholder="Product Description" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Product Description'" required></textarea> </div> <div class="mt-10"> <input type="file" name="product_image" placeholder="Product Image" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Product Image'" required class="single-input"> </div> <div class="mt-10"> <input type="text" name="product_price" placeholder="Product Price" …