Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker-compose how to reference files in other directories
Having this dockerfile: FROM python:3.8.3-alpine ENV MICRO_SERVICE=/home/app/microservice # RUN addgroup -S $APP_USER && adduser -S $APP_USER -G $APP_USER # set work directory RUN mkdir -p $MICRO_SERVICE RUN mkdir -p $MICRO_SERVICE/static # where the code lives WORKDIR $MICRO_SERVICE # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk del build-deps \ && apk --no-cache add musl-dev linux-headers g++ # install dependencies RUN pip install --upgrade pip # copy project COPY . $MICRO_SERVICE RUN pip install -r requirements.txt COPY ./entrypoint.sh $MICRO_SERVICE CMD ["/bin/bash", "/home/app/microservice/entrypoint.sh"] and the following docker-compose.yml file: version: "3.7" services: nginx: build: ./nginx ports: - 1300:80 volumes: - static_volume:/home/app/microservice/static depends_on: - web restart: "on-failure" web: build: . #build the image for the web service from the dockerfile in parent directory command: sh -c "python manage.py collectstatic --no-input && gunicorn djsr.wsgi:application --bind 0.0.0.0:${APP_PORT}" volumes: - .:/microservice:rw # map data and files from parent directory in host to microservice directory in docker containe - static_volume:/home/app/microservice/static env_file: - .env image: wevbapp expose: - ${APP_PORT} restart: "on-failure" volumes: static_volume: I need to reference the following files (in … -
Websocket with Django channels drops connection with heroku,
im stck in here , i made a blog with a chat room , with django channels and its workin locally perfectly, but when i deploy it to heroku using daphne no message(chat) is showing this is the result og heroku logs --tail this is redis configuration in settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [(os.environ.get('REDIS_HOST', 'localhost'),6379)], }, }, } Procfile web: daphne elearnow.asgi:application --port $PORT --bind 0.0.0.0 -v2 please let me know if i need to add anything else, as i mentioned its stopped showing messages only in production , but locally with the same code everythin is fine i made sure Redis is working, and add "s" for my jquery so its secure "wss://" Thank you very much for your help -
Abstract model with dynamic fields
I am wondering since ages how to achieve the following: I have an abstract class wrapping several attributes shared by multiple models. But not every model needs every attribute in exactly the same way. Here is an example: MyModelA and MyModelB both have two fields: value_1 and value_2. But while MyModelA needs them to be required/not nullable, they can be nullable for MyModelB. class MyAbstractModel(models.Model): value_1 = models.IntegerField() value_2 = models.IntegerField() class Meta: abstract = True What I tried: Not deriving MyAbstractModel from models.Model but from object like a regular mixin Setting a class attribute which is overwritten in the child classes to determine the nullable-state. It always takes the definition from MyAbstractModel. Using a class attribute but not set it in the MyAbstractModel. Then the makemigrations command fails because of the undefined variable. Cry Being DRY is such an important paradigm in django, I really wonder that there is nothing on this topic in the internet. Thanks in advance! -
Django IntegrityError: null value in column "interestreceiver_id" of relation "HomeFeed_interest" violates not-null constraint
Django : Why is my submit interest form not submitted because of an integrity error issue? Did I write my view or template wrongly? How should I solve this error as i've never encountered before. i searched on this website and saw some profile examples but mine is blog post and i dont really understand how their change could solve the error.. I received the following integrity error: IntegrityError at /HomeFeed/submitinterest/slug-5 null value in column "interestreceiver_id" of relation "HomeFeed_interest" violates not-null constraint DETAIL: Failing row contains (17, 2021-01-06 10:54:25.489884+00, t, ddfe, efeffe, 5, documents/Discussion_between_joowon_and_SLDem_-_2021-01-05.pdf, 13, null, null, 1). views.py @login_required def submit_interest_view(request, slug): user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') interest_requests = Interest.objects.filter(interestsender=user, interestreceiver=blog_post.author, is_active=True) if interest_requests.exists(): return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use 'author = user.account' if there is OneToOne relation between user and account obj.author = author obj.blog_post = blog_post obj.save() messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest') … -
relation "app_model" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_model"
I'm using Django and created a new model after deploying my app to Heroku, I get this error when I try to access my app's admin page. -
Djongo Models - How to get rid of : Object of type AssertionError is not JSON serializable
I'm having a weird problem in my django Restfull Application ! i'm using Djongo as db engine (MongoDB) the problem seems to be happening in /usr/local/lib/python3.8/dist-packages/rest_framework/utils/encoders.py which sometimes say create() function returned null object or returned AssertionError as Object which is not Serializable at the end ! Model : class Product(models.Model): """ Product Model """ _id = models.ObjectIdField() name = models.CharField(max_length=MAX_PROD_NAME_LEN) sku = models.CharField(max_length=MAX_PROD_SKU_LEN , unique=True) category = models.CharField(max_length=MAX_PROD_CAT_LEN) desc = models.TextField(default="") agent_desc = models.TextField(default="") urls = models.JSONField(blank=True , null=True) productType = models.CharField(max_length=MAX_PROD_TYPE_LEN) variants = models.JSONField(default={ # "op1":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "op2":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "op3":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "quantity":models.IntegerField(default=1), # "price":models.DecimalField(max_digits=10, decimal_places=2), }) options = models.JSONField(default={}) accessories = models.JSONField(default={ # "name" : None, # "attachements":[], # "quant" : None, # "desc" : None }) created_at = models.DateTimeField(auto_now_add=True , null=False) updated_at = models.DateTimeField(auto_now=True, null=True) deleted_at = models.DateTimeField(default=None) is_deleted = models.BooleanField(default=False) objects = models.DjongoManager() # built-in Model's objects Alike ! def __str__(self): return self._id View : class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def list(self, request): queryset = Product.objects.all() serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): print(f"Retrieving infos of {pk}") queryset = Product.objects.all() oid = None try: oid = ObjectId(pk) except Exception: return Response("Product not found !") product = get_object_or_404(queryset, _id=oid) serializer = … -
Django date is not recognized in the view
The date is not recognized in the view . When I post, error came out like "please enter the date" There seems to be a problem with select name. Because of prefix. i need to use prefix because of multiple forms Is there a way to solve this? I need help . my models.py class Grade(models.Model): title = models.CharField(max_length=255, verbose_name='title') date = models.DateTimeField(default=datetime.now, verbose_name='date') ... my views.py class StudentDetail(DetailView): model = Student template_name = 'student/view.html' context_object_name = 'student' form_class = AddConsultation second_form_class = AddGrade def get_object(self, queryset=None): return get_object_or_404(Student, pk=self.kwargs['pk'], school_year=self.kwargs['school_year']) ... def post(self, request, *args, **kwargs): student = get_object_or_404(Student, pk=kwargs['pk']) consultation_form = self.form_class(request.POST, prefix='consultation') grade_form = self.second_form_class(request.POST, prefix='grade') if grade_form.is_valid(): grade = grade_form.save(commit=False) grade.created_to = student grade.created_by = request.user grade.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) my template ... <dl class=""> <dt>date</dt> <dd> <ul class="select-box thumb3"> <li> <select name="grade-date_year" class="member__select-btn"> {% for i in year %} <option value="{{i}}">{{i}}year</option> {% endfor %} </select> </li> <li> <select name="grade-date_month" class="member__select-btn"> {% for i in month %} <option value="{{i}}">{{i}}month</option> {% endfor %} </select> </li> <li> <select name="grade-date_day" class="member__select-btn"> {% for i in day %} <option value="{{i}}">{{i}}day</option> {% endfor %} </select> </li> </ul> </dd> </dl> ... -
How do I stream video using Node JS and Use it in my Django Project?
I am working on a Django project related to Video Streaming. All my basic functionalities(like Authentication, login, etc.) are being made using Django. Now I want to Stream Video on my Web App. I didn't find a solution to Stream my videos directly using Django. So, I decided to stream my video using Node.js and integrate this feature in my Django Project. Here is the Node-Express Code I used for Streaming my Videos in my frontend. app.get("/video", function (req, res) { const range = req.headers.range; if (!range) { res.status(400).send("Requires Range header"); } const videoPath = "mySample.mp4"; const videoSize = fs.statSync("mySample.mp4").size; const CHUNK_SIZE = 10 ** 6; // 1MB const start = Number(range.replace(/\D/g, "")); const end = Math.min(start + CHUNK_SIZE, videoSize - 1); const contentLength = end - start + 1; const headers = { "Content-Range": `bytes ${start}-${end}/${videoSize}`, "Accept-Ranges": "bytes", "Content-Length": contentLength, "Content-Type": "video/mp4", }; // HTTP Status 206 for Partial Content res.writeHead(206, headers); const videoStream = fs.createReadStream(videoPath, { start, end }); videoStream.pipe(res); }); If someone can tell me how can I integrate this with my Django Project. Thanks :) -
Page reload is not working with POST request on browser back and forward button
I am trying to reload a page on clicking the back or forward button or reload in the browser. Below are the usecases: 1.User enters details in signup form and submits -> the same page shows up with an OTP form. If this page is revisited using back, forward or reload button, it should be redirected to the first page with empty signup form. 2.User submits the cart form -> moves to checkout page and submits form -> moves to payment gateway. If the Checkout page is revisited using back, forward or reload button, it should be redirected to the cart page. Redirects are happening to Cart page if I copy paste the Checkout page to the browser, based on the type of request, GET or POST I want this similar to Instagram signup, where user fills the Signup form and goes to OTP form. If user reloads or revisits the OTP form, he is redirected to the original Signup form. Also the tab history stack only has one page for both Signup and OTP forms I tried using PerformanceNavigationTiming.type but it's not working. Below is the code. var perfEntries = performance.getEntriesByType("navigation"); if (perfEntries[0].type === "back_forward") { location.reload(true); } I … -
Django: 'python manage.py runserver' returns 'TypeError: object of type 'WindowsPath' has no len()'
I have created a new django proejct and the only modification I have made is to the settings, changing the database from sqlite to postgres: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'yachtdrop', 'USER': 'postgres', 'PASSWORD': 'passsword', 'HOST': '127.0.0.1', 'PORT': '5432', } } I am using pipenv to manage my virtual environment, my pipfile is as follows: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" requests = "*" flask = "*" psycopg2-binary = "*" [dev-packages] [requires] python_version = "3.9" When I write the command 'python manage.py runserver', the system returns 'TypeError: object of type 'WindowsPath' has no len()' and I don't understand why this is happening. I am running this on Windows. I have recently reset my Windows system and have a fresh installation of python, pipenv and postgres. It would be great if anyone could help me out here. Thanks! -
Get data user profile django rest
i want to get data user in profile . i do register login rest_framework_simplejwt I got the token.But it is not possible to get data this user. which URL to get data . token work. //simplejwt simplejwt Models class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=11) likecus=models.ManyToManyField(smartphone ,verbose_name="b") def __str__(self): return "User: {}, phone: {}".format(self.user, self.phone) url ??here correct ????? path('customers/<int:id>', views.CustomerRetrieveView.as_view()), path('api-token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api-token-refresh/', TokenRefreshView.as_view(), name='token_refresh'), Views class CustomerRetrieveView(generics.RetrieveAPIView): queryset = Customer.objects.all() permission_classes=(IsAuthenticated,) def get(self,request, **kwargs, pk): queryset = get_object_or_404(Customer, pk=self.kwargs.get('pk')) serializer=CustomerSerializer(queryset) return Response(serializer.data) Serializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' -
How to download a dynamic file in django?
I have created a django application that converts txt to csv files. Now, I want to create a view function to download the newly converted csv files. Any suggestions will be highly appreciated. How to read the path object in download view? views.py def submit(request): # this function uploads txt files. # this function converts txt to csv files. For example abcd.txt is converted into abcd0000.csv and abcd0000.csv is stored in /main/temp/ folder. path = 'main/temp/converted_file.csv' #(Example)This file is dynamic # context is also present return render(request,'submit.html',context) Now I want to create a download function. For example: def download(request): data = open(path,'r').read() resp = HttpResponse(data, mimetype='application/x-download') resp['Content-Disposition'] = 'attachment;filename=path.csv' return resp submit.html <html> <head> <title> </title> </head> <body> <p>You have successfully converted the file. </p> <p><a href ="{% url 'download' %} ">Download (Filename)</a></p> </body> </html> -
Django Admin site not showing add permission option for a user
Actually i was learning permissions in django and also learning about groups. At first i have not inherited the PermissionMixin class when i have created my models. After finding i find my mistake why there is no option for the permission and groups for the custom user model. After that i updated my models and inherited the permissionmixin and finally it showed the permissions and groups option for a user in my model. But...............there is no such option to add a user to a group or to give permission to a user. As i have seen in some youtube videos there are some arrow keys to add permission or to remove them. Please help me to find out what i'm missing. I'm still a learner and learning django. My models from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser,PermissionsMixin ) # ///////////////User Manager///////////////////// # Create your models here. # overriding the create and superuser funciton class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), username=username, … -
How to 'select distinct on' as a subquery using django filters
I'm creating a search function for my django project and was wondering how I can group rows while ordering them by the amount of points the players have scored. I want to be able to group them and when it finds values with the same name, it just takes the first value The solution I found on postgresql select * from (select distinct on (name) * from database_manager_player) t order by pts desc; I wanted to know if there was a way to code something similar in django. in views.py: def get_queryset(self): qs = Player.objects.all().order_by('-pts') sort_by = self.request.GET.get("sort") if sort_by is not None and sort_by != str(0) sort_by = "-" + sort_by with 'qs' how could I do something in the if statement so that it does the same as in postgresql. -
403 csrf token error with paytm in django
I am trying to integrate the paytm payment gateway to my django web app. While most the process works properly and the payment is successful, the callback URL is not being called. Instead, I get the following error message Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. When I spoke to the technical team at paytm they told me that I had to accept the callback URL in POST. The person I spoke to, had little experience in django and could not help me further. I am not really sure what accepting the response in POST means. Here is my code views.py def donate(request): if request.method == "POST": form = DonateForm(request.POST) name = request.POST.get('firstName') phone = request.POST.get('phone') email = request.POST.get('email') amount = float("{0:.2f}".format(int(request.POST.get('amount')))) ord_id = OrdID() cust_id = CustID() paytm_params = { "MID" : MERCHANTID, "WEBSITE" : "DEFAULT", "INDUSTRY_TYPE_ID" : "Retail", "CHANNEL_ID" : "WEB", "ORDER_ID" : … -
Django,how to filter multiple JSONField data?
Im using django with postgres i was able to add multiple filters in my views but mu question here is is there any possibility that i can filter multiple same jsonfield with different values: ex i can filter localhost:127.0.0.1:products?areaOfUse=residential so is there any possibilty that i can get the result of /products?areaOfUse=residential&areaOfUse=test So from here i need to query two different json objects. -Here are my views class SubcategoriesProductsAPI(APIView): # @cache_control(must_revalidate=True, max_age=3600) def get (self, request, subCategoryId = None, pk = None): try: ''' Missing filters for PVC: 1.Colour Range 2.Pattern 3.Design Type ''' filters = {} design = self.request.query_params.get('design', None) dimension = self.request.query_params.get('dimension', None) collectionName = self.request.query_params.get('collectionName', None) material = self.request.query_params.get('material',None) min_price = self.request.query_params.get('min_price',None) max_price = self.request.query_params.get('max_price',None) page = self.request.query_params.get('page', None) wearLayer = self.request.query_params.get('wearLayer',None) areaOfUse = self.request.query_params.getlist('areaOfUse',None) productType = self.request.query_params.get('type', None) installationMethod = self.request.query_params.get('installationMethod',None) format_type = self.request.query_params.get('format_type',None) wearLayer = self.request.query_params.get('wearLayer',None) levelOfUse = self.request.query_params.get('levelOfUse',None) if design is not None: filters['product_options__options__data__design'] = design if productType is not None: filters['product_options__options__data__type'] = productType if dimension is not None: filters['product_options__options__data__dimensions__contains'] = [{'dimension': dimension}] if collectionName is not None: filters['product_options__options__data__collectionName'] = collectionName if material is not None: filters['product_options__options__data__material'] = material if wearLayer is not None: filters['product_options__options__data__wearLayer'] = wearLayer if installationMethod is not None: filters['product_options__options__data__installationMethod'] =installationMethod … -
not able to upload and display django form
1.views.py from django.shortcuts import render from . models import User from .forms import Userform def Home(request): if request.method == "POST": form = Userform(request.POST or None,request.FILES or None) if form.is_valid(): form.save() else: form = Userform() return render(request,"home.html",{"form":form}) def read(request): read = User.objects.all() return render(request,"read.html",{"read":read}) 2.models.py from django.db import models class User(models.Model): name = models.CharField(max_length=12) rollno = models.IntegerField() # files = models.FileField() 3.form.py from django import forms from .models import User class Userform(forms.ModelForm): class Meta: model = User fields = ('name','rollno') urls.py from django.contrib import admin from django.urls import path from app import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("",views.Home,name="Home"), path("read/",views.read, name="read"), ] urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 4.home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" action="read/" enctype="multipart/form-data"> {%csrf_token%} {{form}} <button type=submit>click to submit</button> </form> </body> </html> read.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {%block containt%} {%for i in read%} {{i.name}} {{i.rollno}} {%endfor%} {%endblock%} </body> </html> i want to add data to django admin using a form but data is not uploading at django admin Not able to upload data into django admin hence cant read it please help i want … -
How to define a model class variable to keep track of temporary data without saving to database
I am trying to design a checkout process where the tax information needs to go through a lookup table to get the appropriate tax rate based on parameters like buyer_address, product_price, etc. I am trying to avoid storing the tax rate as a property of the cart as a model field in the database because this value changes on the fly as the checkout form values change (cart line items change or shipping address changes). It's not solely a property of the cart or cart line item but depends on other paramters. I tried using a local variable in the class, and during the checkout process, once the customer clicks on PlaceOrder (POST to PaymentDetailsView), on the backend, a tax lookup will be done and added to the cart accordingly by setting that property. I am having a hard time understanding why the variable value remains None even after setting it. The lookup right now returns an example number of 0.8 as but I would have a more detailed method for the lookup that later. MODELS class BagLine(models.Model): _unitTax = None bag = models.ForeignKey(Bag, on_delete=models.CASCADE, related_name='lines') product = models.ForeignKey(ProductDesign, on_delete=models.CASCADE, related_name='bagLines') quantity = models.PositiveIntegerField(default=1) @property def unitTax(self): return self._unitTax @unitTax.setter … -
Django remote user not available in middleware - only in view
I`m using the django remote user middleware, and an own middleware mysupermiddleware: MIDDLEWARE = [ ..., 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'my_project.middleware.mysupermiddleware', ] When a remote user authenticates, it is available in the view. request.user shows the username. But in my middleware, it is not available def mysupermiddleware(get_response): def middleware(request): print (request.user) request.user returns AnonymousUser When I print request.user in my view, it returns the remote authenticated user. When I authenticate with ModelBackend instead RemoteUserBackend, the user is available in middleware and view. Is this intended? How do I make the remote user available in the middleware? Django version is 3.1.1 -
Django translation.activate doesn't change the language
I have a two-language Django website and when I want to change the language, it doesn't work. Here is the links in the template to change the language: <a href="{% url 'change_lang' %}?lang=en&next={{ request.path }}">EN</a> <a href="{% url 'change_lang' %}?lang=fa&next={{ request.path }}">FA</a> I send the language that I want and the current path as parameters for the view. This is the urls.py: from .views import change_language urlpatterns = [ path('change_lang', change_language, name='change_lang'), ] And this is the views.py: from django.utils.translation import activate def home(request): # My commands # activate('fa') context = { # Some key and values } return render(request, 'home.html', context) def change_language(request): activate(request.GET.get('lang')) return redirect(request.GET.get('next')) And I found that activate(request.GET.get('lang')) doesn't work. But when I uncomment the activate('fa') in the home view, It does work. But this command doesn't work in the change_language method. Is it because of the redirect function in the change_language view? What did I do wrong? Thanks for your help. -
Creating custom Django Rest Framework permision
I have created a django rest custom permision and for testing purposes I made sure has_object_permission and has_permission retrun False. from rest_framework import permissions class IsWorker(permissions.BasePermission): message = "Login with Supplier Account" def has_object_permission(self, request, view, obj): return False def has_permission(self, request, view): return False How comes this view doesn't work as expected? from packages.models import Package from .serializers import WorkerPackageSerializer from rest_framework.permissions import IsAuthenticated from api.permissions import IsWorker class WorkerPackageDetailViewSet(generics.RetrieveUpdateDestroyAPIView): serializer_class = WorkerPackageSerializer permission_classes = (IsAuthenticated, IsWorker) lookup_field = "id" def get_queryset(self): return Package.objects.all() Expectations: I thought it would return a forbidden error with the message Login with Supplier Account but if the user is not authenticated it returns a not authenticated error and if the user is authenticated it returns the data without any error. -
HTML checkbox value is only return 'on' in django
html <FORM NAME="myForm" method="GET" action="{%url 'search_result'%}"> <label for="F">Female</label><INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" value="F" id="0"> <DIV ID="subCats0" CLASS="subCats"> <INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" vaule='10' id='10'> gender=10 <div id="sub10" Class="sub"> <INPUT TYPE="checkbox" NAME="category_name[]" value="c"> 1.c <INPUT TYPE="checkbox" NAME="category_name[]" value="a"> 2.a <INPUT TYPE="checkbox" NAME="category_name[]" value="d"> 3.d </div> </DIV> <BR> <label for="M">Male</label><INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" id='1' value='M'> <BR> <DIV ID="subCats1" CLASS="subCats"> <INPUT TYPE="checkbox" NAME="10"> gender=10 </DIV> <input type="submit" value="search" id="search_button"> </FORM> css .subCats { display: none; margin-left: 20px; } .sub { display: none; margin-left: 20px; } javascript function toggleShow(checkbox) { var id = 'subCats' + checkbox.id; var subCats = document.all ? document.all[id] : document.getElementById ? document.getElementById(id) : null; if (subCats) { if (subCats.style.display == '' || subCats.style.display == 'none') subCats.style.display = 'block'; else subCats.style.display = 'none'; } } function toggleShow2(checkbox) { var id = 'sub' + checkbox.id; var sub = document.all ? document.all[id] : document.getElementById ? document.getElementById(id) : null; if (sub) { if (sub.style.display == '' || sub.style.display == 'none') sub.style.display = 'block'; else sub.style.display = 'none'; } } when click the submit, gender and category_name[] return correct value. for example, gender=F&age=on&category_name=b But age value is only return 'on'. Even though set the value of the check box, only return 'on'. what is problem..? Is the … -
Import Excel/csv and save data to new DB table
I am trying to develop a web application for Import any type of data like Excel/CSV and to insert the data to new table of connected DB without django model. While Inserting table column name as excel column and excel file name is table name. I wrote the code for Excel import using HTML screen its working fine. but I am stucking with Insert imported data to new DB table. Request your suggestion. def index(request): if "GET" == request.method: return render(request, 'index.html', {}) else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) worksheet = wb["PolicyData"] print(worksheet) excel_data = list() for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'index.html' {"excel_data":excel_data}) HTML code: <html> <head> <title>Import File</title> </head> <body style="margin-top: 30px;margin-left: 30px;"> <form action="{% url "test:index" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;"> </form> <p></p> <hr> {% for row in excel_data %} {% for cell in row %} {{ cell }}&nbsp;&nbsp; {% endfor %} <br> {% endfor %} </body> </html> -
Is there a way to perform accent-insensitive lookups using Django and MariaDB?
I would like to make an accent-insensitive lookup in a french database (with words containing accents): >>> User.objects.filter(first_name="Jeremy") ['<User: Jéremy>', '<User: Jérémy>', '<User: Jeremy>'] After lots of research, I found that Django has an Unaccent lookup for PostgreSQL but nothing for other databases (like MariaDB) Is there a way to make this happen without changing the database to PostgreSQL? -
How to get user email id through username by using csv file
By using csv/xls file we will upload usernames then in download we have to get user email_id to that specific user. How can I do? any help