Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating query in nested django model and group the results in django
I am trying to create query in my postgresql database with django ORM and then group the results by specific ip_addr. Here is my models: class Report(models.Model): network = models.CharField(max_length=50) timestamp = models.CharField(max_length=30) def __str__(self): return f"{self.network}_{str(self.timestamp)}" class Device(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) ip_addr = models.GenericIPAddressField() mac_addr = models.CharField(max_length=20) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.ip_addr class Port(models.Model): host = models.ForeignKey(Device, on_delete=models.CASCADE) port = models.IntegerField() status = models.CharField(max_length=15) application = models.CharField(max_length=100) def __str__(self): return str(self.port) When I perform query Port.objects.filter(host__report_id=pk) I get all the port in specific Report. My problem is that I do not know how to group all ports whit the ip_addr they belong to. I will appreciate any useful advice. -
Cant refresh JWT Token "Signature has expired."
I am using django-rest-framework-jwt and react-redux for my SPA. Need refresh token that expires in 5 minutes. Refresh works during the 5 minutes. After it does not work, console show this error: POST http://localhost:8000/auth/api-token-refresh/ 400 (Bad Request) createError.js:17 Uncaught (in promise) Error: Request failed with status code 400 at createError (createError.js:17) at settle (settle.js:19) at XMLHttpRequest.handleLoad (xhr.js:78) and postman show this: { "non_field_errors": [ "Signature has expired." ] } there's the middleware's code import axios from "axios"; import * as urls from "../helpers/url"; import { authUpdateToken } from "../actions/auth"; const jwthunk = ({ dispatch, getState }: any) => (next: any) => (action: any) => { if (typeof action === 'function') { if (getState().auth && getState().auth.token) { const currentToken = getState().auth.token; verifyToken(currentToken) .then((tokenVerified: any) => { refreshToken(tokenVerified, dispatch) }) .catch(() => { refreshToken(currentToken, dispatch) }) } else { console.log('Not Auth'); } } return next(action); } export default jwthunk; const verifyToken = async (token: any) => { const body = { token }; let verifiedToken = ''; await axios.post('http://localhost:8000/auth/api-token-verify/', body) .then(({ data: { code, expires, token } }: any) => { verifiedToken = token; }); return verifiedToken; } const refreshToken = async (token: any, dispatch: any) => { const body = { … -
How to combine a form and multiple formsets for the same model in a view?
I have three models "parent - child - grandchild". I would like for one view to handle one form for parent, one formset for child and multiple formsets for grandchild. Specifically; parent_1_form child_1_formset (children of parent_1) child_1_form (form 1 of formset) grandchild_1_formset (children of child 1) child_2_form (children of parent 1) grandchild_2_formset (children of child 2) So I want to create a parent form, then a child formset and for each child form I want a new grandchild formset. Especially this last part seems challenging, to have multiple formsets for a single model in one view. I can manage to create a parent form, child formset and grandchild formset in one view. However I am unsure how I would be able to combine multiple formsets for the same model into one view. Could anyone give some advice on how to structure this? -
How to convert select_related queries in Django into a single dataframe
I am working in Django and I would like to simply merge three tables into one dataset. My models look like so and I have tried variants of the following command: class Quadrat(models.Model): quadrat_number = models.IntegerField() class Capture(models.Model): quadrat= models.ForeignKey(Quadrat, on_delete=models.DO_NOTHING) capture_total = models.IntegerField() class Species(models.Model): capture = models.ForeignKey(Capture, on_delete=models.DO_NOTHING) species = models.CharField(max_length=50) data = pd.DataFrame(list(Species.objects.select_related('Capture_set', 'Quadrat_set').all() I get an attribute error: Cannot find 'Capture_set' on Species object, 'Capture_set' is an invalid parameter to select_related() I am probably using select_related wrong. Any ideas ? -
Django - Is it possible to translate only some of the models (admin forms)?
Say that you have a django admin site with the common users/groups fields, and some other fields that you like to leave as plain English, yet some of the forms you need to translate to another pre-defined language: Think Hebrew/Arabic where the interface can easily be changed to RTL by using a CSS, but then the English in the page does not fit, because the page is ... right to left, and it is desirable that not only the fields are translated, but also the titles. The documentations, and many other solutions here shows that there is good support to translate the whole admin site, by setting the language to the whole site, but I could not find how to set the language specifically to some forms, which seems not a very unreasonable request, I am sure others have raised before... -
Django annotate, combine multiple related values onto same instance
I have a django app with the following models: class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Job(models.Model): title = models.CharField(max_length=100) class PersonJob(models.Model): person = models.ForeignKey(Person, related_name='person_jobs') job = models.ForeignKey(Job, related_name='person_jobs') is_active = models.BooleanField() Multiple Person instances can hold the same job at once. I have a Job queryset and am trying to annotate or through some other method attach the names of each person with that job onto each item in the queryset. I want to be able to loop through the queryset and get those names without doing an additional query for each item. The closest I have gotten is the following: qs = Job.objects.all().annotate(first_names='person_jobs__person__first_name') .annotate(last_names='person_jobs__person__last_name') This will store the name on the Job instance as I would like; however, if a job has multiple people in it, the queryset will have multiple copies of the same Job in it, each with the name of one person. Instead, I need there to only ever be one instance of a given Job in the queryset, which holds the names of all people in it. I don't care how the values are combined and stored; a list, delimited char field, or really any other standard data type would be … -
Is it possible in django ModelForm to leave Filefield empty?
I want to make an app where you can upload few files, where only one is required - you are obligated to choose one file, but the others are optional. If I don't choose all the files I get: MultiValueDictKeyError at /fpFilterRun/ At the beginning I was using Form, now I switched to ModelForm, tried to check if fileFields are empty or not, digged through I believe whole Stack and nothing helped. models.py class FPFilter(models.Model): QueryName = models.CharField(max_length=25) DCAfile = models.FileField() MSAfile = models.FileField(blank=True, null=True) SSfile = models.FileField(blank=True, null=True) RSAfile = models.FileField(blank=True, null=True forms.py class FPFilterForm(ModelForm): class Meta: model = FPFilter fields = ['QueryName', 'DCAfile', 'MSAfile', 'SSfile', 'RSAfile'] labels = { 'QueryName': 'Query name:', 'DCAfile': 'DCA file:', 'MSAfile': 'MSA file:', 'SSfile': 'Secondary Structure file:', 'RSAfile': 'Relative Solvent Accessibility file:', } views.py def fpFilterRun(request): if request.method == 'POST': fpfilter_form = FPFilterForm(request.POST, request.FILES) if fpfilter_form.is_valid(): query_name = request.POST['QueryName'] DCADict = save_file(request.FILES["DCAfile"], saveDir) if request.FILES['MSAfile'] is not 'u''': MSADict = save_file(request.FILES['MSAfile'], saveDir) MSAPath = MSADict['filePath'] else: MSAPath = 'empty' if bool(request.FILES['SSfile']) is False: SSDict = save_file(request.FILES['SSfile'], saveDir) SSPath = SSDict['filePath'] else: SSPath = 'empty' if request.FILES['RSAfile'] is not None: RSADict = save_file(request.FILES['RSAfile'], saveDir) RSAPath = RSADict['filePath'] else: RSAPath = 'empty' else: fpfilter_form = … -
How to use imports from requirements.txt in python
I am attempting to use a python file in a basic web application. I have my two requirements (docx and xlrd) in my requirements.txt file, but when the python file tries to import either of the requirements, it cannot find the module. I am currently working on Repl.it. Pictures are attached. I have tried to import only in either location, but I either fail to import the necessary packages, or I cannot refer to functions from the necessary file. Requirements.txt - xlrd==1.2.0 docx==0.2.4 other script.py - import docx from docx.enum.table import WD_ALIGN_VERTICAL import xlrd error - (continued) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/home/runner/main/urls.py", line 5, in <module> from main import views File "/home/runner/main/views.py", line 3, in <module> from excelToDocx import transfer File "/home/runner/excelToDocx.py", line 1, in <module> import xlrd ModuleNotFoundError: No module named 'xlrd' exit status 1 -
Chart.js integration to Django project
New to Charts.js and Django. Seems like I make it working, but not as good as I want it to. Would like to integrate two calculations made on Django side: my views.py: def graph(request): bug_all = BugTable.objects.filter() bug_all_total = bug_all.count() bug_posted = BugTable.objects.filter( status=BugTable.BUG_POSTED) bug_posted_total = bug_posted.count() context = {'bug_all_total': bug_all_total, 'bug_posted_total': bug_posted_total} return render(request, 'graph.html', context) my graphs.html <canvas id="Bug-status-bar" class="col-md-6"></canvas> <script THERE GOES CHART CDN LINK></script> <script type="text/javascript"> var ctx = document.getElementById('Bug-status-bar'); var dataArray = [{{bug_all_total|safe}}, {{bug_posted_total|safe}}] var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['All', 'Posted', 'Pending', 'Fixed'], datasets: [{ label: 'Statistic on bug activity', data: dataArray, backgroundColor: [ 'rgba(255, 99, 132, 0.4)' 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)' 'rgba(54, 162, 235, 1)', ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> When I put one of those elements (bug_all_total or bug_posted_total) to graph.html data section it works fine, but for some reasons it does not work together. Any suggestions why? Any help is appreciated. -
Django select_related chained foreign keys doesn't return non-direct related objects
I have been through multiple other posts so this one might seem a duplicate but I couldn't find an answer. I'm new on the platform so I apologies if this is not the proper way to proceed. I use Django 2.2 Based on the official doc, it says that select_related() returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#select-related Here is the official example: You can follow foreign keys in a similar way to querying them. If you have the following models: from django.db import models class City(models.Model): # ... pass class Person(models.Model): # ... hometown = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True, ) class Book(models.Model): # ... author = models.ForeignKey(Person, on_delete=models.CASCADE) then a call to Book.objects.select_related('author__hometown').get(id=4) will cache the related Person and the related City: # Hits the database with joins to the author and hometown tables. b = Book.objects.select_related('author__hometown').get(id=4) p = b.author # Doesn't hit the database. c = p.hometown # Doesn't hit the database. # Without select_related()... b = Book.objects.get(id=4) # Hits the database. p = b.author # Hits the database. c = p.hometown # Hits the database. Here is my code: class Campaign(SlugifyNameMixin, TimeStampedModel, TimeFramedModel, StatusModel): STATUS = … -
Django tutorial. Generic views. context_object_name = 'latest_question_list'
I'm a bit confused with Django generic views. As shown in here we are converting custom views into generic views. And while I understand what happens in DetailView and ResultsView, I don;t entirely grasp how this: def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) converts into this: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] In the first example, latest_question_list = Question.objects.order_by('-pub_date')[:5] But in the second example, what latest_question_list variable is equal to in here? We haven't even defined it.. Can anyone please shed some light into this? -
Permission to custom buttons on change_form.html of Django Admin
I have added some custom buttons in the change_form.html of Django Admin. However, I wanna to hide those buttons to specific user. <!-- change_form.html --> {% extends "admin/change_form.html" %} {% block submit_buttons_bottom %} {{ block.super }} <div class="my-submit-row"> <input type="submit" value="Save as draft" name="_drafted" class="btn btn-lg btn-success"> </div> {% endblock %} As the code below, I can hide the "save" and "save_and_continue" button, which are built-in buttons, make them only can be seem by the superuser. Anyone has any experiences or suggestions for this? # admin.py class MyAdmin(admin.ModelAdmin, ExportCsvMixin): ... def change_view(self, request, object_id, extra_context=None): if not request.user.is_superuser: extra_context = extra_context or {} extra_context['show_save_and_continue'] = False extra_context['show_save'] = False return super(MyAdmin, self).change_view(request, object_id, extra_context=extra_context) -
How to fix Django autocomplete_fields jquery error?
I'm using Django autocomplete_fields feature but I have a problem with Jquery TypeError: $element.select2 is not a function Under django development server works perfectly as spected but when I deploy the code on a server to test jquery is not working and I get VM106 inlines-nested.js:18 Uncaught TypeError: Cannot read property 'fn' of undefined autocomplete.js:14 Uncaught TypeError: $element.select2 is not a function I'm using Django 2.1 + gunicorn + docker + nginx to deploy the code My code in admin.py is class CityModelAdmin(admin.ModelAdmin): search_fields = ['name'] class ProfileAdminModel(NestedModelAdmin): #form = ProfileCustomForm inlines = [DescriptionInline, AddressInline, CommentInline] autocomplete_fields = ['city','profession','location', 'user', 'branch1', 'branch2', 'branch3', 'institution1', 'institution2'] admin.site.register(City,CityModelAdmin) admin.site.register(Profile, ProfileAdminModel) -
How to access a column from a table having two foreign keys?
I am trying to access a column form my table . This table have two foreign keys. from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.db.models.signals import post_save class Question(models.Model): question_id = models.IntegerField(default=0, unique=True) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.IntegerField() def __str__(self): return str(self.answer_text) class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(upload_to='',blank=True) points = models.IntegerField(default=0) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class Points_Tally(models.Model): userid=models.ForeignKey(User,on_delete=models.CASCADE) questions_id=models.ForeignKey(Question,on_delete=models.CASCADE) status=models.IntegerField(default=0) def __str__(self): return str(self.userid) ''' This is the view where i want to access status form Points_Tally table. If status is zero then user can submit the answer to the question then points will be increased and the status will be set to 1 so that if the user try to answer it again he won't be able to do that. ''' def detail(request, question_id,pk=None): question_data=get_object_or_404(Question,pk=question_id) if pk: user = User.objects.get(pk=pk) else: user = request.user form = forms.ValidateAnswerForm() points_tally_object = Points_Tally.objects.all() entire_data=[] for items in points_tally_object: entire_data.append(items.questions_id.question_id) #this is for the answer stored_ans = Answer.objects.all() answer_list = [] for k in stored_ans: answer_list.append(k.answer_text) if request.method == 'POST': form = forms.ValidateAnswerForm(request.POST) if … -
I have problems with views
I have this models: Class Category(models.Model): name = models.CharField(max_length=150, unique=True) description = models.CharField(max_length=250) def get_absolute_url(self): return reverse('categories_url', args=[str(self.id)]) class Company(models.Model): name = models.CharField(max_length=150, unique=True) country = models.CharField(max_length=50) class Motobike(models.Model): name = models.CharField(max_length=150) company = models.ForeignKey('Company', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('details_url', args=[str(self.id)]) And views: class CategoryView(DetailView): model = Motobike template_name = 'bikes_site/categories_detail.html' pk_url_kwarg = 'pk' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = self.get_object() context['motobikes'] = Motobike.objects.filter(category_id=category.pk) return context And test: def test_category(setup): client = Client() category_id = Category.objects.get(name='Мотоциклы').id response = client.get(f'/categories/{category_id}/') assert response.status_code == 200 response_data = json.loads(response.content.decode('utf-8')) assert len(response_data) == 2 assert response_data[1]['name'] == 'Ninja Turbo' assert response_data[1]['vendor'] == 'Kawasaki' assert response_data[1]['category'] == 'Мотоциклы' assert response_data[1]['description'] == '' response = client.get(f'/categories/25/') assert response.status_code == 404 I need to present all thin in JSON, through JsonResponce, and what should almost go to the meaning of the dictonary, did i create them correctly? -
Save the field in the model based on another field in the same model. Django
I am trying to save my field of the model based on another field in this same model. For example: class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" my_try = models.CharField(max_length=50, default=baby_boomer_status) #it does not work How I can properity save my_try always when i change birth_date in my object. To have value in my field my_try "Pre-boomer" or "Baby boomer". Any help will be appreciated. -
How to dipslay Django Views in html templates?
Trying to setup a random percent matching score to my Django-Haystack search results, everything seems to be working fine on the backend (no errors) but I'm unable to display these matching scores into my templates (html). So how can I display them? Here's my code: Using a custom forms for Haystack in forms.py: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Categories filter if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs Then I'm passing it to a custom View: from .forms import FacetedProductSearchForm from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 20 context_object_name = 'object_list' And I have these two functions in my Views to generate the matching scores: def random_search_match_percentages(array): from random import random from math import floor index = 0 results = [] for element in array: # define a maximum and a minimum range maximum = 100 - index if index <= … -
How to change a related field's attribute in another model if a date has passed
In my model, if the "trip_end" date has passed I'd like for the van stored in "van_used" to have its available attribute set back to true. I am not sure how to set up a function to run the check daily. here is my model.py: class trips(models.Model): first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) trip_start = models.DateField(blank=True, null=True) trip_end = models.DateField(blank=True, null=True) van_used = models.ForeignKey(vans, on_delete=models.CASCADE, blank=True) def delete(self, *args, **kwargs): """When a trip is deleted, mark the van that it used as available.""" if vans.objects.filter(vanName=self.van_used).exists(): vans.objects.filter(vanName=self.van_used).update(available=True) super(trips, self).delete(*args, **kwargs) I'm open to all suggestions, I am still new to django so I want to get these basics down. -
Django CKEditor - Can't load media
I'm using CKEditor outside the admin panel. I want to load media in my custom ckeditor/widget.html but it's not working. Here's my 'ckeditor/widget.html': {% block css %} {{ form.media }} {% endblock %} <div class="write_comment"> <div class="django-ckeditor-widget" data-field-id="{{ id }}"> <textarea{{ final_attrs }} data-processed="0" data-config="{{ config }}" data-external-plugin-resources="{{ external_plugin_resources }}" data-id="{{ id }}" data-type="ckeditortype">{{ value }}</textarea> </div> <div class="bottom"> <ul class="flex-horizontal"> <li><p class="chars_written"></p></li> <li><p class="chars_left"></p></li> </ul> </div> </div> Here's my custom widget: class CommentInput(CKEditorWidget): @property def media(self): media = super().media css = { "all": ( static("widgets/comment/comment.js"), ) } js = [ static("widgets/comment/comment.css"), ] media.add_css(css) media.add_js(js) print(media) return media -
Django Admin - prevent save under certain conditions and display message to user
I am putting together a Django app - created and registered the models and model forms. When adding or editing a particular model record, I need to call an external service for some information. If the information is retrieved successfully I want to update a column on that model which the user is unaware of and save the model. If the call fails I need to prevent the save from occurring and a custom message returned to the user. I have tried raising Exceptions, returning messages as String etc but nothing seems to work. Although I can stop the save from occurring I end up with a stack-trace if I don't return the model. I have seen various solutions using the clean() method or signals but none seem to suit the need. The order of things I need to happen: Validate the Form data being entered (happens automatically) Do the API call to the external service to retrieve the info Assign the info to the model prop and save the model If API call fails, cancel save() and display message to user I just cannot seem to find a simple solution out there - any help appreciated! -
Django many-to-many inline model admin selects waaay too many rows from rel
I am trying to make a n-to-n rel work the way that it shows the corresponding relationship in the admin page for each of the two models in this rel. Out of the box only the model that has the relationship defined on it gets the form on its admin page. So i have followed the official documentation: https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects As you should see(below in my code) i have basically added exactly what it says. Now my problem is that i have about 350k rows in this mapping table, but if i select in my database one bar only has 80 foos, and the reverse selection maybe 140. Now it seems like it selects 147k rows(!), so it seems like it somehow selects about half of my entire join table even though i am just clicking on a specific foo. So somehow it seems like it isn't doing just a simple join between the two models with ids, when i look in my sql log the SQL it generates is just selecting things from one table at a time, which is weird because the join can be done in 1 line. So i have a Django app that has the following … -
How to print a tuple from view to html
I am woking in Django and I would simply like to print a tuple from view to html. Like so: VIEW.PY def dumdum_view(request): dummy =[(1,2,3)] dumdum = tuple(dummy) return render_to_response('dumdum.html', {'dumdum':dumdum}) HTML.PY {% for i in dumdum %} {{ i.0 }} {{ i.1}} {{ i.2 }} {% endfor %} I have tried various variations of the simple code above but nothing works. Any ideas ? -
Dont get field in result create method django rest framework
I have a method of creating clien. one of the body fields of my method is client_users which is not in my client model. He has a foreign key for clients. I overwrite the create method and it is ok. But when I return the method I have this error: AttributeError: Got AttributeError when attempting to get a value for field `clientes_usuarios` on serializer `ClienteCreateSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Cliente` instance. Original exception text was: 'Cliente' object has no attribute 'clientes_usuarios'. My field in my serializer: class ClienteCreateSerializer(serializers.ModelSerializer): endereco_residencial = EnderecoSerializer(read_only=False) endereco_cobranca = EnderecoSerializer(read_only=False,required=False) contatos = ContatoClienteSerializer(many=True, read_only=False, required=False) certificados = CertificadoSerializer(many=True, read_only=False, required=False) email = serializers.EmailField(source='usuario.email') cnpj = serializers.CharField(max_length=14, min_length=14, source='usuario.cpf_cnpj') foto = serializers.CharField(required=False) data_abertura = serializers.DateField(input_formats=settings.DATE_INPUT_FORMATS, required=False, allow_null=True) clientes_usuarios = UsuarioClienteCreateSerializer(many=True,read_only=False) I have outher methods like this and they works fine -
Django creates an empty logging file in production
I want to have the same debug level in production as in development. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/home/djangoadmin/logs/the.log', 'when': 'midnight', # this specifies the interval 'interval': 1, # defaults to 1, only necessary for other values 'backupCount': 10, # how many backup file to keep, 10 days 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } I get an empty file in my Ubuntu digital ocean instance ? What am I doing wrong ? -
Django - In a survey app that uses forms is it necessary to use Formsets?
I'm currently working with a survey app. The answers are stored in a table created by a very simple model: class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, null=False) item = models.ForeignKey(Item, related_name = "question", on_delete=models.PROTECT, null = True) answer = models.TextField() So for example, if the survey has 10 questions, 10 rows would be created in the database for each user. Given the above, the form to be created must have multiple questions and the corresponding inputs to answer. My questions are: 1. For these cases it is obligatory to use formsets? 2. If it is not mandatory, is it recommended? or is there a better way to deal with this problem?