Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Oauth callback function in python. I there is a webserver should sends me Token and I want to react to the token if it's correct by call back
I want to make the same function but in Python Django how can I do that because I want to make authentication for login using Oauth 2.0 public function callback(Request $request){ $response = Http::post('https://oauth.zid.sa' . '/oauth/token', [ 'grant_type' =>'authorization_code', 'client_id' => 48, 'client_secret' => 'LsswUNyWTjyKT9AsXnpsv3FnG4glSNZQ5SM3YRnD', 'redirect_uri' => 'http://client.test/oauth/callback', 'code' => $request->code // grant code]);} -
upload image in forms Django
I am trying to upload image from form but whenever I submit everything got saved in database other than image field.But when I try to do samething from admin panel it works. models.py class Post(models.Model): title = models.CharField(("Title"), max_length=100) title_image = models.ImageField( ("Title Image"), upload_to='static/Images/TitleImages/', max_length=None, blank = True,null = True) Forms.py class AddPostForm(ModelForm): class Meta: model = Post fields = ['title','title_image'] Views.py class AddPostView(LoginRequiredMixin,CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous: messages.error(request,"You need to login to access this page") return redirect('/') elif request.user.is_superuser: if request.method == "POST": form = AddPostForm(request.POST) if form.is_valid(): form.save() messages.success(request,"POST added successfully") return redirect('/') else: print("error") else: print("method is not post") form = AddPostForm() return render(request,'MainSite/add_post.html',{'form':form}) else : messages.error(request,"You need to have superuser permission to access this page") return redirect('/') addpost.html <form action= "" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <button class="btn btn-primary profile-button" style = "width:150px;"type="submit" >Add Post</button></div> </form> my model have 2 things title and title_image but whenever I submit only title is saved and when I do through admin panel it works. I dont know what I am doing wrong here any advice will be helpful. Thanks in advance -
DJango unable to upload image on update
So basically django is unable to upload file after calling update function. It does work with create function. The path is getting updated in the database but the file isn't copying in the /media/ I'm not using the form for image (only for blog content), rather using froala editor. views.py def blog_update(request, pk): context = {} if not (request.user.is_authenticated): return redirect('/') else: try: blog_obj = Blog.objects.get(id = pk) if blog_obj.user != request.user: return redirect('/') initial_dict = {'content': blog_obj.content} form = BlogForms(initial = initial_dict) if request.method == 'POST': form = BlogForms(request.POST) image = request.FILES['image'] title = request.POST.get('title') gist = request.POST.get('gist') user = request.user if form.is_valid(): content = form.cleaned_data['content'] blog_obj = Blog.objects.filter(id = pk).update( user = user , title = title, gist = gist, content = content, image = image ) messages.success(request, f"Blog updated successfully!") return redirect('/my-blogs/') context['blog_obj'] = blog_obj context['form'] = form except Exception as e: print(e) return render(request, 'update-blog.html', context) forms.py class BlogForms(forms.ModelForm): class Meta: model = Blog fields = ['content'] I tried to print the path for existing file as well as the new selected file and it shows correct. Somehow the update function isn't copying the file to the media dir. I'm new to this, any help is … -
Django ChoiceField with custom forms
I am relatively new to Django and have been following up some tutorials on how to create registration forms with Django. **This is the html form code** <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>First name</label> {{ form.first_name }} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Last name</label> {{ form.last_name }} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="col form-group"> <label>Email</label> {{ form.email }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Directorate</label> <select name="directorate" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in form.directorate %} <option value=""></option> {% endfor %} </select> </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>Create password</label> {{ form.password }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Repeat password</label> {{ form.confirm_password }} </div> <!-- form-group end.// --> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Register </button> </div> <!-- form-group// --> </form> **This is models.py code** class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) directorate = models.CharField(max_length=100) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) … -
Date value in Django API response is one day lesser that actual value in database
I have a Django model which contain a date field. While I am calling a get API to get values from this model. The date value in response is one day lesser that what is there in the db. Please find a sample table id type created_date 1 test_type 2019-05-23 05:30:00 While I calling a get API I got response like this: {id":"1","type":"test_type","created_date":"2019-05-22T20:00:00-04:00"} Can you please help to fix this issue. And please give me an idea why this is happening. Thanks in advance -
Taking django application to https
I have a django application running perfectly fine in development server with http://localhost:8081 I need to take it to https. For which I tried 2 methods, but none of them is working. Method1: Using stunnel I installed stunnel and generated cert and key with openssl. openssl genrsa 2048 > ca.key openssl req -new -x509 -nodes -sha1 -days 365 -key ca.key > ca.cert cat ca.key ca.cert > ca.pem Defined dev_https as: pid= cert = certs/ca.pem sslVersion = all foreground = yes output = stunnel.log [https] accept=10443 connect=8081 and executed below commands: stunnel certs/dev_https & HTTPS=on /home/user/python3.9/bin/python3 /path/to/django/app/manage.py runserver localhost:8081 This is giving me error on console from stunnel as: connect_blocking: connect 127.0.0.1:8081: Connection refused (111) Connection reset: 0 byte(s) sent to SSL, 0 byte(s) sent to socket from django app gui: If I try to access the app over https://localhost:10443 This site can’t be reached If I try to access app over http://localhost:8081 ---> It works fine. But that's not required. Method2: Apache with mod_wsgi I installed mod_wsgi with rpm. Then modified httpd.conf as: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /path/to/django/app/wsgi.py WSGIPythonHome /home/user/python3.9 WSGIPythonPath "/home/user/python3.9/lib;/home/user/python3.9/lib/python3.9/site-packages" <Directory /path/to/django/app> <Files wsgi.py> Require all granted </Files> </Directory> and restarted the httpd. On starting the django … -
django inspectdb non public schema
We only have 1 database with atleast 10 different schemas how can I generate an inspectdb. Let's say python manage.py inspectdb "schema9.table1" > models.py to generate models I found couple of answers saying that django dont support this kind of feature specifically postgresql but maybe since it's 2022 maybe there's a simple and short way to do this -
Writeable Serializer
I have the following viewsets and serializers setup to create a single action to post a schedule with it's steps but I receive the following error. class StepCreateSerializer(serializers.Serializer): start_time = serializers.TimeField() time = serializers.IntegerField() def update(self, instance, validated_data): pass def create(self, validated_data): print(validated_data) return validated_data class ScheduleCreateSerializer(serializers.Serializer): name = serializers.CharField(max_length=100) identifier = serializers.CharField(max_length=10) steps = StepCreateSerializer(many=True) def update(self, instance, validated_data): pass def create(self, validated_data): steps_data = validated_data.get('steps', []) schedule = Schedule.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(schedule=schedule, **steps_data) return schedule class ScheduleViewSet(BaseViewSet): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer def create(self, request, *args, **kwargs): ser = ScheduleCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) ser.save() return Response() I call it with the following json payload with POST method: { "name": "Schedule123", "identifier": "S123", "steps": [ { "start_time": "07:21:00", "time": 5, "valve_actions": [ { "start_state": true, "end_state": false, "valve": 2 }, { "start_state": true, "end_state": false, "valve": 1 } ] } ] } It results in the following error when called with the payload TypeError: Direct assignment to the reverse side of a related set is prohibited. Use steps.set() instead. The models are as follows class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey("manager.Schedule", on_delete=models.CASCADE, related_name="steps", null=True) How do … -
Route53 DNS issue with Django Elastic Beanstalk app
Not sure what I am doing wrong here. My zone is public and I have simple routing for the A records pointing to the EB alias. I even tried a CNAME to no avail. I even did a test response within the console. Everything checks out but there is something funny happening between the Route53 -> EB handshake. The EB alias works just fine by itself. I would love some pointers. Perhaps I need to configure something within Django settings? -
Getting "_pickle.PicklingError: Can't pickle <function>: it's not the same object" for django-q async_task decorator
I'm trying to create a decorator that I can apply to any function, so I can make it a django-q async task. The decorator is written as bellow def django_async_task(func): """Django Q async task decorator.""" def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper Then I can use the above decorator in any task as below @django_async_task def my_task(a): print(f'Hello {a}') task_id = my_task('Vidu', task_name='task1') However, I cannot get the above to work as I'm getting _pickle.PicklingError: Can't pickle <function my_task at 0x7f3dc084be50>: it's not the same object as tests.my_task I tried functools wraps as below but it didn't have any effect. def django_async_task(func): """Django Q async task decorator.""" @functools.wraps(func) def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper I also tried a decorator class but it didn't solve the issue either. -
Password reset function in django admin is not working
urls.py from django.contrib import admin from django.urls import path,include from django.urls import re_path from App.views import * from.router import router from django.views.generic import TemplateView from rest_framework_simplejwt.views import ( TokenObtainPairView,TokenRefreshView) from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views urlpatterns = [ path('', TemplateView.as_view(template_name="social_app/index.html")), #social_app/index.html path('admin/', admin.site.urls), #admin api path('api/',include(router.urls)), #api path('accounts/', include('allauth.urls')), #allauth re_path('rest-auth/', include('rest_auth.urls')), #rest_auth path('api-auth/', include('rest_framework.urls')), re_path('/registration/', include('rest_auth.registration.urls')), path('api/token/', MyObtainTokenPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('jobview/',job), path('timelog/',timelogview), path('chaining/', include('smart_selects.urls')), path('admin/password_reset/',auth_views.PasswordResetView.as_view(),name='admin_password_reset',), path('admin/password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done',), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm',), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete',), ] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) I have given the password reset function in the admin page login, it is showing as "Forgotten your password or username?" in the page but when I click it the url changes http://127.0.0.1:8000/admin/login/?next=/admin/password_reset/ to this but the same login page is loading i didnt redirected to any other reset page. I have tried but couldn't able to fix it, kindly help me to fix this issue. -
Django+Docker - print() works in settings.py but not in other files
I'm using Django with Docker on my local system. print("Hello World") works in settings.py, but doesn't work in any other file!? Guess the Logger is taking away the control, but I just can't figure out how. At my wits end with this issue. Even print("Hello World", flush=1) doesn't work. (Here's the bigger issue) -
Multiple orders are being saved in one time django ecommerce?
In my django ecommerce website. I am trying to impplement order. It's working, but in one click being saved two orders. orderItem def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] quantity = data['quantity'] print('Action:', action) print('Product:', productId) print('Quantity:',quantity) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + quantity) if action == 'remove': orderItem.quantity = (orderItem.quantity - quantity) orderItem.save() if action=='delete': orderItem.quantity=0 if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) order def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) name = data['form']['name'] email = data['form']['email'] phone = data['form']['number'] phoneAdd = data['form']['numberAdd'] address = data['form']['address'] time = data['form']['time'] date = data['form']['date'] payment = data['form']['payment'] comment = data['form']['comment'] id_order = int(data['form']['id']) if request.user.is_authenticated: customer = request.user.customer order = Order.objects.get(id=id_order) order.transaction_id = transaction_id order.complete=True order.save() OrderInfo.objects.create(customer=customer,order=order,name=name,email=email,phone=phone,phoneAdd=phoneAdd,address=address,time=time,date=date,payment=payment,comment=comment) else: print("Not logged in ") return JsonResponse('Payment submitted..', safe=False) It's working and complete is being changed to TRUE. However, another empty order being created. So, what's the problem? Can you please help to solve this problem? -
Scanning External files inside python backend
I have some files that I need to download and then upload to a specific location during execution of code. These files are other than source code files but required by the source code(.yaml, .xml, some .zip folders etc.) I need to scan these files for any security vulnerabilities - on the backend. Most available approaches look at source code and not at external files. Any advice to this end would be useful.(No recommendations) Note:- I am not asking for any Software recommendations. Please feel free to ask for clarifications if you find the question misleading. -
Django Admin S3 Private Media Files
When using the private media django-storages class below. When I view the uploaded file in the admin it does not generate the URL Query String Authorization parameters. from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class PrivateMediaRootTenantedS3Boto3Storage(S3Boto3Storage): auto_create_bucket = True default_acl = "private" file_overwrite = False custom_domain = False -
datatable column filtering with serverside(ajax) doesn't work
I'm developing with django and javascript with datatable. I want to apply column filtering in my datatable (https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html) but it works fine without serverside option & ajax (in client side), but it doesn't work with serverside option & ajax. How can i FIX IT? Please help me..T_T this is my code. <table id="sample_table" class="table table-bordered table-hover"> <thead> <tr> <th class="sample_id">ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </thead> <tbody id="sample_table_body"> </tbody> <tfoot> <tr> <th>ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </tfoot> </table> </div> <!-- /.card-body --> </div> var column_list = [ { "data" : "id" , "className": "sample_id"}, { "data" : "receiving_at" }, { "data" : "serialnumber" }, { "data" : "name" }, { "data" : "birthday" }, ]; $('#sample_table tfoot th').each(function(){ var title = $("#sample_table thead th").eq( $(this).index() ).text(); $(this).html('<input type="text" placeholder="Search '+title+'" />' ); }); var sample_table = $('#sample_table').DataTable({ "paging": true, "autoWidth": false, "lengthChange": false, "ordering": true, "processing" : true, "columns": column_list, "order": [ [0, 'desc'] ], "fixedHeader": true, "orderCellsTop": true, "ajax": { url: '/view_datatable/', type: 'POST' }, "serverSide" : true, //get data from server "initComplete": function() { // column filtering RUN after table loaded . $( '#sample_table tfoot input' ).on( 'keyup change clear', function () { if ( sample_table.search() !== … -
API request failing if pagination is required in Django due to OrderBy' object has no attribute 'lstrip'?
I have a view that inherits from the ListModelMixin from Django REST Framework and have overridden the list(...) function so I can add query parameter validation to the list method: <!-- language: python--> class UserViewSet(ListModelMixin): def get_queryset(self): return User.objects.all() def list(self, request): queryset = self.get_queryset() # Get the query parameters from the request sort_by = request.query_params.get('sort_by') sort_order = request.query_params.get('sort_order') sorting_query: OrderBy = F(sort_by).asc(nulls_last=True) if sort_order == "desc": sorting_query = F(sort_by).desc(nulls_last=True) querySet = querySet.order_by(sorting_query, "id") # Code fails here on the pagination method page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The error I see when running the API is: AttributeError(\"'OrderBy' object has no attribute 'lstrip'\")", which I suspect has something to do with the sorting_query variable, but I have no idea WHY. The thing is, I only see this error when the total number of results exceed the MAX page size and pagination is needed. Otherwise, the API works fine. Any help would be appreciated! Note: I'm using cursor pagination from the Django REST Framework. -
Creating a Django post feed that gradually renders posts in batches as you scroll down
I am trying to make a Django post feed without pagination, but hypothetically, once there are more than a thousand posts, it would be too heavy to always render all of the posts available. So I am trying to find a way to mimic what many other websites with infinite feeds (like Twitter for example) do so that it renders only a batch of posts, and then renders additional ones once you scroll down to the end of the already rendered ones. I am using a function view instead of the class view. Thank you in advance for any help. -
Ignore HTML line in Django Template
I am new to Django. That's why I am a bit confused. and I am not sure is it possible or not? {% for appoint in appoints %} {% if appoint.a_status == 'Pending' %} <h4>Pending</h4> <p>{{appoint}}###<a href="#">Accept</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Accept' %} <h4>Accepted</h4> <p>{{appoint}}###<a href="#">Done</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Done' %} <h4>Done</h4> <p>{{appoint}}</p?> {% else %} <h4>Reject</h4> <p>{{appoint}}</p?> {% endif %} {% endfor %} This is part of a template. I want to ignore Django attribute/code to ignore the h4 tag. I know I can do this something by running loop for every h4 tag. but that will less efficient. -
Please, help to solve an exercise 19.1 from the book Python-Crash-Course.-Eric-Mattes
When I try to edit a post I see this error: TypeError at /edit_post/ edit_post() missing 1 required positional argument: 'post_id' blogs/models.py from django.db import models # Create your models here. class BlogPost(models.Model): """Creating blog topics and text""" title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Retunrning title""" return self.title def __str__(self): """retunrning text""" return self.text blogs/views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import PostForm # Create your views here. def index(request): """Homepage for blogs""" return render(request, 'blogs/index.html') def posts(request): """Shows the blogposts list""" posts = BlogPost.objects.order_by('-date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) def new_post(request): """Creating new topic""" if request.method != 'POST': #Data didn't sent; create empty form form = PostForm() else: # Data sent POST; process data form = PostForm(data=request.POST) if form.is_valid(): form.save() return redirect('blogs:posts') # Show empty or invalid form context = {'form': form} return render(request, 'blogs/new_post.html', context) def edit_post(request, post_id): """Edit post""" post = BlogPost.objects.get(id=post_id) if request.method != 'POST': # Request; form is filled with the data from current post form = PostForm(instance=post) else: # Sending POST data; process data form = EntryForm(instance=post, data=request.POST) if form.is_valid(): form.save() return redirect(request, 'blogs:posts') context = {'post': post, 'form': form} return … -
How to use if control statement in jinju2 embedded html file
I'm using parsehub to scrape a bunch of movie names and have a python script export it to an html file and that is working fine. However I want to use an if statement to only print titles that have "The" in them. The structure is fine and it is evaluating the if clause, but it always evaluates to false and I am not sure why. This is my first time using Jinju2 or even hearing about the language. {% for movie in movies %} {% if 'The' in movie %} <div name="title">{{movie["title"]}}</div> {% endif %} {% endfor %} Alternatively, the parsehub tutorial I was following https://help.parsehub.com/hc/en-us/articles/217751808-API-Tutorial-How-to-get-run-data-using-Python-Flask said that there is a way to optionally filter the scraped data but I have looked into it and am not sure how to do so. # movies.py from flask import Flask, render_template import requests import json API_KEY = '' PROJECT_KEY = '' PROJECT_DATA = f"https://www.parsehub.com/api/v2/projects/{PROJECT_KEY}/last_ready_run/data" app = Flask(__name__, template_folder='.') @app.route('/') def homepage(): params = { 'api_key': API_KEY, } r = requests.get( PROJECT_DATA, params=params) #print("The r var is: \n") #print(r) return render_template('movies.html', movies=json.loads(r.text)['movies']) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) How do I get the jinju2 if statement to evaluate to true, or how … -
Django running sum with a lag
I am trying to create a table with running sum with a lag using Django window functions -------------------------------------------------- id price size cumm_sum lagged_cumsum --------------------------------------------------- 1 5 6 6 0 2 5 9 15 6 3 15 10 25 15 Following the excellent answer here: Django cumulative sum or running sum I tried to do the following query.annotate(cumsum=Window(Sum("size"), order_by=F("price").asc()), lagged_cumsum=Window(Lag("cumsum", offset=1, default=0), order_by=F("price").asc())) However I keep getting the following error code: OperationalError: misuse of window function SUM() any ideas what i may be missing? -
How to delete all schemas in postgres
I'm using django-tenants, and for some tests I need to delete all schemas at once, so I was wondering how could I delete all schemas with a single sentence/script from postgresql shell, because deleting one by one is not scalable. Thx so much. -
ValidationError at /opd/ ['“OPDCashSheet object (2)” value must be a decimal number.'] How can a model-object be a decimal number?
models.py: class Opd(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) bill_number=models.IntegerField(default=None) date=models.DateField(default=datetime.date.today) service_name=models.ForeignKey(ServiceName, on_delete=SET_NULL, null=True) mode=models.CharField(max_length=5, default=None) amount=models.DecimalField(max_digits=7, decimal_places=2) remarks=models.TextField(max_length=500, blank=True, default=None) opd_date=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) def __str__(self): return self.patient.name class OPDParticulars(models.Model): opd_particulars=models.CharField(max_length=150) def __str__(self): return self.opd_particulars class OPDCashSheet(models.Model): date=models.DateField(default=datetime.date.today) patient=models.ForeignKey(Patient, on_delete=SET_NULL, blank=True, null=True) opd=models.ForeignKey(Opd, on_delete=SET_NULL, null=True, blank=True) opd_particulars=models.ForeignKey(OPDParticulars, on_delete=SET_NULL, null=True, blank=True) source=models.CharField(max_length=10, default='OPD', null=True, blank=True) case_number=models.IntegerField(null=True, blank=True) mode=models.CharField(max_length=5) cash_in=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) cash_out=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) balance=models.DecimalField(max_digits=7, decimal_places=2, default=0) bank_oopl=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) remarks=models.TextField(max_length=500, blank=True, null=True, default=None) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) class BankDeposits(models.Model): opdcashsheet=models.ForeignKey(OPDCashSheet, on_delete=SET_NULL, null=True, blank=True) date=models.DateField(default=None) amount=models.DecimalField(max_digits=7, decimal_places=2, default=None) bank=models.CharField(max_length=70, default=None, null=True, blank=True) mode=models.CharField(max_length=5, default=None) bank_ac=models.CharField(max_length=25, default='ABC Pvt. 123456789') branch=models.CharField(max_length=20, default='XYZ') remarks=models.TextField(max_length=500, blank=True, null=True, default=None) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) forms.py: class UpdateOPDCashSheetForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=OPDCashSheet labels={ 'cash_in':'Cash-in', 'cash_out':'Cash-Out', 'balance':'Cash Balance', 'bank_oopl':'To Bank', 'opd_particulars':'Description', } fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } class BankDepositsForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=BankDeposits labels={ 'bank_ac':'Bank A/c', } fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } class OpdForm(ModelForm): MODE_SELECT = ( ('cash', 'Cash'), ('bank', 'Bank'), ) mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=Opd fields='__all__' widgets={ 'date': DateInput(attrs={'type': 'date'}), } views.py: def opd_view(request): if request.method=='POST': fm_opd=OpdForm(request.POST) if fm_opd.is_valid(): opd=fm_opd.save() OpdReport.objects.create(patient=opd.patient, opd=opd) if opd.mode=='cash': OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, cash_in=opd.amount) … -
search files on a specific folder in Django
how to search files on a specific folder in Django 2.1.15w i'm making a n an web app, and i want user to select a variable file only from on specific folder, how i should fix the header in Django to show on directory path, happy to here any ideas