Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Not being able to merge front end to backend
Im learning programming and im completely new in it..i was working on a project and i have used django for back-end. Now the problem im currenctly facing is that i got no idea how should i link frontend and backend ?.. first we created backend (where there is login/signup/and dashboard) using django and boostrap,js .. and the backend work perfectly so below the folder structure of the backend we are working on. so this is the structure of the backend .. to be more clear check 2nd image. Here you can see that, budgetwebsite folder which is just below the folder authentication. budgetwebsite is our main thing or a part of our system.. then we did django startapp for authentication(for username validation and email) then we did django startapp for userincome(here we worked on userincome like add/delete income) then we did django startapp for expenses(here we worked on expenses like add/delete/expense) and that userpreference is our admin panel. thats for the backend section Now lets move on the front end section aswell. then we created a different folder name front end and we started working on it. So now lets move to the problem... i just want to merge this … -
How to display changed fields in Django Admin?
I have a model Managers and a proxy model MyManagers. A am trying to display changed field in Admin panel for proxy model, but Admin/history display only user, date and action. How to fix it? My models.py from django.db import models from django.contrib import admin from simple_history.models import HistoricalRecords class Managers(models.Model): name = models.CharField(max_length=30, default='') lastname = models.CharField(max_length=30, default='') enduser_id = models.CharField(max_length=8, default='', help_text=u"Please enter the end user id, like ABC1WZ1") history = HistoricalRecords() class Meta: verbose_name = 'Manager' verbose_name_plural = 'Managers' def __str__(self): return self.name + self.lastname class ManagersAdmin(admin.ModelAdmin): list_display= ('name','lastname','enduser_id') class MyManagers(Managers): class Meta: proxy=True def __str__(self): return self.name.upper() +' '+self.lastname.upper() class MyManagersAdmin(admin.ModelAdmin): search_fields = ['name', 'lastname','enduser_id'] list_display = ('name', 'lastname','enduser_id') history_list_display = ['name','lastname','enduser_id','changed_fields'] def changed_fields(self, obj): if obj.prev_record: var = obj.diff_against(obj.prev_record) return var.changed_fields return None My admin.py: from django.contrib import admin from .models import * # Additional board for assigning a manager to a Department. admin.site.register(Managers, ManagersAdmin) admin.site.register(MyManagers, MyManagersAdmin) -
Django Multi table inheritance serializer display
I have extended my model like this. class Item(models.Model): name = models.CharField(max_length=50) class Category1(Item): code = models.CharField(max_length=50) class Category2(Item): status = models.IntegerField(default=1) class Order(models.Model): # fields class OrderItem(models.Model): order = models.ForeignKey("Order", on_delete=models.PROTECT, related_name="order_items") item = models.ForeignKey("Item", on_delete=models.PROTECT) Is there any way to access the child fields from the parent model? From the serializer, I have to display all the details from the Order model. Order -> OrderItem -> Item I was able to display up to the Item details, but I have to display the other fields from Category1 and Category2. Is there any way I can execute this? My serializer is like this class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = "__all__" class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) class Meta: model = Order fields = "__all__" -
how to design blog commenting system with django orm?
im new to django and im wondering how can i design a nested commenting system for my blog project ? class Post(models.Model): title = models.CharField(max_length=20) paragraph = models.TextField() sources = models.CharField(max_length=100) author = models.CharField(max_length=50) likes = models.PositiveIntegerField(default=0) def __str__(self): return f'||{self.title}|| from -> {self.author}' class Comment(models.Model): name = models.CharField(max_length=20) mail = models.EmailField() content = models.CharField(max_length=250) post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True, blank=True) reply = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return f'{self.name} said --> {self.content}' i tried this for models and, it doesnt seem to work for nested comments. -
Application error in heroku when django is deployed
I am trying to deploy a Django project to Heroku and for some reason it gives me an 'Application Error'. When I look at the logs, I get this: 2022-01-30T12:44:14.000000+00:00 app[api]: Build succeeded 2022-01-30T12:44:21.330403+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=lms-mkc.herokuapp.com request_id=44f703bc-3648-49a3-a440-d421a3e8d742 fwd="196.189.238.73" dyno= connect= service= status=503 bytes= protocol=https 2022-01-30T12:44:21.808170+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=lms-mkc.herokuapp.com request_id=a2c0669b-650d-4188-84b3-92d3ba425942 fwd="196.189.238.73" dyno= connect= service= status=503 bytes= protocol=http -
i facing kernel issue in my jupyter notebook from anacoda
Traceback (most recent call last): File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\web.py", line 1704, in _execute result = await result File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\handlers.py", line 74, in post model = yield maybe_future( File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 98, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 110, in start_kernel_for_session kernel_id = yield maybe_future( File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 176, in start_kernel kernel_id = await maybe_future(self.pinned_superclass.start_kernel(self, **kwargs)) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\multikernelmanager.py", line 186, in start_kernel km.start_kernel(**kwargs) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\manager.py", line 337, in start_kernel kernel_cmd, kw = self.pre_start_kernel(**kw) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\manager.py", line 286, in pre_start_kernel self.write_connection_file() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\connect.py", line 466, in write_connection_file self.connection_file, cfg = write_connection_file(self.connection_file, File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\connect.py", line 136, in write_connection_file with secure_write(fname) as f: File "C:\ProgramData\Anaconda3\lib\contextlib.py", line 119, in enter return next(self.gen) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_core\paths.py", line 461, in secure_write win32_restrict_file_to_user(fname) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_core\paths.py", line 387, in win32_restrict_file_to_user import win32api ImportError: DLL load failed while importing win32api: The specified procedure … -
model only shows up in admin if foreign key to superuser
In the django admin I have a model "profile" that has a foreign key to user. If I make a new instance of the profile model it shows up in the admin only if the user it's attached to a user who has superuser status. I would like to have them all show up in the admin. Where would I start looking to find the permissions for "profile"'s admin page. To my knowledge my query set is set to Profile.objects.all() So what else should I be looking for? views.py is as follows class ProfileViewSet( RetrieveModelMixin, ListModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet, ): """ API endpoint that allows users to be viewed or edited. """ queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [permissions.IsAuthenticated] lookup_field = "user__username" admin.py just has fieldsets definitions. serializer.py has fields definitions. -
How to create a django model with static image file
enter code here class EncryptedMessage(models.Model): image = models.ImageField(upload_to="images", blank=True) def __str__(self): return 'image: {}'.format(self.image) This is my django model, I need to create an object with static image file. class EncryptedMessage(models.Model): image = models.ImageField(upload_to="images", blank=True) def __str__(self): return 'image: {}'.format(self.image) -
How to specify that class C would be used inherited by classes that also inherit from class A
I'm trying to create a utility class UploadFile that would be used by subclasses of ModelAdmin. I can just create a vanilla class and it would be all fine and dandy. However, is there a way to tell static analyzers and code completion tools that this utility class will have access to properties of ModelAdmin, without UploadFile inheriting from ModelAdmin? Inheriting from ModelAdmin gives the error: TypeError: Cannot create a consistent method resolution order (MRO) for bases ModelAdmin, UploadFile Example code: class ModelAdmin(...): def send_message(...): pass class UploadFile: def upload(self): self.send_message() class MyModelAdmin(ModelAdmin, UploadFile): pass Moving ModelAdmin inheritance from MyModelAdmin to FileUpload would prevent MyModelAdmin from creating other utility classes that would also access ModelAdmin properties and methods. -
Django - Different behavior between DEV and PROD
I'm finalizing my first own Django app and I have some strange issues, as the behavior on my server is different than in my local Dev environment. My main issue is about a page displaying 2 multiple select boxes, and buttons dedicated to move items from one to the other thanks to Javascript functions: it works in DEV but not in Prod. On top of that, the display is also different, and looks weird on the Prod server. The page is dedicated to list users and add them to a group. The icons intend to move one / all user(s) from the list to the group, and vice versa. It works perfectly in DEV but not at all in PROD. I start with the JS code related to the buttons (I also consider a double click on a single item to move it from one group to the other and it doesn't work either, so it's included hereafter): // Add all (from source to destination) $('#add_all').on("click", function(e) { e.preventDefault(); $('#id_users').find('option').removeAttr('selected'); $('#id_all_users option').each(function() { add_option('#id_all_users', '#id_users', $(this)); $('#id_users_in_group').val($('#id_users_in_group').val() + "-" + String($(this).val())) }) }) // Add selected (from source to destination) $('#add_selected').on("click", function(e) { e.preventDefault(); $('#id_users').find('option').removeAttr('selected'); let values = $('#id_all_users').val(); $('#id_all_users … -
Django request.session not working properly
i am creating a web app and i'm using ajax to send the data from frontend to backend so i can process the forms and save them to the database. I send the data from ajax to a get-data method and from there i save it to the session, and when i access the /success page and try to get the same data from session, it tells me that the key doesn't exist. How is that possible? Here is the code down below. $.ajax({ type: "POST", url: "/get-data/", data: JSON.stringify(obj), dataType: "text", headers: { "X-CSRFToken": getCookie("csrftoken") }, success: function (response) { console.log("success"); // i get this, so i it means that the ajax works properly. }, error: function (response, err, err2) { console.log(err2); }, }); def get_data(request): if request.method == "POST": if is_ajax(request): rec_data = json.loads(request.body) print("the request came") request.session["data_check_form"] = rec_data print("everything set") print(request.session["data_check_form"]) # i print this and i get the json file properly return JsonResponse({"success": "200"}) def success_view(request): print("test") data = request.session.get("data_check_form", False) print(data) # i get false ... -
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: django aws
When trying to get data from the database I receive the below error: 2022-01-30 11:47:05,004 ERROR Exception inside application: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above error occurs only in production. I have an external database in RDS (amazonAWS) and I am not sure why it's still trying to make a connection to "/var/run/postgresql/.s.PGSQL.5432". Here is my database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': os.getenv('RDS_USER'), 'PASSWORD': os.getenv('RDS_PASSWORD'), 'HOST': os.getenv('RDS_HOST'), 'PORT': '5432' } I am using the below snippet which authenticates users using token authentication in channels: from urllib.parse import parse_qs from channels.auth … -
Why does docker build constantly fail?
I'm trying to use Docker for the first time for my Django project using the book "Django For Professionals", but I am keep on getting build errors when I type "Docker build ." for a few days. I have looked at other stack overflow posts(An error, "failed to solve with frontend dockerfile.v0") but it still does not work. Here is the error code that I get. yoonjaeseo@Yoons-MacBook-Pro hello % docker build . [+] Building 0.1s (2/2) FINISHED => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 419B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s failed to solve with frontend dockerfile.v0: failed to create LLB definition: file with no instructions yoonjaeseo@Yoons-MacBook-Pro hello % export DOCKER_BUILDKIT=0 export COMPOSE_DOCKER_CLI_BUILD=0 yoonjaeseo@Yoons-MacBook-Pro hello % docker build . Sending build context to Docker daemon 179.2kB Error response from daemon: failed to parse Dockerfile: file with no instructions I have my Dockerfile within my Django project and it is as follows: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ Please let me know if any additional information is needed. Thank you! -
A question app that the user must give coins to ask a question and the answerer will get the coins
enter code hereI am creating a kind of a question and answer web application. I want the user asking the question to compulsorily give coins. The choices are already there. Then the user that answers the question gets the coins given by the other user. I am using Django signals, but the user that ask the question got hienter image description heres coins deducted but the answerer didn't get any coin it is given me an error. This is the model for the question and answer . I already have the user model with the user default coin as 5000 class Question(models.Model): COINS_CHOICES = ( (10, 10), (20, 20), (30, 30), (40, 40), (50, 50), (60, 60), (70, 70), (80, 80), (90, 90), (100, 100), ) label = models.CharField(max_length=5000) image = models.ImageField() #slug = models.SlugField() timestamp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now_add=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) coins_given = models.PositiveSmallIntegerField(choices=COINS_CHOICES, blank=False, null=True) def __str__(self): return self.label class Answer(models.Model): label = models.CharField(max_length=5000) image = models.ImageField() timestamp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) clap = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="answers") def __str__(self): return self.label def number_of_clap(self): return self.clap.count() class Comment(models.Model): text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) … -
Running a for loop inside html file for specific time in django
I want a for loop to run 2/3 times for this specific model. Lets assume I have 10 data, I want the first 3 one to be shown inside html file through a for loop. Can anyone help me with this one? This is the models.py class CompanyInformation(models.Model): name = models.CharField(max_length=50) details = models.TextField(max_length=50) website = models.CharField(max_length=50, null=True, blank=True) social_fb = models.CharField(max_length=50, null=True, blank=True) social_ig = models.CharField(max_length=50, null=True, blank=True) social_twitter = models.CharField(max_length=50, null=True, blank=True) social_youtube = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name views.py file from django.shortcuts import render from .models import * # Create your views here. def aboutpage(request): aboutinfo = CompanyInformation.objects.all()[0] context={ 'aboutinfo' : aboutinfo, } return render(request, 'aboutpage.html', context) inside the html file {% block body_block %} <p class="redtext">{{ aboutinfo.name }}</p> <p class="redtext">{{ aboutinfo.details }}</p> <p class="redtext">{{ aboutinfo.website }}</p> {% endblock body_block %} -
Django ; How i can migrate a project done with the sqlite3 to postgresql
From days my friend has worked in the OS:windows and he did a part of the django application using the database :sqlite3 , he give me a backup of his work to complete my part , on the backup i have found a database named databaseproject.db, My question here that am using Linux as an OS and postgresql , How I can migrate this database databaseproject.db(it's an sqlite3 database ) to postgresql. Ps: when i have tried do the command below on the directory(after copied the project in a virtual environement on my linux): python manage.py dumpdata --natural-foreign \ --exclude=auth.permission --exclude=contenttypes \ --indent=4 > data.json ----> command go without errors, Here i have found the data.json contain an empty list.. So i want to know , How i can correctly migrate from sqlite3 to postgresql.? Thanks in advance. -
Django models not being saved to database when updated using Celery and when deployed to Heroku
So the title is a bit long winded but i think explains my issue pretty well. I have a Django project that updates models every 60 seconds by scraping currency data from another website using Celery and RabbitMQ. When i run the celery worker locally it works perfectly, however when i deploy to Heroku the models do not update. When i check the logs (heroku logs --tail) It shows that the tasks are running but they aren't updating the database models. I beleive this must be due to some configuration error in my settings.py file but i have tried numerous solutions and nothing has worked. I have also tried changing to use Redis instead and have experienced the same problem (it runs fine in the logs but does not actually update the database). Here is what i believe to be the relevant code that could be causing the problem. Settings.py (when using rabbitMQ): CELERY_BROKER_URL = 'rabbitMQ_url_given_from_heroku' BROKER_URL = os.environ.get("CELERY_BROKER_URL", "django://") BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = None CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ["json", "msgpack"] Settings.py (when using Redis): CELERY_BROKER_URL = 'Redis_url_given_from_heroku' CELERRY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' celery.py import os from celery … -
I'm trying to read CVS file in Django
I'm new to Django trying to read data from CSV file and display data in form of a table using Django templates. Please help me with how I can do it. -
Prefetch doesn’t sim
My queryset is product = Prosucts.objects.all().prefetch_related(Prefetch(‘prod_sale’, Sales.objects.filter(type__in=(1,2)).annotate(quantity_sold=Sum(‘quantuty’)), to_attr=‘prod_sold’)) So if I have product juice=3, apple =6, apple=4 My queryset gives me juice = 3, apple = 6 , 4 I can’t get Apple to be 10 -
Python manage.py command showing ImportError
When hit the command python manage.py makemigrations i get the immport error the error is like this ImportError : Module 'Backend.apps'does not contain a 'BackendConfigrest_framework'class. Choices are : 'BackendConfig' -
Filtering by Foreign Key in ViewSet, django-rest-framework
I want my api to return certain objects from a database based on the foreign key retrieved from the url path. If my url looks like api/get-club-players/1 I want every player object with matching club id (in this case club.id == 1). I'm pasting my code down below: models.py class Club(models.Model): name = models.CharField(max_length=25) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=30) club = models.ForeignKey(Club, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.name serialziers.py class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = 'id', 'owner', 'name' class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = 'id', 'name', 'offense', 'defence', 'club', 'position' views.py, This is the part where I get the most trouble with: class ClubViewSet(viewsets.ModelViewSet): queryset = Club.objects.all() serializer_class = ClubSerializer class PlayerViewSet(viewsets.ModelViewSet): queryset = Player.objects.all() serializer_class = PlayerSerializer class GetClubPlayersViewSet(viewsets.ViewSet): def list(self, request): queryset = Player.objects.all() serializer = PlayerSerializer(queryset, many=True) def retrieve(self,request, clubId): players = Player.objects.filter(club=clubId, many=True) if not players: return JsonResponse({'error': "No query found!"}) else: serializer = PlayerSerializer(players) return Response(serializer.data) urls.py from rest_framework import routers from django.urls import path, include from .views import (GameViewSet, PlayerViewSet, ClubViewSet, GetClubPlayersViewSet, create_club, set_roster) router = routers.DefaultRouter() router.register(r'clubs', ClubViewSet, basename="clubs") router.register(r'players', PlayerViewSet, basename="players") router.register(r'get-club-players', GetClubPlayersViewSet, basename="club-players") urlpatterns = … -
Django error with views for form display and save
I have a víews to display and save a form as below: @login_required(login_url='/login') # Check login def addlisting(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = ProductForm() return render(request, 'listing/addlisting.html', { 'form': form }) But When I load the html file I got this error ValueError at /addlisting The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/addlisting Django Version: 3.2.3 Exception Type: ValueError Exception Value: The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\lib\site-packages\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\bookapp', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\Scripts\\python38.zip', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\DLLs', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\lib', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\lib\\site-packages'] Server time: Sun, 30 Jan 2022 07:41:40 +0000 Please take a look. Thanks in advance !!!!!!!!!!!!!!!!!!!! -
How to work with nested if else in django templates?
Here, In this project I'm building a Ecommerce website and I'm using Django here. So, here I want to show that if there is no product of category Electric "Sorry, No Product is Available Right Now !!!" will be shown. where n is the number of product which is sent to this template from app views. But I'm not getting "Sorry, No Product is Available Right Now !!!" as I've no product of Electric category in my database. How to fix this? where I'm doing wrong? views.py def electric(request): product = Product.objects.all() n = len(product) params = {'product': product, 'range':range(1,n), 'n':n} return render(request,'electric.html',params) electric.html {% if n is 0 %} <div class="p-3 mb-1 bg-warning text-white text-center my-0"> <h1><b>Sorry, No Product is Available Right Now !!! </b></h1> </div> {% else %} <div class="album py-2 bg-gradient"> <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for i in product %} {% if i.category == "Electric" %} <div class="col"> <div class="card shadow-sm"> <img src="{{i.image}}" /> <div class="card-body"> <h4 class="card-title">{{ i.product_name}}</h4> <h6 class="card-subtitle mb-2 text-muted"> Category: {{i.category}} </h6> <p class="card-text">{{i.description}}</p> <div class="buy d-flex justify-content-between align-items-center"> <div class="price text-success"> <h5 class="mt-4">Price: {{i.price}} BDT</h5> </div> <a href="#" class="btn btn-danger mt-3"><i class="fas fa-shopping-cart"></i> Add to Cart</a> </div> … -
how to check is staff is True before login into dashboard which i have created by myself in Django?
I have created a dashboard and in my dashboard superuser creates the username, password, and all this thing but in my dashboard, I want to check first the username is staff or not before login into the dashboard. how to do that? can anyone help me from django.shortcuts import redirect, render from django.contrib import auth, messages from orderkitchen.models import kitchenData from django.contrib.auth.models import User def login_dashboard(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username, password = password) if user is not None: auth.login(request,user) messages.success(request, 'You are Logged in') return redirect('dashboard') else: messages.error(request,'Your Username or Password is incorrect') return redirect('login_dashboard') return else: return render(request,'accounts/dashboard_login.html') def dashboard(request): return render(request, 'accounts/dashboard.html') only the staff status is True then only then can logged in -
How i can to delete record when import file using django-import-export?
My project use Django framework and installed django-import-export plugin. I can import and export everything normally. But when i imported file to database. All new records from file upload was imported successfully. but old record that is not in the new records not delete. old data in database ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 110 3 , Mr.C , 150 new file upload ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 4 , Mr.D , 130 the result when imported ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 3 , Mr.C , 150 # < this not delete 4 , Mr.D , 130 I want it to be like this in database. ---------- ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 4 , Mr.D , 130 How i can to delete old record when imported using django-import-export plugins?