Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can multiple Django `bulk_update` queries be part of single atomic transaction?
Can multiple Django bulk_update queries be part of a single atomic transaction? Usually when we want to save multiple models in single atomic transaction we can do something like this: def my_update(model_a, model_b, model_c, model_d): with transaction.atomic(): model_a.save() model_b.save() model_c.save() model_d.save() Similarly I want to update a bulk set of models in single atomic transaction, like so: def my_bulk_update(models_a, fields_a, models_b, fields_b, models_c, fields_c, models_d, fields_d): with transaction.atomic(): Model_A.objects.bulk_update(objs=models_a, fields=fields_a) Model_B.objects.bulk_update(objs=models_b, fields=fields_b) Model_C.objects.bulk_update(objs=models_c, fields=fields_c) Model_D.objects.bulk_update(objs=models_d, fields=fields_d) Digging around the bulk_update code I found the following snippet: with transaction.atomic(using=self.db, savepoint=False): for pks, update_kwargs in updates: rows_updated += self.filter(pk__in=pks).update(**update_kwargs) It shows the updates are done within an atomic transaction. It means the my_bulk_update has nested atomic transaction and I'm not aware what the behaviour would be. So some queries I have regarding this are: Is my_bulk_update atomic? What is the behaviour of the nested transaction? Could the using=self.db mean that nested transactions be ignored? -
Using pyarmor to obfuscate multiple tornado apps
Try to obfuscate a project using pyarmor written in tornado with multiple apps. For a single app with the following structure, it was quite easy to obfuscate using pyarmor . ├── apps │ ├── __init__.py │ └── app.py # show below └── handler ├── __init__.py └── myhandler.py # apps/app.py import tornado.ioloop import tornado.web from handler import MainHandler def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) app = make_app() server = tornado.httpserver.HTTPServer(app) server.bind(8888) # port server.start(1) tornado.ioloop.IOLoop.instance().start() Just using the following command, where apps/app.py is the entry point for the tornado app cd /myproject pyarmor obfuscate --src="." -r --output=/path/tp/obs_site apps/app.py Then we get the output folder which is an obfuscated project ready to be distributed. The start-up script is as the same before: python apps/app.py to start the tornado server. Unfortunately, things become more complicated when dealing with multiple apps. Due to legacy reasons, components such as handlers and routes are not well organized and separated in different folders, due to the complexity of the whole project, it is infeasible to change the whole project structure for now. Any ideas on how to obfuscate a project with dozens of apps below(2 apps for example) with the following structure, thanks in advance! . … -
Django: Is there anyway to specify a django url path for a template of the item currently being iterated in a forloop
I have a simple unordered list of entries that have been iterated over a Django forloop like this. <ul> {% for entry in entries %} <li>{{ entry }}</li> {% endfor %} </ul> However, I wanted to make all of the listed items in the forloop to be links to a template html file. Which brings the question, is there a way to format my code to where the URL pathway can take the name of the entry to link it to the desired template for it? Something like this. <ul> {% for entry in entries %} <li><a href="{% url 'encyclopedia/{{ entry }}' %}">{{ entry }}</a></li> {% endfor %} </ul> obviously this code doesn't work, but is there something similar that I can do? Heres my urls.py and views.py for more information. urls.py path("<str:TITLE>", views.TITLE, name="TITLE") views.py def TITLE(request, TITLE): # util.markdownify(f"{TITLE}.html", f"{TITLE}.md") return render(request, f"encyclopedia/{TITLE}.html") -
What is the best practice to embed a NodeJS module in a Python project?
I am doing a small Python web project based on Django for which I need to use a module, which is written in JavaScript for NodeJS (Ulixee Hero). The NodeJS module would need to run server-side and be controlled by the Python-based implementation of the server app. Apparently, there once was a Python package to run JavaScript code (PyExecJs), which, however, is discontinued. Given that I'm experienced with Python, but have only few experiences with JavaScript, and none with NPM or NodeJS, what is a good way to start? What is a good way to structure the Django project, given that there will be this NodeJS module? How to implement the interface between Python and the NodeJS module? I was hoping to find a guide, but it looks like this use case is rather exotic. To what I have read so far, it looks like a good approach to run the NodeJS code using a subprocess. Are there better alternatives? What is the preferred way of installing NodeJS in this situation? My first goes was to use Pip, but the NodeJS version in pip is outdated and discontinued. -
How to pass a parameter to Class based views in Django?
how to pass this parameter in the class called? This is url #url path('all-agency/<int:id>', AllAgenciesView.as_view(), name='all-agency'), cbv #views class AllAgenciesView( TemplateView): template_name='agencies.html' class AllAgenciesListView(ServerSideDatatableView): def get_queryset(self): agencies = SettingsAgency.objects.using('agency-namespace').filter(id=self.kwargs['id']) return agencies this is in template #in anchor tag(html) <a href="{% url 'all-agency' id=2 %}" ><div>Agencies</div></a> in address bar it would look like this: http://127.0.0.1:8000/all-agency/2 Now I want to pass the 'id' into the class based views but when i did filter(id=self.kwargs['id'). I Got returned KeyError: 'id' i tried another way which is filter(id=self.kwargs.get('id')) and it returned None when i print(agencies) another way ive tried filter(id=self.request.GET.get('id')) this also returned the same None -
How to send link include id in email user in django?
please i need to help i send this lien http://127.0.0.1:8000/benevole/demande_participer/id:?/ in email user but id is not Read in email Thanks in advance ---this is the urls.py path('benevole/demande_participer/<int:id>', views.demande_participer, name='demande_participer'), ------ this is views.py => def demande_participer(request,id): participers=Mission.objects.get(id=id) benParticiper=User.objects.filter(username=request.user) template=render_to_string('Association/email_template.html') email=EmailMessage( 'Veuillez confirmer votre participation a la mission proposer',#header message template, # h1 settings.EMAIL_HOST_USER, [request.user.email], ) email.fail_silenty=False email.send() ---this is email_template.html {% load crispy_forms_tags %} {% block content %} Confirmé la Participation http://127.0.0.1:8000/benevole/demande_participer/id:?/ {% endblock %} -
What is the best frontend framework can use with Django? and How learn it separately? [closed]
Django | frontend framework (?) -
Django MultipolygonField don't display map when map has polys
In Heroku don't display map when edit/update polys Heroku. But when I backup the database in docker the map is displayed without trouble Docker. Heroku has the next configuration: Stack 22 GDAL 3.5.0 Python 3.9.13 Django 1.11.25 And docker has: GDAL 2.4.0 Python 3.9.13 Django 1.11.25 The problem is the buildpack (heroku-geo-buildpack) or something else? The code of that field is: models.MultiPolygonField( pgettext_lazy("Store service field", "polygons"), geography=True, null=True, blank=True ) -
in django how to return the object without saving in the database just ceate at runtime and give in response
from django.shortcuts import render import requests from bs4 import BeautifulSoup from home.models import MetaData,project def extractURL(request): if request.method == "POST": # Making a GET request url = request.POST.get('url') varProj = project.objects.get(id=1) r = requests.get(url) soup = BeautifulSoup(r.content,"html.parser") print(soup.find_all('loc')[0].text) res = soup.find_all('loc') resArr = [] for x in res: resArr.append(x.text) for y in resArr: getPage = requests.get(y) tempSoup = BeautifulSoup(getPage.content,"html.parser") print(tempSoup.find_all('title')[0].text) print(tempSoup.find_all('meta',attrs={"name":"description"})) x = MetaData.objects.create(title=tempSoup.find_all('title')[0].text,description=tempSoup.find_all('meta',attrs={"name":"description"}),url=y,project=varProj) x.save() # print(tempSoup.find_all('meta',attrs={"name":"keywords"})) # resObjArrary.append(MetaData(tempSoup.find_all('title')[0].text,tempSoup.find_all('meta',attrs={"name":"description"}),y)) # resObjArrary[count] = MetaData(tempSoup.find_all('title')[0].text,tempSoup.find_all('meta',attrs={"name":"description"}),y) # print(tempSoup.find_all('description')[0].text) # soup = BeautifulSoup(r) resObj = MetaData.objects.filter(project=varProj) context = { "res":res, "resObj":resObj } # print(soup) return render(request,"index.html",context) With this piece of code I am getting a sitemap url and then iteration over that after the iteration i am creating metaData of the page saving in my database then return which I can iterate in my frontend now I want is three any way by which I can send the object without saving send the object just at the run time -
Docker Environment File in Image not found by Decouple
so i've been trying to deploy a Django App using Docker, but I can't successfully make it work. Here's the error i'm encountering: I'm using Decouple to manage Environment Files and "broker_url" is a variable inside the .env When I try reading the .env file from the file that accesses it, it's able to print it properly -- here is the code for printing the content of the env -- here is the content of the log -- here is the list of all the files in the directory what do i do to make Decouple see that the .env has the 'broker_url' variable? -
What are steps necessary to deploy django application to make it live using apache server?
I am host my locally build django app into live server in Digital Ocean using public IP. My VM is debian based. What i did is: Copy my "attendance" project into /var/www/. I created new conf file in: /etc/apache2/sites-available/attendance.conf. I enable it and disable 000-default.conf. In attendance.conf I put code like: <VirtualHost *:80> ServerAdmin admin@143.244.134.97 ServerName 143.244.134.97 ServerAlias 143.244.134.97 DocumentRoot /var/www/attendance ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I enable apache 2 also. When I go to the browser I view only the files. It is like: [image seen in browser][1] Do I didn't edit properly for wsgi setup in apache2>(application.conf). OR What are the other possible solution to make my site live? -
Django | Page not found (404) No Cars matches the given query
I tried to create a form for creating a new article on the site, but this error came out. I've rechecked everything 10 times, but I don't understand what the error is. hello/urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.index, name='hello'), path("cars/<slug:car_slug>/", views.car_slug, name='car_slug'), path('cars/addpost/', views.addpost, name='addpost') ] hello/views.py : from django.shortcuts import get_object_or_404, render, redirect from .models import * from .forms import * def index(request): data = {} return render(request, 'hello/index.html', data) def car_slug(request, car_slug): car = get_object_or_404(Cars, slug=car_slug) data = { 'car': car } return render(request, 'hello/car_pk.html', data) def addpost(request): if request.method == 'POST': form = AddPostForm(request.POST) if form.is_valid(): Cars.objects.create(**form.cleaned_data) return redirect("hello") else: form.add_error(None, "Ошибка добавления поста") else: form = AddPostForm() data = { 'form': form, 'title': 'Добавление поста' } return render(request, 'hello/addpost.html', data) hello/forms.py: from django import forms from .models import * class AddPostForm(forms.Form): title = forms.CharField(label='Название', max_length=300) slug = forms.SlugField(label='URL', max_length=40) content = forms.CharField(label='Характеристика', widget=forms.Textarea(attrs={'cols':60, 'rows': 10})) is_published = forms.BooleanField(label='Состояние', required=False, initial=True) brand = forms.ModelChoiceField(queryset=Brands.objects.all(), label="Бренды", empty_label='Не выбрано') hello/models.py : from django.urls import reverse from django.db import models class Cars(models.Model): title = models.CharField(max_length=255, verbose_name="Название") slug = models.SlugField(verbose_name="URL", unique=True, db_index=True, max_length=255) content = models.TextField(verbose_name="Характеристика", null=True) time_create = models.DateField(verbose_name='Дата публикации', auto_now_add=True) … -
module 'django.contrib.messages.constants' has no attribute 'error'
I was working on my django project and everything seemed fine, until I simply wanted to login, and I found this error: module 'django.contrib.messages.constants' has no attribute 'error' The code that is responsible for this has not been touched for at least 2 months! Here is the view: from django.contrib.auth import authenticate from django.conf.settings import * from django.contrib import messages # Connexion def loginview(request): if request.method == 'POST': usr = request.POST.get('email_kw') pwd = request.POST.get('pwd_kw') user = authenticate(request, username=usr, password=pwd) if user is not None: login(request, user) logger.info(f"Connexion de {request.user}") return redirect("dashboard") else: messages.error(request, "Erreur: Nom d'utilisateur ou mot de passe incorrects, veuillez réessayer.") # this is the line that causes the problem logger.error(f'Connexion de {request.user} echouee') return render(request, 'core/login.html', {'page_title': 'Se connecter'}) if request.user.is_authenticated: return redirect("dashboard") return render(request, 'core/login.html', {'page_title': 'Se connecter'}) -
Django "extra_context" not being passed to form renderer when using FormView
Django version 4.1 When I pass "extra_context" to my class-based view, it seems to get filtered out before being passed to the form renderer. In the stack trace below you can see that the context item 'svg': {'id_batch': 'number'} appears in the call of str(value), but it is no longer present in mark_safe(renderer.render(template, context) The same issue is present if I use a CreateView instead. Below are snippets of the relevant files: # settings.py # All of my forms are rendered with this same html snippet from django.forms.renderers import TemplatesSetting class CustomFormRenderer(TemplatesSetting): form_template_name = "form_snippet.html" FORM_RENDERER = "project.settings.CustomFormRenderer" # forms.py from django.forms import ModelForm from .models import Upload class UploadForm(ModelForm): class Meta: model = Upload fields = ['batch'] # views.py from django.views.generic import FormView from .forms import UploadForm class MeasurementView(FormView): # default template will be 'assays/upload_form.html' template_name = 'assays/upload_form.html' form_class = UploadForm extra_context = {'svg': {'id_batch': 'number'}} -
Building a USSD menu with Django
Am building a USSD web app with Django and am using the API https://documenter.getpostman.com/view/7705958/UyrEhaLQ#intro I am having a problem sending response and getting the menu displaying on upon dialing the USSD code. @csrf_exempt def ussd(request): if request.method == 'GET': html = "<html><body>Nothing here baby!</body></html>" return HttpResponse(html) elif request.method == 'POST': url = "https://99c9-102-176-94-213.ngrok.io/ussd" code_id = request.POST.get("USERID") serviceCode = request.POST.get("MSISDN") type = request.POST.get("MSGTYPE") session_id = request.POST.get("SESSIONID") text = request.POST.get("USERDATA") MSG = "" if text == "": MSG = "Welcome To Votedigital" elif text == "1": MSG = "Test Two" payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type, "USERDATA": text, "SESSIONID": session_id, "MSG": MSG, } headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) print(code_id) print(response.text) return HttpResponse(response) When i check my post summary, the elements are empty { "USERID": null, "MSISDN": null, "MSGTYPE": null, "USERDATA": null, "SESSIONID": null, "MSG": "" } -
Poetry install doesn't seem to install the packages in the right place
So I'm having a problem for quite some time which I cannot get solved. Basically I took over a project which uses Poetry for package managing (It is a Django project). Adding packages with 'poetry add' and then installing them via 'poetry install' all works fine locally (I use a Docker container). But when pushing the changes to my server and then running 'poetry install' it says the packages are already installed. But when running the Django application, I get an internal server error saying the package doesn't exist. An example is given with the 'openpyxl' package. pyproject.toml ... [tool.poetry.dependencies] openpyxl = "^3.0.10" ... poetry.lock ... [[package]] name = "openpyxl" version = "3.0.10" description = "A Python library to read/write Excel 2010 xlsx/xlsm files" category = "main" optional = false python-versions = ">=3.6" [package.dependencies] openpyxl = {version = ">=2.6.0", optional = true, markers = "extra == \"xlsx\""} [package.extras] all = ["markuppy", "odfpy", "openpyxl (>=2.6.0)", "pandas", "pyyaml", "tabulate", "xlrd", "xlwt"] cli = ["tabulate"] html = ["markuppy"] ods = ["odfpy"] pandas = ["pandas"] xls = ["xlrd", "xlwt"] xlsx = ["openpyxl (>=2.6.0)"] yaml = ["pyyaml"] openpyxl = [ {file = "openpyxl-3.0.10-py2.py3-none-any.whl", hash = "sha256:0ab6d25d01799f97a9464630abacbb34aafecdcaa0ef3cba6d6b3499867d0355"}, {file = "openpyxl-3.0.10.tar.gz", hash = "sha256:e47805627aebcf860edb4edf7987b1309c1b3632f3750538ed962bbcc3bd7449"}, ] ... error: … -
(1366, "Incorrect integer value: 'CargoEmpleado object (1)' for column 'cargo_empleado' at row 1")
I try to modify the cargo_empleado column of my empleado table with stored procedures, but I get an error: (1366, "Incorrect integer value: 'CargoEmpleado object (1)' for column 'cargo_empleado' at row 1") models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') views.py def asignarrol(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('cargo_empleado'): rolupdate= Empleado() rolupdate.rut=request.POST.get('rut') rolupdate.cargo_empleado=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) cursor=connection.cursor() cursor.execute("call SP_asignar_rol('"+rolupdate.rut+"','"+str(rolupdate.cargo_empleado)+"')") messages.success(request, "Al empleado "+rolupdate.rut+" se le asigno un rol ") return render(request, 'app/asignarrol.html') else: return render(request, 'app/asignarrol.html') SP CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_asignar_rol`(p_rut varchar(9),p_id_nuevo_cargo varchar(50)) BEGIN UPDATE Empleado SET cargo_empleado=p_id_nuevo_cargo WHERE rut=p_rut; END help me please!! -
Error when reverse url with multiple arguments - Django
I'm writing a test for an url, problem is it fails when I try to pass multiple arguments, here is some code: #test_urls.py from django.test import SimpleTestCase from django.urls import reverse, resolve from cardiotesting.views import * class TestUrls(SimpleTestCase): def test_new_cardio(id_patient, protocol): id_patient = '05' protocol = 'fox' url = reverse('new_cardio_testing', args=[id_patient, protocol]) print(resolve(url)) #urls.py from django.urls import path from . import views urlpatterns = [ path('new/<str:id_patient>', views.new_cardio_testing, name='new_cardio_testing'), ] #views.py def new_cardio_testing(id_patient, protocol): pass When I run the test it returns: .E ====================================================================== ERROR: test_new_cardio_testing (cardiotesting.tests.test_urls.TestUrls) ---------------------------------------------------------------------- TypeError: TestUrls.test_new_cardio_testing() missing 1 required positional argument: 'protocol' But when there is only one argument the test succeeds. Appreciate any help. -
How to import model from one app to another?
The issue I face: Error: ModuleNotFoundError: No module named 'CVBuilderApp.cvs' What I did: In my main app views file i.e, in the CVBuilderApp.views file views.py: from CVBuilderApp.cvs.models import PersonalInfo My project structure: CVBuilderApp - accounts - models, urls, views - cvs - models, urls, views - CVBuilderApp - settings.py - manage.py How do I import the model while the main application name and the project name are the same? Please help -
How to select related objects with only one query
Models: class Tag(BaseModel): tag_name = models.CharField(max_length=250) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.tag_name) super(Tag, self).save(*args, **kwargs) def __str__(self): return str(self.tag_name) class Tags(BaseModel): filtertype = models.CharField(max_length=250) tags = models.ManyToManyField(Tag) My current solution: def get(self,request,version): filtertype = request.query_params.get('filtertype', '') filtertypes = filtertype.split(",") tagsList = Tags.objects.filter(filtertype__in=filtertypes).values_list('tags', flat=True).distinct() queryset = Tag.objects.filter(id__in=tagsList) context = {"request": request} serialized = TagListSerializers(queryset, many=True, context=context) return Response(serialized.data) Im trying to get all the relevant Tag base on Tags/filtertype. Im wondering how can I do it with only one query. -
Django foreign key query returns records that are not in the database
I have a strange situation where Django seems to be giving me records that do not actually exist in the database when queried via a related_name on a foreign key. Here's a simplified example: Let's say I have a Person model and a Pet model, where each Pet has an owner, which is a foreign key on Person: class Pet(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name =models.CharField(max_length=50, null=False, db_index=True) owner = models.ForeignKey("Person", null=False, related_name="pets", on_delete=models.CASCADE) relationship = models.IntegerField(null=False, choices=PetRelationship.choices(), db_index=True) Now, I have the below function that retrieves a person's pets: def pet_tester(person): for pet in person.pets.filter(relationship=PetRelationship.FRIENDLY): pet_id = pet.id LOGGER.info(f"*************** pet.id = {pet_id}") LOGGER.info(f"******* Pet exists? = {Pet.objects.filter(id=pet_id).exists()}") ... Note that this is NOT a "minimal reproducible example". I can only reproduce it in my much larger application. For some reason (in the real app), the "exists" query is coming back as False. The output is like this: *************** pet.id = 123e4567-e89b-12d3-a456-426614174000 ******* Pet exists? = False If I query the actual database (Postgresql) directly (outside of Django), that pet ID sure enough does NOT exist. However, the person.pets.filter query is returning it just the same. I do not understand how this is even possible. It JUST retrieved the … -
celery for separate django docker microservices
I have 2 django microservices main_ms and Oms1_ms. the project name of both is config and both have these installed redis==4.3.4 celery==5.2.7 celery[redis]==5.2.7 both have celery.py. main_ms's is like this import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() and for Oms1_ms, instead of proj I have oms1_oms1 in both __init__.pys I have from .celery import app as celery_app __all__ = ('celery_app',) in both settings I have provided CELERY_BROKER_URL='redis://redis:6379/0' CELERY_RESULT_BACKEND='redis://redis:6379/0' from one of views I have in main_ms which calls the other celery from config.celery import app from rest_framework import views from rest_framework import status from rest_framework.response import Response class Oms1_Oms1ListView(views.APIView): def get(self, request, *args, **kwargs): remoteResponse = app.send_task('oms1_oms1.fun') print(remoteResponse) return Response({}, status=status.HTTP_200_OK) and in Oms1 app in Oms1_ms container in tasks.py I have from config.celery import app @app.task() def fun(): return 'as always!!' so when I run celery -A oms1_oms1 worker -l DEBUG command in Oms1 container I get this error Error: Invalid value for '-A' / '--app': Unable to load celery application. The module oms1_oms1 was not found. so how to set celery with django docker microservices correctly? where I have gone wrong? I also know one of celery uses is primarily to … -
Display the data of User role in Django Template
I have a django model with User roles. I want to be able to get the first_name, last_name and other details of a user role displayed other a template when another user role or the same user role is logged in. This is my models class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) #username = models.CharField(unique = False , max_length=100) #email = models.CharField(unique = True , max_length=100 ) nin = models.IntegerField(unique = False , null=True) avatar = models.ImageField(null= True, default="avatar.svg") is_landlord = models.BooleanField(default=False) objects = UserManager() REQUIRED_FIELDS= [] class Landlord(models.Model): user = models.OneToOneField(User,related_name="prop_owner", null= True, on_delete=models.CASCADE) bio = models.TextField(null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS= [] objects = UserManager() def __str__(self): return str(self.user) This is my views def propertySingle( request, pk, is_landlord, ): user = User.objects.get(is_landlord=is_landlord) property = Property.objects.get(id=pk) properties = Property.objects.all() images = Image.objects.filter(property=property) context = { "property": property, "properties": properties, "images": images, 'user':user, } return render(request, "base/page-listing-single.html", context) Template <div class="sl_creator"> <h4 class="mb25">Property Owned By:</h4> <div class="media"> <img class="mr-3" style="width: 90px; height:90px;" src="{{request.user.avatar.url}}" alt="avatar"> <div class="media-body"> <h5 class="mt-0 mb0">{{user.last_name}} {{request.user.first_name}}</h5> <a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.user.is_landlord.first_name}} -
How to export "down" on Django admin?
I need to export the author and each of his books, but the author just export the author. I managed to make the "book" maintainer export the author, but for every book it appears the author in every line. I have the "tabular in line" that means if I pick and author it shows every book in the admin page, so I know it's possible to do it but I don't know why, help! I have Author, Country and Book, and looks like this, models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) country = models.ForeignKey(Country, blank=True) The admin.py: admin.site.register(Book) admin.site.register(Country) class BookInline(admin.TabularInLine): model = Book max_num = 0 can_delete = False @admin.register(Author) class AdminAuthor(ImportExportActionModelAdmin): list_display = (name) inlines = [ BookInline, ] class Meta: model = Book It's not a many to many relationship, its one to many, so plis help me to make it look Something like this as a django admin action: +--- Author -----+ … -
Djnago-admin how to add extra Fields registrations in django-admin interface
In my web application, only the admin can register a user. I need to add extra fields to the registration form only in the djnago-admin interface, how can I do it, please?