Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to display form fields and objects in django
I am trying to create multiple forms in one template page(dischargedetails.html) using different views. Each form model is having foreignkey Ipd,First form (ProcedureForm) is working fine but the in Second form(investigation Form) not able to display investigation date feild and investigation name field models.py : class Investigation(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) name = models.CharField(max_length=60) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) class Procedure(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) time = models.TimeField( blank=True,default=now) urls.py : re_path(r'^(?P<ipd_id>\d+)/investigation/$', my_patient.create_investigation, name='create-investigation'), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), views.py: @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method =="POST": procedure = ProcedureForm(request.POST) if procedure.is_valid(): procedure.save() return HttpResponseRedirect(request.path_info) else : return HttpResponse(procedure.errors.as_data()) else : prolist=Procedure.objects.all().filter(ipd=ipd_id) procedure = ProcedureForm() return render(request, 'dischargedetails.html',{'object':object,'procedure':procedure,'prolist':prolist}) @login_required def create_investigation(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method=="POST": investigation = InvestigationForm(request.POST) if investigation.is_valid(): inves = investigation.save(commit = False) inves.object = object inves.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(investigation.errors.as_data()) else : investigationlist = Investigation.objects.all().filter(ipd=ipd_id) investigation = InvestigationForm() return render(request, 'dischargedetails.html',{'object':object,'investi':investigation,'investilist':investigationlist}) template <form method="post" action="{% url 'create-investigation' ipd_id=ipd.ipd_id %}" enctype="multipart/form-data"> <label>Date</label> <div class="input-group date"> {{ investi.date| add_class:'form-control' }} <label id="addNotesIDhelp" class="error" for=""></label> </div> <div class="form-group"> <textarea id="notesTextId" name = "report" type="text" placeholder="Add Investigation"class="form-control" value … -
iam getting stuck with the data preprocessing code for machine learning application
currently iam developing a machine learning application please help me in this code when i was uploading the big datasets getting an error please help in this code prep_file = Prepross.objects.get_or_create(filename = CurrentFile.objects.order_by('-id')[0].filename, coltype = request.POST.getlist('coltype'), assvar = request.POST.getlist('assvar'), missingvalues = request.POST.getlist('missingvalues'), trainingset_size = request.POST['trainingset_size'], featscaling = request.POST.getlist('featscaling') ) # Get dataframe and change data type context = {} file_name = CurrentFile.objects.order_by('-id')[0].filename coltype = request.POST.getlist('coltype') coltype = dict([i.split(':', 1) for i in coltype]) df = pd.read_csv(os.path.join('media\downloaded', file_name), dtype= coltype) row_count = df.count()[0] # Keep only selected columns assvar = request.POST.getlist('assvar') xcols0 = [s for s in assvar if ":X" in s] xcols = [i.split(':', 1)[0] for i in xcols0] ycol0 = [s for s in assvar if ":y" in s] ycol = [i.split(':', 1)[0] for i in ycol0] cols = xcols + ycol df = df[cols] xcols = ', '.join(xcols) ycol = ', '.join(ycol) missing = request.POST.getlist('missingvalues') missing = ', '.join(missing) trainingset_s = request.POST.getlist('trainingset_size') trainingset_s = ', '.join(trainingset_s) testset_s = 100 - int(trainingset_s) feat = request.POST['featscaling'] # Taking care of missing data if missing == "no": if len(df) != len(df.dropna()): context['selecty'] = 'Your data seem to have Missing Values' else: df = df.dropna() # Return error if columns are not … -
Is there a way to use custom sql queries with various arguments in django?
I'm creating an application that allows a user to filter through millions of records in a database (using dates, post types, etc.). The problem is that the database queries I need to perform are kind of complicated to use Django's ORM so I need to use custom SQL, and I don't have much experience dealing with SQL and this part of Django. If I needed the user specified filters before executing the query, how can I put in custom SQL without knowing how many filters/parameters there might be? And after that, how do I return what I found through that custom query into views so that the results can be displayed on the web page? I've already looked at the Django documentation on raw and custom SQL queries but there isn't a lot of documentation and help on custom SQL queries outside of the Django official documentation, so any help would be appreciated. from django.db import connection def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row The example code here is from the documentation. Say the filter had … -
Is there a way to use custom template in editor in django admin?
I have an issue with loading custom template file into editor which resides in django admin. I just simply put the file path into CKEDITOR_CONFIGS like so: CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ [...] ], 'templates_files': [ /path/to/template/template.js' ], 'templates': 'template' } } CKEDITOR.addTemplates( 'template', { templates: [ { title: 'BLEBELLBELBE', description: 'A template that defines two columns, each one with a title, and some text.', html: '<table cellspacing="0" cellpadding="0" style="width:100%" border="0">' + '<tr>' + '<td style="width:50%">' + '<h3>Title 1</h3>' + '</td>' + '<td></td>' + '<td style="width:50%">' + '<h3>Title 2</h3>' + '</td>' + '</tr>' + '<tr>' + '<td>' + 'Text 1' + '</td>' + '<td></td>' + '<td>' + 'Text 2' + '</td>' + '</tr>' + '</table>' + '<p>' + 'More text goes here.' + '</p>' } ] } ); Ckeditor is ignoring the file or just throwing and error on browser console that file can't be loaded. What am I doing wrong? -
python : object.__dict__ not showing all attributes
I am trying to print all the attibutes of an object. The purpose is mainly for debugging. I am using the following code: import json print(json.dumps(object.__dict__), indent=4, sort_keys=True, default=str)) It prints the attibutes of the object. But i was checking the list of all properties of the object using dir(object) I found that __dict__ does not show some properties at all which are listed by dir(). I thought of using dir(object) but it only a list of properties without attributes. So i think: `__dict__` has `incomplete` properties but with attirbutes `dir()` has complete list of properties but no attibutes So what is the best way to get a full dictionary of a attibutes of an object so that i can pretty print and see using json.dumps EXAMPLE I am working in a django project. And this is with related to db connection so the example is of a variable names db_con which is of the following object <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f29dee47a58> __dict__ way import json print(json.dumps(db_con.__dict__), indent=4, sort_keys=True, default=str)) The output is { "_thread_ident": ATTRIBUTE_VALUE "_thread_sharing_count": ATTRIBUTE_VALUE "_thread_sharing_lock": ATTRIBUTE_VALUE "alias": ATTRIBUTE_VALUE "autocommit": ATTRIBUTE_VALUE "client": ATTRIBUTE_VALUE "close_at": ATTRIBUTE_VALUE "closed_in_transaction": ATTRIBUTE_VALUE "commit_on_exit": ATTRIBUTE_VALUE "connection": ATTRIBUTE_VALUE "creation": ATTRIBUTE_VALUE "errors_occurred": ATTRIBUTE_VALUE "execute_wrappers": ATTRIBUTE_VALUE "features": … -
Python Django multiple request parameters
I am new to python & django and am trying to build a simple web application. I am running into the below issue I am passing the following code def view(request, cases_id, transactions_id): item = Cases.objects.get(pk=cases_id) item2 = Transactions.objects.get(pk=transactions_id) return render(request, 'view.html', {'item': item, 'item2': item2}) and getting the following error: view() missing 1 required positional argument: 'transactions_id' -
Docker up command exited with code 0 on another machine
Docker container for my app works fine on my system, while it doesn't on others'. I tried the following commands to re-run my docker container on a different machine: $docker-compose build $docker-up (this is where it fails !) Docker FROM python:3.6.8 MAINTAINER angy@localhost COPY ./ /app WORKDIR /app RUN pip install -r requirements.txt #CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3' services: python: build: context: . dockerfile: Dockerfile volumes: - ./:/myapp ports: - "8000:8000" Starting angy_proj_python_1_b395bdd740ea ... done Attaching to angy_proj_python_1_b395bdd740ea angy_proj_python_1_b395bdd740ea exited with code 0 -
Display all facets that were enabled in previous page
I have a book catalogue which I'm trying to filter search through. Each book falls under topic: ("english" "science" etc) and has a subcategory subcategory: (english: [poetry, plays], science: [chemistry, mechanics]). Each book item also has 2 attributes: book_format ("paperback" ,"hardcover" etc) language Currently the first 2 filters based on topic and subcategory work fine. Under format and language I've found a bug that enables a previously unavailable facet. For example if I chose "science book -> chemistry" the facet_count returns 0 "paperback books" so paperback is unavailable. But when I any other book format in the format field it enables paperbacks. I've debugged and traced the error to oscar.apps.search.facets in munge_field_facet the 'disabled' key is set to True or False based on: 'disabled': count == 0 and not is_faceted_already is_faceted_already is always true, this is because it is dependent on whether any facet in that field has been selected. In my case since I chose "hardcover" in the book_format field all of the facets in that field are enabled. I've checked the docs and various forums on faceting and it seems no one has needed to choose multiple facets whilst keeping previously disabled facets disabled. Here is the problem … -
Reduce 'waiting' time for a GET request to API
I am using Angular for frontend and Django for backend. I am referencing an API with particular graph data I am trying to retrieve. I think I have done it in an efficient way and have tried researching the best ways to do it. But the timings still show 5000-6000ms in waiting. Is this because of the angular to django link before the request is actually sent? I am doing it this way as I have an authorization key I wanted to keep secure in the backend. Code is long and in many files, I will try to explain: -Django get request to retrieve data for 3 graphs, this view also transforms the data into dictionaires and then returns keys and values separately as a response.-This is all coming from the Angular frontend which calls this upon loading the page to view the graphs. I expect/want a quick request and subsequent page loading but the page loads and then the graphs don't load for another few seconds. Any information would be appreciated. -
Upload image while user is filling in the form and validate the uploaded image
I have a django-form where a user can rate a product. To make sure the user has bought the product he has to upload a picture of the invoice. Every invoice has a bar code so what I want to achieve is to analyze the uploaded picture if there is a bar code. This should happen while the user is filling in the other fields of the form. My question is: is this even possible and if yes how can I upload a Image without pressing the submitbutton of the form. I'm in a early prototyp phase of my project so at the moment its enough when the images are only uploaded to a directory without validation. Please let me now if you need more information -
ValueError at /users/index/ Ensure you specified correct input image, input type, output type and/or output image path
I am building of program using opencv. I get this "Ensure you specified correct input image, input type, output type and/or output image path" error when I pass a variable through the function If I mentioned the image path like "media/image.jpeg" then everything works properly. I have tried using manually like detect("media/image.jpeg") this which works. If I put any variable like detect('"' + uploaded_file_url + '"') it doesn't work. Views.py file from .FirstDetection import detect from django.core.files.storage import FileSystemStorage def index2 (request): global name global uploaded_file_url name = "name" uploaded_file_url = "media/image.jpeg" if request.method == 'POST' and request.FILES['pic']: pic = request.FILES['pic'] fs = FileSystemStorage() filename = fs.save(pic.name, pic) uploaded_file_url = fs.url(filename) name = detect("media/image.jpeg") mylist = [] for n in name: mylist.append(n) return render(request, 'index.html', { 'uploaded_file_url': uploaded_file_url, 'd2' : mylist }) return render(request, 'index.html')''' **Detection.py file** from imageai.Detection import ObjectDetection import os def detect(image): # execution_path = os.getcwd() os.chdir("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django") media_path = os.getcwd() if os.path.exists("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django/media") : os.chdir("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django/media") execution_path = os.getcwd() detector = ObjectDetection() detector.setModelTypeAsRetinaNet() detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5")) detector.loadModel() url = '"' + "'" + image + "'" + '"' detections = detector.detectObjectsFromImage(input_image=os.path.join(media_path , image), output_image_path=os.path.join(execution_path , "imagenew.jpeg")) for eachObject in detections: name = eachObject["name"] # probability = eachObject["percentage_probability"] if(eachObject["percentage_probability"] … -
How to implement a progress bar based on the execution time of python function called in django views.py?
I'm executing a python function called through Django views.py. The python function takes about 3 to 10 minutes to complete. Based on the execution time of the above python function, how do I show the progress bar in front end? -
How to save ModelForm fields that are disabled in a template? (Not included in POST request)
I have created a ModelForm and an UpdateView to update the model's values. To simplify, let's say I have formfields A,B and C. My template displays A,B and C, but users can only edit A and B. C is calculated based on the values of A and B (server-side only). I am calculating C in the clean_C method of the modelform. If I set C to 'disabled' in my template, the value is not updated in my model. (I'm guessing this is because it is not included in the POST data?) If I set C to readonly, it saves correctly. Is there a way to still save C while keeping the field disabled? (to clarify, there is nothing in my model/modelform that disables the field, this is only in the template) It looks like the clean_C method runs regardless of the disabled/readonly flag in the template, and the appropriate value is included in the cleaned_data dictionary in the modelform's clean method. I've been digging through the Django source code to figure out why this happens. Can someone point me to where the data from cleaned_data is saved to the ModelForm / Model? -
Multiple pdf file should upload
While selecting Multiple pdf file is selected but while saving only one file is saving views.py def pdf_upload(request): pdf = Client_files.objects.all() client = Client.objects.all() process = Client_Process.objects.all() print(process) print(client) if request.method == 'POST': form = Upload_files(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('/pdf/upload/') else: form = Upload_files() return render(request,'uploadpdf.html',{'form':form,'pdf':pdf,'client':client,'process':process,}) models.py class Client_files(models.Model): Date = models.DateTimeField(default=datetime.now, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True) File_Name = models.FileField() Pages = models.IntegerField(null=True) Count = models.IntegerField(null=True) Status = models.BooleanField(default = False) class Meta: db_table : 'client_files' Attached the views and models,while selecting file i can select multiple files but while uploading i can only upload one file -
Render database values in template django
i have created app student from this i have to access database values on templates i have done the changes and apply migrations but it shows No changes detected in app 'student' , when i visit the localhost/phpmyadmin/ i only get the text from html file but not getting database values i want output like this: the student here, name, department, class, on web page 1)models.py file `from django.db import models class Student(models.Model): roll_no = models.TextField() name = models.TextField(max_length = 40) stud_class = models.TextField() department = models.TextField() ` 2)views.py file from django.shortcuts import render from django.shortcuts import render from django.http import HttpResponse from .models import Student def student_show(request): student = Student.objects.all() #order_by('roll_no') return render(request,'student/student1_show.html', {'student':student}) -
Assign URL to some specific words of a paragraph in dynamically rendered template from the data stored in Database
I have a Django blog app which shows the posts that I have created using a ClassBased DetailView. I want to assign different URLs to the different words in the paragraph just like Wikipedia. If it was a static page, it would have been solved easily but is it possible to assign <a> tags/URL values to the different words. Is there any method to do so? -
Django+MySQL - "Authentication plugin 'caching_sha2_password' cannot be loaded"
When running the command: python manage.py runserver I'm getting the following error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") These are the relevant settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': 'root', 'PASSWORD': '<my-password>', 'HOST': 'localhost' } } I've seen solutions that went around the problem, such as in this thread. They suggest changing the engine to mysql.connector.django, however the engine recommended by django is mysqlclient and therefore I would like to use it. Other suggestion were to use naive password instead of sha2. I'd rather not go with this solution for security reasons. Versions: mysql 8.0.17 for Win64 on x86_64 (MySQL Community Server - GPL) python 3.7.4 Django 2.2.4 mysqlclient 1.4.4 -
NoReverseMatch at /1/dischargedetails/
I am trying to create multiple forms in one template page(dischargedetails.html) using different views. Each form model is having foreignkey Ipd, when i am trying to submit forms ending up with error "Reverse for 'create-investigation' with keyword arguments '{'ipd_id': ''}' not found. 1 pattern(s) tried: ['(?P\d+)/investigation/$']" , models.py : class Investigation(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) name = models.CharField(max_length=60) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) class Procedure(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) time = models.TimeField( blank=True,default=now) urls.py : re_path(r'^(?P<ipd_id>\d+)/investigation/$', my_patient.create_investigation, name='create-investigation'), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), views.py: @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method =="POST": procedure = ProcedureForm(request.POST) if procedure.is_valid(): procedure.save() return HttpResponseRedirect(request.path_info) else : return HttpResponse(procedure.errors.as_data()) else : prolist=Procedure.objects.all().filter(ipd=ipd_id) procedure = ProcedureForm() return render(request, 'dischargedetails.html',{'object':object,'procedure':procedure,'prolist':prolist}) @login_required def create_investigation(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method=="POST": investigation = InvestigationForm(request.POST) if investigation.is_valid(): inves = investigation.save(commit = False) inves.object = object inves.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(investigation.errors.as_data()) else : investigationlist = Investigation.objects.all().filter(ipd=ipd_id) investigation = InvestigationForm() return render(request, 'dischargedetails.html',{'object':object,'investi':investigation,'investilist':investigationlist}) template <form method="post" action="{% url 'create-investigation' ipd_id=ipd.ipd_id %}" enctype="multipart/form-data"> -
Websocket disconnecting while running chat app from Django Channels tutorial
I'm building the chat app from Django Channels tutorial inside my django project. I successfully completed Tutorial Part 1 But when I get to the part of "Enable a channel layer" in Tutorial Part 2 I get a ConnectionRefusedError. In my_project/settings.py file I got INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stream_django', 'channels', 'debug_toolbar', 'messaging_app', ] WSGI_APPLICATION = 'my_project.wsgi.application' ASGI_APPLICATION = 'my_project.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } CELERY_BROKER_URL = 'redis://localhost:6379' In my_project/routing.py got from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import messaging_app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( messaging_app.routing.websocket_urlpatterns ) ), }) In my_project/urls.py have urlpatterns = [ ... path('chat/', include('messaging_app.urls')), ... ] and in my_project/messaging_app/urls.py have urlpatterns = [ path('', views.index_chat, name='index_chat'), path('<str:room_name>/', views.chat_room, name='chat_room'), ] In my_project/messaging_app/routing.py got from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chat/<str:room_name>/$', consumers.ChatConsumer), ] In my_project/messaging_app/consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) I tried to run $ python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() … -
Django project and application data model
I have to build several web-panels and I'm using django. Each panel is a Django Application, so I have: datalake_backend __init__.py models.py : IAV_PANEL __init__.py models.py : AMAZON_FUSE_PANEL __init__.py models.py : Currently the command: ./manage.py makemigrations skips the models defined into datalake_backend/models.py I defined the installed application as follow: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datalake_backend' 'datalake_backend.IAV', 'datalake_backend.AMAZON_FUSE_REVENUE' ] and it's falling to find datalake_backend. It this not possibile or am I missing something? Perhaps need I to defined a new application which holds the datalake_backend common logic and service? Something like: datalake_backend __init__.py models.py : IAV_PANEL __init__.py models.py : AMAZON_FUSE_PANEL __init__.py models.py : DATALAKE_BACKEND __init__.py models.py : In this case, I wonder why there is a models.py file into the project folder. Any link, suggestion or other pointers are welcomed. -
How can i custom a model that insert form data in a list that will show as one field in Django admin?
I am new to Django, and am trying to set a model that takes all the data that is implemented by the end-user, and insert them in a list and save it in the database, so I can see the data of each end-user in a separated list in Django admin. I tried to use super() to initialize the models.Model but what happened is that I wrote super(models.Model).init(self) and then ran it, it gave me an error saying that the relation attribute is missing class Topic(models.Model): def __init__(self,email,age,relation): super(models.model).__init__(self) self.email = email self.age = age self.relation = relation self.data = [] def submit(self): self.data.append(self.email) self.data.append(self.age) self.data.append(self.relation) def __str__(self): return "{}".format(self.data) def __rper__(self): return self.data ## this is the other code that I tried but it gave me an error saying email isn't defined ## class Topic(models.Model): email = models.CharField(max_length = 264,unique = True) age = models.IntegerField() relation = models.CharField(max_length = 264,unique = True) def submit(self): data = list(email,age,relation) def __str__(self): return "{}".format(Topic.submit()) def __rper__(self): return self.__str__() this error is for the second code, hope you guys will help and thank you so much. >>> from form.models import Topic >>> t = Topic(email = "naser@gmail.com",age = 20,relation = "single") >>> t.submit() … -
How to make the appearance of form in django?
I am trying to make a form but it is not showing me. Instead it is giving me error UnboundLocalError at /withdraw/ local variable 'form' referenced before assignment How to resolve this issue? views.py @login_required def withdraw(request): if request.method == 'POST': form = Withdrawapayment(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your request has been submitted.') return redirect('balance') context = {'form': form} return render(request, 'nextone/withdraw.html', context) models.py class WithdrawPayment(models.Model): payment = models.DecimalField(max_digits=100, decimal_places=2) class Meta: verbose_name_plural = 'Withdraw Payment' forms.py class Withdrawpayment(forms.ModelForm): class Meta: model = WithdrawPayment fields = ['payment'] -
How to implement log rotation in Django so that the files that are "rolled over" have custom names?
I want to implement logging in Django such that: 1] After a log file size exceeds a certain threshold, a new log file is generated and written to. 2] The name of this new file should be customisable. As an example, the log file name could be current_date_and_time-app_name.log 3] [Optional] The file that has reached the size limit is zipped and stored. How do I go about doing this? I tried using the RotatingFileHandler class but it rewrites old logs and also does not give the flexibility to change the log name. Here is the code that I have written: BASE_DIR_APP = os.path.dirname(os.path.abspath(__file__)) DIR_LOGS = os.path.join(BASE_DIR_APP, 'logs') current_time = datetime.now().strftime("%b-%d-%Y_%H-%M-%S--%f") U_LOGFILE_SIZE = 1 * 1024 U_LOGFILE_COUNT = 2 logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'file', 'maxBytes': U_LOGFILE_SIZE, 'backupCount': U_LOGFILE_COUNT, 'filename': os.path.join(DIR_LOGS, current_time + '.log') } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] } } }) -
Couldn't find that process type (web) deploying Heroku
In logs there is message about no running process. The output from heroku ps:scale web=1 is Couldn't find that process type (web). Procfile: web: gunicorn radio.wsgi --log-file - wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'radio.settings') application = get_wsgi_application() project structure: radio/ ├── player/ ├── radio/ ├── static/ ├── Procfile ├── requirements.txt └── runtime.txt -
M2M field was required and then changed to blank=True
I've got 2 models Task and TaskType. Task could have several types and they are required. Now new requirements dictate that types are unnecessary and should be removed. I set blank=True in Task field called types and run migration. Actually migration was created but didn't applied to DB. class TaskType(Base): name = models.CharField(max_length=50) class Task(Base): ... # initially there was only one parameter - TaskType types = models.ManyToManyField(TaskType, blank=True) ...