Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to send custom password reset email in latest Django version
I have the same question as this stack overflow: Does Django password_reset support html email templates? But, I could not get the solutions to work in the current Django version. The basic attempt render the html as a string. How do I get the html to render as html? my urls.py: path('accounts/password-reset/', auth_views.PasswordResetView.as_view( template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), password_reset_email_template.html: <html> <tr> <td style="color:#333333; font-family: Helvetica, sans-serif;text-align:left; font-size:14px; line-height:20px; padding-bottom:18px;text-align:left;"> {% load i18n %} {% autoescape off %} You're receiving this e-mail because you requested a password reset for account. {% endautoescape %} <p>Follow the link below to reset:</p> <a href="https://domain{% url 'password_reset_confirm' uidb64=uid token=token %}"> Reset Password </a> </td> </html> I also tried to create a new view, but that does not render anything at all. def reset(request): return password_reset(request, template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt', post_reset_redirect=reverse('login')) -
Docker-compose cannot find file manage.py in runserver command
I what to dockerize my django app, i create my Dockerfile : FROM python:3.6-alpine RUN apk add --no-cache linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /DEV WORKDIR /DEV COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . . at this point i create my docker-compose.yml: version: '3' networks: mynetwork: driver: bridge services: db: image: postgres restart: always ports: - "5432:5432" networks: - mynetwork environment: POSTGRES_USER: myuser POSTGRES_PASSWORD: mypass POSTGRES_DB: mydb volumes: - ./data:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 networks: - mynetwork volumes: - .:/DEV ports: - "8000:8000" depends_on: - db then i create a .dockerignore file: # Ignore .DS_Store .idea .venv2 __pycache__ !manage.py *.py[cod] *$py.class *.so .Python *.log docker-compose.yml Dockerfile geckodriver.log golog.py golog.pyc log.html media out output.xml report.html startup.sh templates testlibs .dockerignore well, at this point i run: docker-compose build --no-cache at the end image was build correctly, but when i run: docker-compose up system return this error: web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory core_web_1 exited with code 2 Someone can help me about the issue? so many thanks in advance -
How to update selected fields in a model if the entry exists?
I am trying to update two fields in my models if the entry exists. If Campaign History exists, I want to update the call_cost and call_duration fields. I tried using check = CampaignHistory.objects.get(pk=campaign_id) But this raises an error since the CampaignHistory does not exist yet. # models.py class CampaignHistory(models.Model): """ Model to store Campaign History """ campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) call_duration = models.IntegerField() call_cost = models.DecimalField(max_digits=10, decimal_places=6) # views.py def events(request, campaign_id): campaign = Campaign.objects.get(pk=campaign_id) account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) sid = request.GET.get('CallSid', default=None) detail = client.calls(sid).fetch() print("SID:{}\nCampaign:{}\nDuration:{}\nPrice:{}" .format(sid, campaign, str(str(detail.duration)+'s'), str(detail.price)[1:])) check = CampaignHistory.objects.get(pk=campaign_id) # this raises the error if check does not exists how do I fix this? if check: old_cost = check.call_cost new_cost = old_cost + float(detail.price) old_duration = check.call_duration new_duration = old_duration + int(detail.duration) check.call_cost = new_cost check.call_duration = new_duration check.save() else: campaign_history = CampaignHistory(campaign=campaign, call_duration=str(str(detail.duration) + 's'), call_cost=str(detail.price)[1:]) campaign_history.save() return render(request, "CallCenter/events.html") -
Python or PHP for a long term social media site? [on hold]
So I'm planning to build a social media network I'm familiar with PHP but I just thought about python is it more suitable than PHP for a long term project? or should I stick with PHP???? -
How to place Bokeh widgets precisely on an html page
I am struggling to place Bokeh widgets precisely where I want them on an html page built with Django. For example my views.py look like this: from bokeh.io import show from bokeh.layouts import column, row from bokeh.models import CustomJS, TextInput from bokeh.plotting import figure fig = figure(title='title') fig.line(x=[1,2,3], y=[1,2,3]) text_input = TextInput(title="Add graph title", value='') text_input.js_on_change('value', CustomJS( args={'title': fig.title, 'text_input': text_input}, code="title.text = text_input.value" )) widgets_layout = column(text_input) figures_layout = row(fig) #show(row(widgets_layout, fig)) # Set up page layout page_layout = row(widgets_layout, figures_layout) script, div = components(page_layout) return render_to_response('app/test.html', {'script':script, 'div':div}) and my html page (test.html) look like this: <!--Test page--> {% extends "base.html" %} {% load static %} {% load bootstrap4 %} {% load i18n %} {% block content %} <!--Bokeh--> <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script> <!--Figure--> <div class='col-lg'> <div class='card-lg bg-light' id='maincontent'> <h2> {% trans "Test" %}</h2> <hr> <div> {{ div | safe }} {{ script | safe }} </div> </div> </div> <br> {% endblock content %} Now, how can I move the little widget (text_input) to a precise position ? Any position will do, I just want to be able to place it pretty much … -
django: how to substract hours from datetime if both values are in fields?
qs = Model.objects.annotate(foo=F('datetime') - F('hours') * 3600) ^ throws an error about fields mismatch. How to tell django to tell DB that hours is an interval (time delta)? -
Docker-Compose can't connect to MySQL
I'm trying to connect Django project with MySQL using docker. I have the problem when upping docker-compose. It says the next error: I'm using port 3307, should i create first new database schema in my local? Or how can I do it because my default port is 3306 but if i try to use it, it says that is busy. My code here: Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 ENV LANG=C.UTF-8 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN apt-get update RUN pip install -r requirements.txt ADD . /code/ Docker-compose version: '2' services: app: container_name: container_app build: context: . dockerfile: Dockerfile restart: always command: bash -c "python3 manage.py migrate && python manage.py shell < backend/scripts/setup.py && python3 manage.py runserver 0.0.0.0:8000" links: - db depends_on: - db ports: - "8000:8000" db: container_name: container_database image: mariadb restart: always environment: MYSQL_ROOT_HOST: 'host.docker.internal' MYSQL_DATABASE: 'container_develop' MYSQL_USER: 'root' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' ports: - "3307:3307" settings.py: DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_develop', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 3307, 'CHARSET': 'utf8', 'COLLATION': 'utf8_bin', 'OPTIONS': { 'use_unicode' : True, 'init_command': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', }, } } -
Django Throttling Not Working on Production mode
I'm using DJANGO REST FRAMEWORK to protect my API. Django Throttling that limits the number of requests on an API for Anonymous and authenticates Users. The throttling is not working on production mode. By the way, I'm using Ubuntu and Nginx server for deploying my site. I use two way but both didn't work for me. Here are the codes. Please help me. I'm noob in django. 1st Method, Which I use is described below. Views.py class SustainedAnon(AnonRateThrottle): rate = '100/day' class BurstAnon(AnonRateThrottle): rate = '10/minute' class SustainedUser(UserRateThrottle): rate = '100/day' class BurstUser(UserRateThrottle): rate = '10/min' class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin): lookup_field= 'puid' serializer_class = ProductApisSerializers """ Provides a get method handler. """ # permission_classes = (IsAuthenticated,) throttle_classes = (SustainedAnon,SustainedUser,BurstAnon,BurstUser) def get_queryset(self): return ProductApis.objects.all() def post(self, request,*args,**kwargs): return self.create(request, *args, **kwargs) URLS.PY from django.contrib import admin from django.urls import path, include from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('',views.index, name='index'), path('api/<slug:puid>/',views.ProductApi.as_view()), ] 2nd Method- DRF Views.py class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin): lookup_field= 'puid' serializer_class = ProductApisSerializers """ Provides a get method handler. """ # permission_classes = (IsAuthenticated,) throttle_classes = [UserRateThrottle,AnonRateThrottle] def get_queryset(self): return ProductApis.objects.all() def post(self, request,*args,**kwargs): return self.create(request, *args, **kwargs) settings.py REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], … -
How to convert form field data before saving to database in a Django ModelForm?
I'm creating an "edit" page in Django python framework (template 'edit_page.html') where user should be able to edit existing data stored in a database. For now I can easily retrieve existing raw data in user form (a Django template), my issue is that I need to convert data populated by user before saving the form. I have an 'ipv4' field in my model mapping a database table column with IPv4 addresses stored as unsigned int. For instance ip address '10.0.0.0' is stored as 167772160 in the database. Data conversion for 'ipv4' could be implemented as follows (exemple): # Convert from raw database to human friendly format (167772160 -> 10.0.0.0) import ipaddress ipv4_raw = 167772160 ipv4_friendly = str(ipaddress.ip_address(ipv4_raw)) print(ipv4_friendly) # Output: 10.0.0.0 # Convert from human friendly format to raw database format (10.0.0.0 -> 167772160 ) import ipaddress ipv4_friendly = '10.0.0.0' ipv4_raw = int(ipaddress.ip_address(ipv4_friendly)) print(ipv4_raw) # Output: 167772160 My form needs to show human friendly 'ipv4' to the user but must have the capability to update the database column in 'raw' format (int). 'ipv4' must be converted from raw format to user friendly format for display and the other way around for database update. Where should I perform this operation and … -
How to edit model objects in an inline formset in Django
In Django I am trying to use an inline formset factory so a user can edit instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying don't save the changes I make when I click submit. My view is like this (not including render): def edit_sets(request, exercisegroup_id): exercisename = ExerciseName.objects.get(pk=exercisegroup_id) SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',)) formset = SetLoggerFormSet(instance=exercisename) if request.method == 'POST': formset = SetLoggerFormSet(request.POST, instance=exercisename) if formset.is_valid(): formset.save() else: formset = SetLoggerFormSet(instance=exercisename) and I am displaying each form in the formset in my template so the user can individually edit the instance: <form method="post">{% csrf_token %} {{ formset.management_form}} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <button type="submit" class="save btn btn-default">Save set</button> </form> Stuck as to why this isn't working. The form displays as it should and this method has previously worked for adding objects, but I am still unable to use it to replace one of those objects in the queryset. Am I missing something I should be doing differently? -
Cant update custom model using custom form in Django
I've two models and I want to update them at the same time with one submit button. First model is User which is from contrib models and default. Second model is UserProfile which has OneToOneField with user. Im making instance of both and rendering both forms at same time. When I update, one one instance (User) is updating, my custom model userprofile is not updating. Sorry im new and have been figuring out what is wrong in my code. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import UserProfile from django.contrib.auth.forms import UserChangeForm class EditProfileForm(UserChangeForm): class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password') class EditProfileForm2(forms.ModelForm): city = forms.CharField() description = forms.CharField() phone = forms.IntegerField() class Meta: model = UserProfile fields = ('city','description','phone') def save(self, commit=True): user = super(EditProfileForm2, self).save(commit=False) user.city = self.cleaned_data['city'] user.description = self.cleaned_data['description'] user.phone = self.cleaned_data['phone'] if commit: user.save() return user Views.py from django.shortcuts import render, redirect from .forms import RegistrationForm, EditProfileForm, EditProfileForm2 from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash def edit_profile(request): if request.method == 'POST': form = … -
Problem with Django: No module named 'myapp'
Good afternoon, I'm new to Django and I'm trying to follow a tutorial. However, when running the server, the following error pops up: File "C:\Users\Jorge\PycharmProjects\web\mysite\mysite\urls.py", line 18, in <module> from myapp.views import * ModuleNotFoundError: No module named 'myapp' This is a screenshot about how my files are right now: enter image description here -
Looking for a Admin Theme For an ERP Project
I am going to start a new Project in Laravel it would be a whole solution for a School ERP & many integrated systems. So can some suggest me a decent good looking / simple bootstrapped based premium admin theme. Thanks in adva -
Django ignore_conflicts doesn't work for User model
I am trying to create a lot of users for testing my Django application. I've used this method on other models and it works, but here it doesn't. When executed it states the error below. The latest Django version (2.2.6) was used. The documentation states: (...) setting the ignore_conflicts parameter to True tells the database to ignore failure to insert any rows that fail constraints such as duplicate unique values. My Code: def draftUser(i): return User(username='Testguy' + str(i), first_name=randomString(7), last_name=randomString(5)) user_cache = [] for i in range(1, 10000): user_cache(draftUser(i)) User.objects.bulk_create(user_cache, ignore_conflicts=True) The last line of the error code: django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username -
Django rest framework - Creating and returning multiple instances of an object instead of one
What I'm doing is posting a list of primary keys with other data to an endpoint and I'm creating an instance of an object per id that is in the list. The problem is that I want to then return all the objects I created but only one instance of the object is expected so it doesn't work. The data I'm posting to /convo/:id/members/ looks like this: { member_ids = [5,1,2,6] } Then in the view I'm passing the current user to my serializer (needed for the object I'm creating because it has an added_by field. I'm doing this by overriding perform_create. It looks ca like this: def perform_create(self, serializer): serializer.save(added_by = self.request.user) Then I'm overriding the create method in the serializer, take each id in the data received and create a member in the conversation. This is how that looks like ca (pseudocode) def create(self, validated_data): added_by = validated_data.pop('added_by') users = validated_data.pop('member_ids') added_members = [] for u in users: added_members.append(ConvoMember.objects.create(convo = x, user = u, added_by = added_by)) return added_members // this fails because its expecting only one instance of ConvoMember // but i still need to be able to do this somehow. How do I go about returning … -
Reverse foreign key relation in Django ORM
How to return all objects instances of a particular model that are being addresed as Foreign key by ANY object instance of a different model ? Lets say there is a model Item and a model ItemRequested that has foreign key relation to Item. How to print all Items that are being mentioned as foreign key in the ItemRequested table/model ? basically this is the SQL query that i want to execute in Django: select * from backend_item where id in (select id from backend_itemrequested); Obviously i want to avoid executing raw SQL commands from inside Django ORM -
Django Admin: How do I serialize data and store it in a model so that it can be restored by the user?
So what I have so far is a model called Registration and a model called Deleted Registration. I overrode the deleted_selected admin action for Registration so that instead of deleting the query, it would make Deleted Registrations. The thing is, it only saves the most important parts. Registrations have a few foreign keys and one-to-one fields. Apparently just saving the most important data isn't good enough and we want to serialize all the data in the selected registration models and store it with the deleted registration. This way, when you select a few deleted registrations, you can click on Restore deleted registrations I'll reiterate what I want so it's a little but more clear: I want to be able to "delete" registrations, where a new deleted registration is created. This way, they can view deleted registrations and, if need be, restore them. Here is the registration model: class Registration(models.Model): objects = RegistrationManager() # Used to identify this object securely in urls without giving the actual primary key uuid = models.UUIDField(default=uuid.uuid4, editable=False) sibs_event = models.ForeignKey("EventInstance", null=True, blank=True) date_registered = models.DateTimeField(auto_now_add=True) # sibs event for this registration sibs_weekend = models.ForeignKey(SibsWeekend, null=False) payment_delegation = models.OneToOneField("PaymentDelegation", null=True, blank=True, related_name="registration", on_delete=models.SET_NULL) Here is the deleted … -
Change ModelChoiceField Initial Value dynamically dependent on user selection
I have three ModelChoiceFields. After the user has set a value in the first checkbox (level), the initial value of the other two checkboxes should change. Views.py def index(request): form = SettingsForm() context = { 'form' : form } return render(request, 'app/settings.html', context) settings.html <form method="post"> {% csrf_token %} <table> {{ settings_form }} </table> <button type="submit" class="button">Apply</button> </form> forms.py class SettingsForm(forms.ModelForm): class Meta: model = Setting fields = '__all__' level = forms.ModelChoiceField( widget = forms.Select, queryset = Level.objects.all() ) language = forms.ModelChoiceField( widget = forms.Select, queryset = Language.objects.all(), initial = 0 ) country = forms.ModelChoiceField( widget = forms.Select, queryset = Country.objects.all() ) # I know I can do something like this in __init__: # self.fields['language'].initial = Language.objects.filter(level=self.level).first() # but that is not dynamically Example User selects level = 2, so language.initial should be set to 'German' and county.initial to 'Germany'. If user selects level = 1, so language.initial should be set to 'English' and county.initial to 'USA'. Can one of you guide me to this goal? -
Group list by specific key in that list
I have the following QuerySet result as a list: <QuerySet [{'answer__question__focus': 'hearing_about_the_event', 'name': 'Facebook', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'Instagram', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'friends', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'missing_event_information', 'name': 'Line-up', 'count': 2, 'total_salience': 2.0}, {'answer__question__focus': 'missing_event_information', 'name': 'food', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'reason_for_attending', 'name': 'girlfriend', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'type_of_people_attending', 'name': 'incomes', 'count': 3, 'total_salience': 2.26287645101547}, {'answer__question__focus': 'type_of_people_attending', 'name': 'people', 'count': 1, 'total_salience': 1.0}]> I now attempt to group this result in my Django application by answer__question__focus with Python. However, I struggle to get my data in the right order/format. Does anyone know how to do so in an efficient way? [ 'hearing_about_the_event': # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 4, 'salience': 3.434 }, { 'name': 'titanic', 'count': 5, 'salience': 1.12 }, { 'name': 'music', 'count': 3, 'salience': 1.12 } ], 'missing_event_information': # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 5, 'salience': 1.5 }, { 'name': 'titanic', 'count': 4, 'salience': 1.12 }, { 'name': 'music', 'count': 2, 'salience': 1.12 } ] ] -
Django framework python
I'm making a registration system for students in Django When the user enters the student number, the system retrieves all the student data. How can I work in this def search(request): if request.method== 'POST': srch = request.POST['srh'] if srch: match = Regiest_Form.objects.filter(Q(std_name__iexact=srch)) if match: return render(request, 'Regiest_app/search.html', {'sr':match}) else: messages.error(request,'no result') else: return HttpResponseRedirect('/search/') else: return render(request, 'Regiest_app/search.html') -
Need to add images and text in a single box in Django
I am currently working on creating a fully functioning blog app in Django, but at the moment, I seem lost on how to create a functionality whereby users can use a single textbox to add images, text and videos without creating separate models, which can then be formatted properly using spaces. An example of what I mean is the textarea in Wordpress where all you have to do is type or copy in your text, upload images and videos and format them using the space bar. -
How to display dynamic django data from views in html?
I have three django models: ProjectName,TaskBudget and TaskActualCost. ProjectName stores the project name (ie Project X). BudgetName stores the project_name(as a foreign key(FK)),budget_name and the total_budget and date for each task ie (Project X, Hotel,600),(Project X, Rental,500). '600' refers to $600. TaskActualCost stores each cost as it is incurred(itemized costs) (ie Hotel: 100, Rental: 50, Food:100) and its date. So it stores the 'task_name'(as FK),'budget_name'(as FK),actual_amount_used and date. ie (Project X,Hotel,100,10/03/2019),(Project X,Hotel,100,10/06/2019), (Project X,Rental,50,04/10/2019) I'm trying to render the 'Task Name', 'Task Budget' and 'Task Actual Cost' in an html table. 'Task Name' and 'Task Budget' are rendering correctly,but 'Task Actual Cost' only displays one amount for all cost item. Models: class ProjectName(models.Model): project_name = models.CharField('Name',max_length = 15,blank = False) def __str__(self): return self.project_name class TaskBudget(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) budget_name = models.CharField('Budget Name'max_length = 50 total_budget = models.DecimalField('Total Budget',max_digits = 9,decimal_places=2) def __str__(self): return self.budget_name class TaskActualCost(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) cost_description = models.ForeignKey(ProjectCost,on_delete = models.CASCADE,null=True) actual_used = models.DecimalField('Actual Used',max_digits = 15,decimal_places = 2) Views: def budgetview(request,project_id): budget_items = TaskBudget.objects.filter(project_name_id = project_id) for budget in budget_items: budget_id = budget.id actual_cost = TaskActualCost.objects.filter(cost_description_id=task_budget_id).aggregate(Sum(' actual_used')).get('actual_used__sum') or 0 print(budget.cost_description,":",actual_cost)#To test the output on StatReloader … -
Django send authenticated user to another django server with the same db
I know question sounds strange, I will explain it here. I have two Django servers which share the same DB. One is a light front/back server and the order one takes the heavy computing part. They share the same database. I am currently securing the web, and I have a couple of views in the light server requiring user login: @login_required() @permission_required('auth.can_upload', login_url='/accounts/login/') This works nicely in the light server since the user is authenticated (request.user returns a valid user in the views). The problem comes when I have to send the uploaded data to the other server since it is protected as I showed earlier, I do not know how to pass it the user that is already logged (user is valid since servers share the DB). # send an upload request using requests s = requests.Session() r1 = s.get(upload_process_url) csrf_token = r1.cookies['csrftoken'] a = s.post(upload_process_url, files=request.FILES, data={'csrfmiddlewaretoken': csrf_token}, headers=dict(Referer=upload_process_url)) I cannot ask every time the user and password or save them. The thing is I want to pass the user that is already logged in a request. The user was logged using the default django accounts/login page and authentication. Any clues and what could I try? I think … -
Log SQL queries even if DEBUG=False
This is my logging config in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'App': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, }, } There's a behavior that I can't explain: if I run with debug=True I can see all SQL queries being logged to the console, but when debug=False that doesn't happen, even if I don't change the configuration above. Why is this? How can I control in my logging config wether or not SQL queries are logged to the console? -
Django - Admin - Add link in a change_form that redirect to another change_form - set field with a value
I have open a post dealing with this subject but had no answer... to resume: I have a form #1 with a link when I click on this link, a new form #2 with a sub-form open now, I would like a field of the form #2 (open after clicking on the link of form #1) to be pre-filled with a value that come from the form #1 all this take place in the admin part of Django admin.py from django.contrib import admin from .models import Participante, Visite, Inclusion, BilanBiologique, ExamenBiologique class ExamenBiologiqueInline(admin.TabularInline): model = ExamenBiologique extra = 0 class BilanBiologiqueAdmin(admin.ModelAdmin): inlines = [ExamenBiologiqueInline,] class BilanBiologiqueLinkInline(admin.TabularInline): readonly_fields = ('examen', ) model = BilanBiologique extra = 0 fields = ('bio_ide', 'vis', 'bio_dat',) class VisiteAdmin(admin.ModelAdmin): inlines = [BilanBiologiqueLinkInline,] class InclusionAdmin(admin.ModelAdmin): readonly_fields = ('examen',) model = Inclusion fields = ('vis',('inc_tdr','examen'),) admin.site.register(Participante) admin.site.register(Visite, VisiteAdmin) admin.site.register(BilanBiologique, BilanBiologiqueAdmin) admin.site.register(Inclusion, InclusionAdmin) models.py from django.db import models from django.urls import reverse from django.utils.safestring import mark_safe from django.core.validators import RegexValidator class Participante(models.Model): pat_ide = models.AutoField(primary_key=True) pat_ide_prn_cse = models.CharField("Identifiant Princesse", max_length=14, validators = [ RegexValidator( regex='^SP[M|F][0-9]{11}$', message= 'L\'identifiant doit être au format requis', code='invalid_participant_id' ), ], unique=True ) pat_inc_dat = models.DateField("Date d'inclusion") def __str__(self): return f"{self.pat_ide_prn_cse}" class Visite(models.Model): vis_ide = …