Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Image Cropping in inlineFormsetFactory using cropper
I'm trying to make inline formset which one field gets chopped image as one of parameters. I have already done cropping with help of some tutorials but it works only with single model, when I tried to transform it to inline formset, new image is being saved in raw form - cropping isn't getting applied. tut I used: https://blog.pyplane.com/blog/how-to-crop-images-in-django-with-javascript/ models look like that: class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) availability = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) class Photo(models.Model): file = models.ImageField(upload_to=getImageURL2, default="static/default.png") uploaded = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields='__all__' class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file',) ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, can_delete=False, ) view def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': print(request.POST) form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") print(form.errors) print(form.non_field_errors()) context['form'] = form formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): for f in formset: imageset_obj = f.save() print("Successfully created new imagest: {}".format(imageset_obj)) return JsonResponse({'message': 'works'}) else: print(formset.errors) print(formset.non_form_errors()) context['formset'] = formset … -
sitemap.xml works on development but 404 errors on production
I've been following the documentation to add a sitemap to my website, everything works perfectly on development, once I upload to production, I have 404 errors as in sitemap can't be found. I checked the database on production to make sure the SITE_ID is the same as the pk of the site registered in database. This is my installed app in settings.py """ Django settings for icerd project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path from django.conf import global_settings # Add custom languages not provided by Django from django.conf import locale from django.utils.translation import gettext_lazy as _ from icerd.productions import production_debug, production_secret_key, allowed_host, production_caches_location # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = production_debug # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = production_secret_key ALLOWED_HOSTS = ["*"] if DEBUG else allowed_host AUTH_USER_MODEL = "registration.User" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
Django template not displaying data from database
I am running into an issue where my database is information is displaying on one template, but I want certain parts to display on another page for a blog. When I click into physics-blog it will display my images and post title. For this, I have looped through the database. Works fine and perfectly. But when I click into one of them and want to show {{ physicsBlog.body }} it doesn't show anything. Which I can't wrap my head around because that works just fine in the other ListView template, but not in the DetailView template. Here is my code. models.py class physicsBlog(models.Model):title = models.CharField(max_length=250)blog_image = models.ImageField(null=True, blank=True)description = models.CharField(max_length=200)author = models.ForeignKey(User, on_delete=models.CASCADE)body = RichTextField(blank=True, null=True)date_created = models.DateField(auto_now_add=True)def __str__(self):return self.title + ' | ' + str(self.author) views.py class physicsBlogListView(ListView):model = physicsBlogtemplate_name = 'physics.html'ordering = ['-id']class physicsBlogDetailView(DetailView):model = physicsBlogtemplate_name = 'physics-blog-details.html' urls.py urlpatterns = [path('', views.home, name="home"),path('physics-blog', physicsBlogListView.as_view(), name="physics-blog"),path('physics-blog/<int:pk>', physicsBlogDetailView.as_view(), name="physics-blog-details"),path('crypto-blog', cryptoBlogListView.as_view(), name="crypto-blog"),path('crypto-blog/<int:pk>', cryptoBlogDetailView.as_view(), name="crypto-blog-details"),] -
Creating a basic Input Form in a Django
I am trying to create a simple form in Django but it is not showing the input form in HTML and there is not error appearing so that I can track the error. Here is the model: class Log(models.Model): log_weight = models.FloatField(validators=[MinValueValidator(0)],blank=True, null=True) log_repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): log_weight = forms.IntegerField() log_repetitions = forms.IntegerField() class Meta: model = Log fields = ['log_weight', 'log_repetitions'] Here is the views: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) context = super().get_context_data(**kwargs) context['exercises'] = exercises return context def addlog(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = LogForm(request.POST) if form.is_valid(): data = Log() # create relation with model data.log_repetitions = form.cleaned_data['log_repetitions'] data.log_weight = form.cleaned_data['log_weight'] data.workout_id = id data.save() # save data to table return HttpResponseRedirect(url) return HttpResponseRedirect(url) Here is the template: <form class="review-form" action="{% url 'my_gym:addlog' workout.id %}" method="post"> {% csrf_token %} {{ form }} </form> Here is the url: urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), path('workout/addlog/<int:pk>', addlog, name='addlog'), ] My question: What is the reason that the form is not showing in the details page? How can I … -
Best Django model field to store frequency (from Hz to 10 GHz)
What is the best model field to store a frequency, from 1 Hz to 10 GHz? IMHO could be a PositiveBigIntegerField but I'm not completely convinced... Thank you