Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Taggit adding a list of tags to tag field by post save method
i am using Django Taggit 3.0.0 with python 3.10.5 and django 4.0.6 adding a list of tags to tag field by post save method i tried below codes which works well no error at all but the tags list is not assigned to the resource ragfield but it is getting listed in admin pannel tags model table. and i also want to add initial tags to each tagfield Model class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="") Tags = TaggableManager() def tag_set(sender, instance,*arg, **kwargs): ans= array_tag(instance) # print(ans) mylist = ["firmware", "download", "gsm"] instance.title='check' instance.Tags.add(*ans) post_save.connect(tag_set, sender=resource) def array_tag(instance): return [instance.title ,instance.desc,instance.size, instance.Brand.title ,instance.Model.title ,instance.Categories.title] -
Run pytest test case in thread isolation
I want to test a function wich uses thread_local variable i.e. threading.local().setattr() and threading.local().getattr() When I run my single test case it passes since it is only test using the thread but when I run pytest in the project which runs all tests in the project, it looks like other test cases are reusing the same thread and my thread_local variable is getting overwritten, Is there a simple way to keep my test case independent from other tests, either by running in a separate thread or locking thread while this test is running(less preferable solution, in this case, I'd rather delete this test case) -
Convert Image file to Base64 and store in database using django rest framework
I am trying to upload an image file and to save it as base64 in PostgreSQL using Django Rest Framework. My files are as follows: **Models.py:** from django.db import models import base64 class MyImageModel(models.Model): image_file = models.ImageField( upload_to="photos/", max_length=6000, null = True) def save(self, *args, **kwargs): if self.image_file: file = str(self.image_file) image = open(file, 'rb') image_read = image.read() self.image_64_encode = base64.encodebytes(image_read) print('This is the image in base64: ' + str(self.image_64_encode)) super(MyImageModel, self).save(*args, **kwargs) **serializers.py:** from django.forms import ImageField from drf_extra_fields.fields import Base64ImageField from .models import * from rest_framework import serializers class MyImageModelSerializer(serializers.ModelSerializer): image_file = serializers.ImageField class Meta: model = MyImageModel fields = ('image_file',) **Views.py:** from .models import * from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response import base64 from imagebase64app.serializers import MyImageModelSerializer # Create your views here. class AddImageView(APIView): def post(self, request, format=None): serializer = MyImageModelSerializer(data = request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response({'message':'Registered Successfully!'},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to set current active user as author field to the Article model?
I have many users who can add articles from Django Admin Panel. I want the author field must be assigned to the user who is currently login. I know we can achieve it through request.user. I want to achieve the same in the Article model's save() method. class Article(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def save(self, *args, **kwargs): self.author = ? super(Article, self).save(*args, **kwargs) -
How to enable and configure https and get a ssl/tls certificate for a nginx/docker-compose/django site, for a .dev domain
I'd like to set up a ssl/tls certificate so that I can navigate to my site through the .dev domain I have. I don't really know the best direction to head in to enable https for my .dev domain (https://en.wikipedia.org/wiki/.dev). I figured out http won't work because .dev domains are preloaded on a http strict transport security (hsts) list (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security). I was thinking of going through this tutorial (https://testdriven.io/blog/django-lets-encrypt/) but I don't know if there are easier ways since my project is set up a little differently and I'm not sure what all I'd have to change to make it work. I can currently reach my site through its ipv4 public address but ipv6 is enabled. My domain is through google domains and as far as I can tell the custom records are correct, I just need the certificate working. What should I do/change to enable https? It's a Django/Wagtail site with 3 containers: nginx, web, and db. /app/docker-compose.prod.yml: version: "3.7" services: nginx: build: context: . dockerfile: ./compose/production/nginx/Dockerfile volumes: - staticfiles:/app/static - mediafiles:/app/media ports: - 80:80 - 443:443 depends_on: - web web: build: context: . dockerfile: ./compose/production/web/Dockerfile image: wagtail_bootstrap_blog_prod_web command: /start volumes: - staticfiles:/app/static - mediafiles:/app/media env_file: - ./.env/.prod depends_on: … -
Error while saving foreign key data in database using Django Model Form
I have two Models for my Project, 1. Category Model and 2. Course Model Course Model has a Foreign Key reference with my Category Model as shown below. class Category(models.Model): categoryname = models.CharField(max_length=200,null=True,blank=True, default="") class Courses(models.Model): coursename = models.CharField(max_length=200,null=True,blank=True, default="") course_category = models.ForeignKey(Category, related_name="courses", blank=True,null=True,on_delete=models.CASCADE) logo = models.ImageField(upload_to='courselogos', null=True, blank=True) Initially I was using HTML form and will be able to save the Course data under a Particular Category to the database as: def add_course(request): if request.method == 'POST': course_name = request.POST.get('coursname') categoryid = request.POST.get('category_id') category = Category.object.get(id=category_id) course_logo = request.FILES.get('logo') course = Courses(coursename=course_name, course_category=category, logo= course_logo) course.save() return redirect('/all_category') Later I decided to move on using Django Model forms and I tried to implement the code as follows class AddCourseForm(forms.ModelForm): class Meta: model = Courses fields = ('coursename', 'course_category', 'logo') widgets = { 'coursename' : forms.TextInput(attrs={'class':'form-control'}), } def __init__(self, *args, **kwargs): category_id = kwargs.pop('category_id',1) super(AddCourseForm, self).__init__(*args, **kwargs) self.fields['course_category']=forms.ModelChoiceField(widget=forms.TextInput(), queryset=Category.objects.filter(id=category_id)) Later in the view I have saved the data as def add_course(request): if request.method == 'POST': addcourse = AddCourseForm(request.POST, request.FILES) if addcourse.is_valid(): addcourse.save() return redirect('/all_category') On my HTML page I am passing the input to the 'course_category' inputfield as 1,2,3....etc as the category_id value I have rendered the field in … -
Import data from CSV file with many to many fields in Python
I would like to be able to import data into my database from a CSV file thanks to the Pandas library, I succeeded for some model data but when the model fields are in many to many I can't. Here is the model whose data I would like to import: class LnkPlantPlant(models.Model): class MAGNET_CHOICES(models.TextChoices): NONE = None IDEAL = 'ideal', GOOD = 'good', MEDIOCRE = 'mediocre', BAD = 'bad' custom_id = models.IntegerField(primary_key=True, unique=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant') plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated') link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True) description = RichTextField(max_length=255, blank=True, null=True) Here the model of the plant: class Plant(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name Here, is my function which allows to import data into the database but I would like to be able to import the name of the many to many fields of the plant and the plant_associated: class UploadLinkPlantData(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): LnkPlantPlant.objects.update_or_create( custom_id=row['Custom Id'], defaults={ "custom_id": row['Custom Id'], "plant": Plant.objects.get(name=row['Plant']), # doesn't work "plant_associated": Plant.objects.get(name=row['Plant associated']), # doesn't work "link": row['Link'], "description": row['Description'] }) return Response({"status": "Succès : plante(s) crée(s) ou mise(s) à … -
"detail": "Method \"POST\" not allowed." django rest framework
I am new to django so having issues with it. Post method is not allowed. I have shared below both views.py and urls.py. Please help me out with it. views.py from django.shortcuts import render from rest_framework import viewsets,generics from user.serializer import UserSerializer,RetailerSerializer,ProductSerializer,Order_ItemsSerializer,Payment_DetailsSerializer,Order_DetailsSerializer from user.models import User,Retailer,Product,Order_Items,Payment_Details,Order_Details from product.models import Cart,Shipping_Address,Track_Repairs,NFT_Details from product.serializer import CartSerializer,Shipping_AddressSerializer,Track_RepairsSerializer,NFT_DetailsSerializer class AddProduct(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class Product_List(viewsets.ModelViewSet): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer class Product_Detail(generics.RetrieveAPIView): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer urls.py from django.urls import path,include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'',views.Product_List) urlpatterns = [ path('product/',include(router.urls)), path('product/<int:pk>/',views.Product_Detail.as_view()), path("product/add/", views.AddProduct.as_view()), ] -
Hi,the submit in this project is not working,how to fix it?
When I click submit in the add tasks page,I get no response.The submit button is supposed to add tasks to the list in the tasks page.It does not show any errors and I'm not sure if its code is even running. this is the views.py code from django.shortcuts import render from django import forms from django.urls import reverse from django.http import HttpResponseRedirect # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label="New Task") # Add a new task: def index(request): # Check if there already exists a "tasks" key in our session if "tasks" not in request.session: # If not, create a new list request.session["tasks"] = [] return render(request, "tasks/index.html", { "tasks": request.session["tasks"] }) def add(request): # Check if method is POST if request.method == "POST": # Take in the data the user submitted and save it as form form = NewTaskForm(request.POST) # Check if form data is valid (server-side) if form.is_valid(): # Isolate the task from the 'cleaned' version of form data task = form.cleaned_data["task"] # Add the new task to our list of tasks request.session["tasks"] += [task] # Redirect user to list of tasks return HttpResponseRedirect(reverse("tasks:index")) else: # If the form is invalid, re-render the page with existing … -
Saved image cannot be displayed in Django filer
I'm having a problem viewing uploaded images in Django filer. The images can be uploaded without any problems and will also be saved in the specified folder. After that it will be shown as follows: Screenshot filer page When I then click on expand I get the following error: Screenshot Error My urls.py looks like this: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, re_path, path from django.views.i18n import JavaScriptCatalog from django.contrib.sitemaps.views import sitemap from cms.sitemaps import CMSSitemap from djangocms_blog.sitemaps import BlogSitemap urlpatterns = i18n_patterns( re_path(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) urlpatterns += staticfiles_urlpatterns() urlpatterns += i18n_patterns( re_path(r'^admin/', admin.site.urls), re_path(r'^', include('cms.urls')), re_path(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap, 'blog': BlogSitemap,}}), re_path(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), re_path(r'^filer/', include('filer.urls')), ) admin.site.enable_nav_sidebar = False I installed django-filer according to the documentation. But apparently it doesn't work. How can I solve this problem? -
Overwrite file if the name is same in Django
How do I overwrite the file if the name of the new file is similar to the one already uploaded. If I can take file.name and delete any file present with this name and then store this file that also works for any . Any method would work please help This is my view.py from django.shortcuts import render from django.views.generic import TemplateView from django.core.files.storage import FileSystemStorage from django.http import HttpResponse import requests from geopy.distance import geodesic as GD import pandas as pd from subprocess import run,PIPE from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) file = request.FILES['file'] fs = FileSystemStorage() fs.save(file.name, file) else: form = UploadFileForm() return render(request, 'upload.html', {'form':form}) -
Add unique_together validation check on internal attirbutes of JSONField
I am using following model. class MyProfile(models.Model): name = models.CharField(max_length=100, default=None) account_id = models.CharField(max_length=64, default=None) prof_config = JSONField(null=True, blank=True, default=None) result = JSONField(null=True, blank=True, default=None) class Meta(object): app_label = "app" verbose_name = "MyProfile" unique_together = [["account_id", "prof_config"]] Previously prof_config included: prof_config = {"username":"pranav","password":"123456"} But now I have changed it to : prof_config = {"username":"pranav","password":"123456","last_sync_time":null} And as I want unique_together validation only on account_id, username and password. For that I changed unique_together to: unique_together = [["account_id", "prof_config__username","prof_config__password"]] But it didn't work. It gave me following error (if last sync time is null for both profiles): "Error while creating My Profile, error:duplicate key value violates unique constraint \"app_myprofile_account_id_prof_config_b94a5cdc_uniq\"\nDETAIL: Key (account_id, prof_config)=(4, {\"password\": \"123456\", \"username\": \"pranav\", \"last_sync_time\": null}) already exists.\n", "causality": "", "opid": "fc3501fa", "opid_chain": "fc3501fa", "level": "ERROR"} I am getting this error even after I have added unique_together for account_id, username and password ([["account_id", "prof_config__username","prof_config__password"]]). But it's still taking whole prof_config. And If last sync time is different the profile is being created. So Is there any way to do this. -
How can I reduce the CPU usage Python?
Here's the situation: There's a django command below. And I want to constantly scan the table EntityLimitTask whose status is not handle and changed it's status to success after some work # command name is update_entity_info import logging from concurrent.futures import ThreadPoolExecutor from functools import partial from django.core.management.base import BaseCommand from django.db.transaction import atomic from django.conf import settings from policy_insight.models import EntityLimitTask from policy_insight.enums import PiTaskStatusEnum, EntityTypeEnum, AgentTypeEnum from user_account.models import KaOEEntityInfo from utils.common import GetOeTokens logger = logging.getLogger('pi') logger.setLevel("ERROR") class Command(BaseCommand): help = 'entity limit info' def add_arguments(self, parser): ... def handle(self, *args, **options): import django.db django.db.close_old_connections() entity_limit_tasks = EntityLimitTask.objects.filter(handle_status=PiTaskStatusEnum.NOT_HANDLE, is_deleted=0) with ThreadPoolExecutor(max_workers=10) as e: e.map(partial(self._update_entity_limit_info, madhouse_token, bv_token), entity_limit_tasks) @staticmethod def _update_entity_limit_info(madhouse_token, bv_token, task): try: # do something task.handle_status = PiTaskStatusEnum.SUCCESS task.save() except Exception: import traceback as tb logger.error("[update_entity_limit] with error: {}".format(tb.format_exc())) Then I write a infinite loop in a shell file like : # update_entity_info.sh source /path/to/bin/activate while true do python /path/to/manage.py update_entity_limit --pythonpath /path/to/conf --settings settings done But when start it I found my CPU usage is very high top PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 21297 user 20 0 984.5m 50.4m 11.6m R 191.3 0.1 0:02.35 python /path/to/manage.py update_entity_limit --pythonpath … -
TypeError at /productdetails/20 'Products' object is not iterable
I am doing CRUD using serializers and I am trying to make a page which will display the details of the clothes that I have clicked on. The below error is coming below is the productdetails function def productdetails(request,id): prod = Products.objects.get(id=id) product = POLLSerializer(prod,many=True) return render(request,'polls/productdetails.html',{'data':product.data}) model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is productdetails.html ,since I need details of only 1 product,there is no need for loops hence I didnt add for loop <table> <tbody> <tr> <td>{{data.id}}</td> <td>{{data.title}}</td> <td>{{data.price}}</td> <td>{{data.sku_number}}</td> <td>{{data.product_details}}</td> <td>{{data.size}}</td> <td>{{data.quantity}}</td> <td>{{data.image}}</td> </tr> </tbody> </table> help is greatly appreciated,thanks! -
DRF update model with many-to-many field
I have two models with many-to-many relationship and I also have nested routers between them. When I'm trying to create a tag at the endpoint api/page//tags/, tag is created in the database for tags, but nothing happend in my table for many to many relationship. How can I fix it? Models look like this. models.py class Tag(models.Model): title = models.CharField(max_length=30, unique=True) class Page(models.Model): ... tags = models.ManyToManyField(Tag, related_name='pages') My serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class PageSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Page fields = ['id', 'title', 'uuid', 'description', 'owner', 'is_private', 'tags'] views.py class PageViewSet(viewsets.ModelViewSet): queryset = Page.objects.all() serializer_class = PageSerializer def perform_update(self, serializer): serializer.save(owner=self.request.user, tags=serializer) class TagViewSet(viewsets.ModelViewSet): serializer_class = TagSerializer queryset = Tag.objects.all() class NestedTagViewSet(CreateModelMixin, ListModelMixin, GenericViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer permission_classes = (IsAuthenticatedOrReadOnly,) def get_page(self, request, page_pk=None): page = get_object_or_404(Page.objects.all(), pk=page_pk) self.check_object_permissions(self.request, page) return page def create(self, request, *args, **kwargs): self.get_page(request, page_pk=kwargs['page_pk']) return super().create(request, *args, **kwargs) def get_queryset(self): return Tag.objects.filter(pages=self.kwargs['page_pk']) def list(self, request, *args, **kwargs): self.get_page(request, page_pk=kwargs['page_pk']) return super().list(request, *args, **kwargs) -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed
I'm creating app with authentication. My project is dockerized. When I run the server everything works fine, except authentication.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. But when I want to run docker-compose exec web python3 manage.py makemigrations or docker-compose exec web python3 manage.py migrate I get an error: File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/init.py", line 176, in get_user_model raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed I've thought it points to settings.py field AUTH_USER_MODEL, but I haven't got it. My views.py: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST} email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') if len(password) < 6: messages.add_message(request, messages.ERROR, 'Password should be at least 6 characters') context['has_error'] = True if not validate_email(email): messages.add_message(request, messages.ERROR, 'Enter a valid email address') context['has_error'] = True if not username: messages.add_message(request, messages.ERROR, 'Username is required') context['has_error'] = True if models.User.objects.filter(username=username).exists(): messages.add_message(request, messages.ERROR, 'Username is taken, choose another one') context['has_error'] = True return render(request, 'authentication/signup.html', context) # status=409 if models.User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Email is taken, choose another one') context['has_error'] = True return render(request, 'authentication/signup.html', context) # status=409 if context['has_error']: return render(request, 'authentication/signup.html', context) user = models.User.objects.create_user(username=username, email=email) … -
django import error in django-import-export
I am using django-import-export. I am getting errors in importing data to a database with foreignkey value. class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand__title','Cat')` Here Brand is used as foreign-key and I get the title by using Brand__title . It works perfectly for exporting but when importing it through an error for foreignkey is null. Line number: 1 - null value in column "Brand_id" of relation "firmApp_model" violates not-null constraint DETAIL: Failing row contains (6, f16, sd, images/sample_3pahsfV.jfif, gf, kjkj, null). None, f16, sd, images/sample_3pahsfV.jfif, gf, 1, kjkj, 1 -
Error when changing sqlite to postgresql while making an app with django
I got an error when I changed sqlite to postgresql while making an app with django. Shows the error that occurred. conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'POST': '5432' } } -
How to Hydrate dehydrated data and import to DB
Hi all i tried to export data from django postgresql and was facing issue of resolving the foreign key id to name/title which was resolved by below method and the data was extracted successfully. class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) now i want to import/upload the data back to database by using the same exported xls without inserting the ID of foreign key and inserting the name of foreign key. need guide to hydrate the data back. i also tried with below hydrate method def hydrate_Brand(self, obj): return str(obj.Brand.title) def hydrate not showing any error but the data is also not imported to database. -
Unable to list locks using list_at_resource_level in azure
compute_client = authenticate.client_management(subscription_id) for resource_group in resources_groups.keys(): vm_list = compute_client.virtual_machines.list(resource_group) for vm in vm_list: array = vm.id.split("/") locks_client = authenticate.locks_client(subscription_id) result = locks_client.management_locks.list_at_resource_level(resource_group, "Microsoft.Compute", "/subscriptions/XXXXXX/resourceGroups/YYYY", "Microsoft.Compute/virtualMachines", array[-1]) Using the following class for locks :: /usr/local/lib/python3.8/dist-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_management_locks_operations.py The result of the above program is :: azure.core.exceptions.ResourceNotFoundError: (InvalidResourceType) The resource type could not be found in the namespace 'Microsoft.Compute' for api version '2016-09-01'. Code: InvalidResourceType Can someone please help me fix this. Thanks. -
How can i use Django template and jinja2 together? Such that i can use both in my project
I want to use both jinja and Django templates together, such that it does not show error of templatenotfound. When I try to use jinja as well, Django does not view the jinja templates but only Django templates, but when I omit the Django templates configuration, jinja works fine. I want to use both. TEMPLATES = [ # trying out jinja { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(MAIN_DIR, 'templates_jinja')], 'APP_DIRS': True, 'OPTIONS': {'environment': 'newquiz.jinja2.environment'} }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates_django')], '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', # for redirecting to previous page after login # imp 'material.context_processors.footer_processor', 'aboutus.context_processors.about_processor', 'quiz.context_processors.material_processor', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] -
Cannot show image and css styling while sending html template with dj_rest_auth
Hy there, I have follow each and every step to send html template while registering user with dj_rest_auth. email is successfully send but image and css styling is shown in email. in urls.py path("auth/registration/", include("dj_rest_auth.registration.urls")), File structure appname templates account email email_confirmation_signup_message.html -
django custome login redirection middleware redirection problem says ERR_TOO_MANY_REDIRECTS
hi friends i need some help i want to redirect a user when he try to access a page in my django settings.py is MIDDLEWARE = ['cart.middleware.LoginRedirectMiddleware'] url.py is (home is the app name) path('',views.login,name="login"), path('home',views.home,name="home"), middleware.py is (located in mainapp) def process_view(self, request, view_func, view_args, view_kwargs): """ Called just before Django calls the view. """ print("executed") if (request.user.is_authenticated): return redirect('home') else: return redirect('login') -
Individual product details viewing
I am making a CRUD of products and one of my tasks is to have a page that would display the details of the product when clicked. I have seen various websites on how to make a product details page including from stackoverflow but without any success.I am also getting the below error despite writing the names of the functions correctly this is despite writing the name 'productdetails' in the urls.py below urlpatterns=[ path('',views.showAdminPage,name="showadmin"), path('products/<int:id>/',views.productdetails, name='productdetails'), path('show/',views.show,name="show"), path('insert/',views.insert,name="insert"), path('update/<int:id>/',views.update,name="update"), path('delete/<int:id>/',views.delete,name="delete"), path('shoppingpage/',views.shoppingpage,name="shoppingpage"), path('allproducts/',views.allproducts,name="allproducts"), path('9-6wear/',views.ninesixwear,name="ninesixwear"), path('kurta/',views.kurta,name="kurta"), path('skirtset/',views.skirtset,name="skirtset"), path('dress/',views.dress,name="dress"), path('kurtaset/',views.kurtaset,name="kurtaset"), path('desiswag/',views.desiswag,name="desiswag"), path('sharara/',views.sharara,name="sharara"), path('plazzo/',views.plazzo,name="plazzo"), path('dhoti/',views.dhoti,name="dhoti"), path('anarkali/',views.anarkali,name="anarkali"), path('fusionwear/',views.fusionwear,name="fusionwear"), path('drapesaree/',views.drapesaree,name="drapesaree"), path('jumpsuits/',views.jumpsuits,name="jumpsuits"), path('croptopwithskirt/',views.croptopwithskirt,name="croptopwithskirt"), path('indowestern/',views.indowestern,name="indowestern"), path('lehenga/',views.lehenga,name="lehenga"), path('heavysuitset/',views.heavysuitset,name="heavysuitset"), path('gown/',views.gown,name="gown"), path('bridalwear/',views.bridalwear,name="bridalwear"), ] productdetails function in views.py def productdetails(request,id): product = Products.objects.get(id=id); context = {'data':product} return render(request,'polls/productdetails.html') model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is the productdetails.html page <table> {% for result in data %} <tbody> <tr> <td>{{result.id}}</td> <td>{{result.title}}</td> <td>{{result.price}}</td> <td>{{result.sku_number}}</td> <td>{{result.product_details}}</td> <td>{{result.size}}</td> <td>{{result.quantity}}</td> </tr> </tbody> </table> kurta.html where the error mentioned above is coming <ul class="row products columns-3" id="appendproducts"> {% for result in data %} <li class="product-item wow … -
Django: fields missing in the Queryset
I have this simple e-commerce project where I am trying to render ItemDetailView using slug, but object_list from Product views.py doesn't have them in the Queryset. I inspected the Queryset and I see many fields missing including Vendor.name Queryset: <QuerySet [{'id': 11, 'category_id': 1, 'vendor_id': None, 'title': 'sample - user1', 'slug': '', 'description': 'sample pic', 'price': Decimal('3.00'), 'date_added': datetime.datetime(2022, 7, 18, 2, 54, 48, 714506, tzinfo=), 'image': 'uploads/IMG-20191217-WA0021_qII27R4.jpg', 'thumbnail': 'uploads/uploads/IMG-20191217-WA0021_qII27R4.jpg'}]> Please help with this. Thanks in Advance #apps/vendor/models.py class Vendor(models.Model): name = models.CharField(max_length = 255) created_at = models.DateField(auto_now_add = True) created_by = models.OneToOneField(User, related_name = 'vendor', on_delete = models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name #apps/vendor/views.py class RegisterMember(CreateView): form_class = UserCreationForm success_url = reverse_lazy('core/frontpage') template_name = 'vendor/register_member.html' class LoginView(LoginRequiredMixin, ListView): model = Vendor template_name = 'vendor/registration/login.html' success_url = reverse_lazy('vendor/member_admin.html') class MemberAdminView(LoginRequiredMixin, ListView): model = Vendor template_name = 'vendor/member_admin.html' def get_context_data(self, **kwargs): context = super(MemberAdminView, self).get_context_data(**kwargs) context['products'] = Product.objects.all() return context class AddItemView(LoginRequiredMixin, CreateView): form_class = ProductForm template_name = 'vendor/add_item.html' success_url = reverse_lazy('vendor/member_admin.html') def form_valid(self, form): form.instance.created_by = self.request.user return super(AddItemView, self).form_valid(form) #apps/product/models.py class Category(models.Model): cat_title = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) ordering = models.IntegerField(default = 0) class Meta: ordering = ['ordering'] def __str__(self): return …