Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use template tags inside model field for displaying static images?
I have a huge report with some 50+ pages and there are several images and tables inside them. Is there any way I can put static tag inside textField which would be rendered in template, or I have to hardcode path inside model and use report.chapter_one|safe inside tempates? report model looks like chapter_one = models.TextField() chapter_two = models.TextField() chapter_three = models.TextField() ..etc And there are some tables and images that go inside those chapters. So what's the best way to display them because in templates I call chapters like report.chapter_one and it displays a wall of text where I can't put image from inside template -
I need help on algorithm for image recognition in python [closed]
I need a code for python that can detect number plates and compare it with the one on database Have no idea on where to start. The number plates supposed to be read through a camera. I need the code which can compare the plate with the one on database to identity the owner if is owing. -
Astrology prediction website using django [closed]
Need all complete source code.please help me.I tried a lot but not coming. I am trying it from many days but I am unable to build it.so can anyone help me in doing this. Hope anyone one help me to do this. I am waiting for it to complete. -
Python Logger does not write to file, still generates logs
have been struggling with this. I had created a logger for a class instance that gets created every 30 seconds or so. To prevent duplicate logging, I added a hasHandlers check, but now the results do not get logged to the file. I can see the logs being generated in PM2 though, so some portion of the logging is working. class ExampleClass: def __init__(self): self.example_logger = logging.getLogger(__name__) handler = TimedRotatingFileHandler('logs/example.log', when='D', interval=1, backupCount=0, encoding=None, delay=False, utc=False) if not self.example_logger.hasHandlers(): self.example_logger.addHandler(handler) self.example_logger.setLevel(logging.DEBUG) For the use-case, a new instance of this class needs to be created every 30 seconds. It is created via a django command. I would like to avoid any logging duplication as that has been an issue in the past. The path to the log file exists, and if the file is not present, it is created. Yet not written to. -
Problems to populate dropdown list with options from one of my tables (which already in Models.py)
I'm a newbie and I'm stuck while trying to populate a dropdown list with the records in one on my tables (mysql), my idea is to get this data from Marcasmodelos, and use it as to be posted with another field to my table "Modelos". But whenever rendering, nothing happens, it only shows the default option. Here are my codes: models.py class Marcasmodelos(models.Model): marca = models.CharField(db_column='Marca', primary_key=True, max_length=20) # Field name made lowercase. class Meta: managed = False db_table = 'marcasmodelos' class Modelos(models.Model): modelo = models.CharField(db_column='Modelo', primary_key=True, max_length=45) # Field name made lowercase. marca = models.CharField(db_column='Marca', max_length=45) # Field name made lowercase. class Meta: managed = False db_table = 'modelos' forms.py class MarcasForms(forms.ModelForm): class Meta: marca=Marcasmodelos fields= '__all__' class ModeloForm(forms.Form): marca = forms.ModelChoiceField(queryset=Marcasmodelos.objects.all().values(), widget=forms.Select(attrs={'class': 'custom-select'})) modelo = forms.CharField(max_length=100) formModelos.html (my form) <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="container"> <div class="row"> <div class="form-group"> <div class="mb-3"> <label for="marca">Marca:</label> <select name="marca" class="form-control custom-select" id="marca"> <option value="">Selecciona una marca</option> {% for marca in marcas %} <option value="{{ marca.id }}">{{ marca }}</option> {% endfor %} </select> </div> </div> <div class="col-fluid"> <div class="mb-3"> <label for="modelo" class="form-label">Modelo</label> <input type="{{ campo.field.widget.input_type }}" class="form-control" id="modelo" name="modelo" placeholder="Modelo del Producto"> {% if campo.errors %} <div class="invalid-feedback">{{ campo.errors }}</div> {% … -
How to use two database one for development and other production in the same application django
I have two databases one for development and other for the production, i set two dbs in my settings, but how can i alternate between the two dbs. Now i use method using in all objects, but i dont know if it`sthe best form. settings.py DATABASES = { 'default': { 'ENGINE': os.getenv('DB_PRODUCTION_ENGINE', 'change-me'), 'NAME': os.getenv('POSTGRES_PRODUCTION_DB', 'change-me'), 'USER': os.getenv('POSTGRES_PRODUCTION_DB_USER', 'change-me'), 'PASSWORD': os.getenv('POSTGRES_PRODUCTION_DB_PASSWORD', 'change-me'), 'HOST': os.getenv('POSTGRES_PRODUCTION_HOST', 'change-me'), 'PORT': os.getenv('POSTGRES_PRODUCTION_PORT', 'change-me'), }, 'development': { 'ENGINE': os.getenv('DB_DEVELOPMENT_ENGINE', 'change-me'), 'NAME': os.getenv('POSTGRES_DEVELOPMENT_DB', 'change-me'), 'USER': os.getenv('POSTGRES_DEVELOPMENT_DB_USER', 'change-me'), 'PASSWORD': os.getenv('POSTGRES_DEVELOPMENT_DB_PASSWORD', 'change-me'), 'HOST': os.getenv('POSTGRES_DEVELOPMENT_HOST', 'change-me'), 'PORT': os.getenv('POSTGRES_DEVELOPMENT_PORT', 'change-me'), } } example queryset def get_database_name(request): environment = request.session.get('environment', 'default') return environment using = get_database_name(request) model = Model.objects.using(using) -
Not Showing Browsable Api interface in djanog rest framework
not showing browsable api interface in django rest_framework http://127.0.0.1:8000/api here is my code auth_app/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,**extra_fields): if not email: raise ValueError('The Email Field must be set') email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,password=None,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) class CustomUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] def __str__(self): return self.email auth_app/serializers.py from rest_framework import serializers from .models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','email','first_name','last_name','is_active','is_staff') auth_app/views.py from rest_framework import generics,permissions,status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .serializers import CustomUserSerializer class RegistrationAPIView(APIView): def post(self,request): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) return Response( { "refresh": str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_201_CREATED, ) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class LoginAPIView(APIView): def post(self,request): email = request.data.get("email") password = request.data.get("password") user = authenticate(request, email=email,password=password) if user: login(request,user) refresh = RefreshToken.for_user(user) return Response( { "refresh":str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_200_OK ) return Response({"error":"Invalid Credentials"},status=status.HTTP_401_UNAUTHORIZED) @method_decorator(login_required,name="dispatch") class LogoutAPIView(APIView): def post(self,request): logout(request) return … -
Wagtail SSL issue running locally with ip instead localhost
Is there anyone who is familiar with disabling SSL redirection in a Python Django/Wagtail project? We're currently experiencing an issue on our local setup where the site isn't functioning properly with an IP address, unless it's using "localhost" and its specific IP address. If you have a solution or any insights into this matter, kindly send me a direct message. Your assistance would be greatly appreciated. Thanks. Tried with the SSL disable configuration but still not worked -
Why is file download not working in my Django view?
The view function in my Django application is designed to transcribe a file and generate a subtitle file in .srt format. It then identifies the transcript file and is expected to automatically download it. However, currently, the automatic download does not occur. The file was submitted on a different page that uses the transcribeSubmit view, while the initiate_transcription view is responsible for handling and returning the file. Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def … -
Data is not loading, via AJAX
Hello Im not good with Ajax so I need some help. I want to see data but it's not appering when I click button. But I can see all data in Network preview. What I can miss in Ajax request any ideas? **My template ** {% extends 'base.html' %} {% block content %} <ul style="list-style-type: none; padding: 0;"> {% for district in object_list %} <li style="background-color: #f7f7f7; border: 1px solid #ccc; border-radius: 5px; padding: 10px; margin-bottom: 10px;"> <h3 style="color: #333; font-size: 20px;"><a href="{% url 'districts-detail' pk=district.pk %}">{{ district.name }}</a></h3> <p style="color: #666;">Drop-offs: {{ district.drop_offs_count }}</p> <p style="color: #666;">Scooter places: {{ district.scooter_places }}</p> <p style="color: #666;">Scooters in district: {{ district.scooters_in_district }}</p> <!-- Update the button to include the district's ID as a data attribute --> <button class="show-info-button" data-district-id="{{ district.id }}">Show Additional Info</button> <div class="additional-info" style="display: none;"> <!-- Include the additional information from the additional-info-popup.html template --> {% include 'district-popup.html' %} <!-- Add more additional information fields here as needed --> </div> </li> {% endfor %} </ul> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Define the base URL for the AJAX requests const baseUrl = "{% url 'get_district_info' 0 %}".slice(0, -1); console.log(baseUrl); $(document).ready(function () { // Handle click event on the "Show Additional Info" button … -
No module named 'paramiko' in docker python:3.12.0-alpine even after installing it (logs say it was installed)
paramiko is inside requirements.txt and is installed via RUN pip3 install -r requirements.txt --prefer-binary in my Dockerfile. I also tried installing it with apk py3-paramiko. docker-compose logs tell me that paramiko is installed. Successfully installed Django-4.1.3 PyNaCl-1.5.0 asgiref-3.7.2 bcrypt-4.0.1 beautifulsoup4-4.12.2 certifi-2023.7.22 cffi-1.16.0 charset-normalizer-3.2.0 cryptography-41.0.4 django-auth-ldap-4.5.0 django-bootstrap-v5-1.0.11 djangoajax-3.3 dnspython-2.4.2 gunicorn-21.2.0 idna-3.4 multiping-1.1.2 mysql-connector-python-8.0.29 packaging-23.1 ***paramiko-3.3.1*** protobuf-4.24.3 pyasn1-0.5.0 pyasn1-modules-0.3.0 pycparser-2.21 python-ldap-3.4.3 requests-2.31.0 soupsieve-2.5 sqlparse-0.4.4 urllib3-2.0.5 ... web_1 | File "/usr/local/lib/python3.9/site-packages/django/urls/conf.py", line 38, in include web_1 | urlconf_module = import_module(urlconf_module) web_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import web_1 | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load web_1 | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 680, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 850, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed web_1 | File "/usr/src/app/emailflow/urls.py", line 2, in <module> web_1 | from . import views web_1 | File "/usr/src/app/emailflow/views.py", line 3, in <module> web_1 | from . import main web_1 | File "/usr/src/app/emailflow/main.py", line 7, in <module> web_1 | import paramiko web_1 | ModuleNotFoundError: No module named 'paramiko' Any help would be greatly appreciated. -
S3 – Images sometimes showing up with wrong rotations
I run a web service where users are allowed to upload images. I've noticed that sometimes, the uploaded image on S3 shows up rotated – as I came to learn due to exif metadata. Taking a sample of some of the images, and opening them in GIMP, it yields a prompt where I have to decide whether to keep or strip the exif metadata. I noticed, however, that sometimes the "properly" rotated image includes the exif metadata, and, other times, to "properly" rotate the image I need to tell GIMP to ignore the exif data. I thought I could resolve this issue simply by getting rid of the exif metadata, but this will not work under the above observation. So, in summary: how can I guarantee image uploading to S3 with the correct image rotation? P.S.: I am using Python via boto3 to upload images. Thanks! -
whats the best way to format Django Templates in VSCODE?
enter image description here VSCode prettier formatter makes this template format in weird way and i get error in django. I have tried multiple Django Extensions , Prettier ,etc. can anyone share best vscode extensions and settings for django . -
Django auto submit form when user done typing?
I have a form with a text field and i want to receive user input and after user done typing (about 2s). Is there a way to achieve this in django(i only know how to do this in pure js) My model and form: class ProductName(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class ProductNameForm(ModelForm): class Meta: model = ProductName fields = ('name',) My template: <div id="searchbar" class="d-flex flex-row"> <form action="search_result" method=POST class="input-group flex-nowrap bg-light mx-0 mx-lg-auto rounded p-1"> {% csrf_token %} {{ place.place }} {% render_field form.name placeholder="Search product..." class+="form-control"%} {% comment %} <input type="text" id="search" placeholder="Search product" name="search-input" class="form-control rounded"> {% endcomment %} <button type="submit" class="btn btn-secondary"><i class="fa fa-search"></i></button> </form></div> My view: def search(request): if request.method == 'POST': form = ProductNameForm(request.POST) place = ProductPlaceForm(request.POST) if form.is_valid() and place.is_valid(): form.save() place.save() form = ProductNameForm() place = ProductPlaceForm() return HttpResponseRedirect('/search_result') form = ProductNameForm() place = ProductPlaceForm() return render(request, 'search_form.html', {'form':form, 'place':place}) -
Django embedded custom template tag
I'm trying to create a custom template tag for Django. However, it is not generating any output; nor receiving any from the parser. The following is the code for the templatetag itself: class MediaQueryNode(Node): def __init__(self, xsmall, small, medium, large, xlarge, wrap=None): self.xsmall = xsmall self.small = small self.medium = medium self.large = large self.xlarge = xlarge self.wrap = wrap def render(self, context): xsmall = None small = None medium = None large = None xlarge = None context = context.flatten() if self.xsmall: xsmall = self.xsmall.render(context) if self.small: small = self.small.render(context) if self.medium: medium = self.medium.render(context) if self.large: large = self.large.render(context) if self.xlarge: xlarge = self.xlarge.render(context) template = loader.get_template("templatetags/mediaquery.html") context.update({ "mediaquery_xsmall": xsmall, "mediaquery_small": small, "mediaquery_medium": medium, "mediaquery_large": large, "mediaquery_xlarge": xlarge, "wrap": self.wrap.resolve(context) if self.wrap else False, }) return template.render(context) @register.tag("mediaquery") def do_media_query(parser, token): subtags = ["xsmall", "small", "medium", "large", "xlarge"] tag_content = {tag: None for tag in subtags} processed_tags = [] end_tag = 'endmediaquery' # Skip any content between {% mediaquery %} and the first subtag parser.parse(subtags + [end_tag]) while parser.tokens: token = parser.next_token() if token.token_type == TokenType.BLOCK: token_name = token.contents if token_name in processed_tags: raise TemplateSyntaxError(f"Duplicate {token_name} tag") if token_name not in subtags and token_name != end_tag: raise TemplateSyntaxError(f"Unknown … -
Django ModelForm - Bootstrap DateTimePicker
I'm having some problems for processing DjangoModelForm and bootstrap-datepicker to select a specific month First of all I get this error when I access the form The specified value "01/04/2023" does not conform to the required format. The format is "yyyy-MM" where yyyy is year in four or more digits, and MM is 01-12 And after selecting manually the month I get periodo: Enter a valid date. limite_retroactividad: Enter a valid date. I tried to handle it with a javascript script but it's working just for the initial dates but not for saving the data. This is what I have: forms.py class RegistroGestionForm(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() periodo = cleaned_data.get('periodo') limite_retroactividad = cleaned_data.get('limite_retroactividad') if periodo and limite_retroactividad: if periodo < limite_retroactividad: # Add validation error self.add_error('limite_retroactividad', 'El periodo no puede ser menor al límite de retroactividad') return cleaned_data class Meta: model = RegistroGestion fields = ['periodo', 'estado', 'limite_retroactividad'] widgets = { 'limite_retroactividad': DateInput( attrs={ 'type': "month", 'class': "form-select mb-3" } ), 'periodo': DateInput( attrs={ 'type': "month", 'class': "form-select mb-3" } ), } views.py class RegistroGestionUpdateView(UpdateView): model = RegistroGestion form_class = RegistroGestionForm context_object_name = 'registro_gestion' template_name = 'esquema_liquidacion/registro_gestion_form.html' def get_context_data(self, … -
manage.py server running twice internally
why while executing the command manage.py runserver in my project server runs twice.How to fix the issue.but while using --noreload this issue not arises but during api testing server doesnot respond.Shwoing file path not found. command:-py manage.py runserver output:- manage.py is being executed. Hello manage.py is being executed. Hello Watching for file changes with StatReloader Performing system checks... command:-py manage.py runserver output:- manage.py is being executed. Hello manage.py is being executed. Hello Watching for file changes with StatReloader Performing system checks... -
Page not found не работает if settings.DEBUG: [closed]
Начал изучение библиотеки Django и столкнулся с проблемой при создании интернет-магазина, что мою страницу не может найти при использовании следующей команды: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) son/urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('koil.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in son.urls, Django tried these URL patterns, in this order: При запуске сервера пишет вот это: admin/ ^static/(?P.)$ ^media/(?P.)$ The empty path didn’t match any of these. В чём может быть проблема? P.S. Заранее извиняюсь, если вопрос задан некорректно, при необходимости могу дополнить. К сожалению не имею ни малейшего понятия, как решить данную проблему( -
Django How to use proxy models instead of parent
My code: from django.db import models class Animal(models.Model): type = models.CharField(max_length=100) class Dog(Animal): class Meta: proxy = True class Cat(Animal): class Meta: proxy = True I want to do: animals = Animal.objects.all() but in animals, I should have only Dogs and Cats instances. I need to cast an Animal object to a specific proxy model somehow. How do I do that? in the init method? -
ModuleNotFoundError: No module named 'real_estate' - uwsgi & django
I've been trying to run my django website using uwsgi, but I keep getting this error. I tried so many solutions from stackoverflow and others but It just doesn't get fixed. I'm using this article to do so: https://medium.com/@panzelva/deploying-django-website-to-vps-with-uwsgi-and-nginx-on-ubuntu-18-04-db9b387ad19d Here are some of the solutions I tried: Having the same version of python in venv and global env(both 3.10.12). Moving wsgi.py file from real_estate directory to the main folder. Changing line 12 of wsgi.py file from "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'real_estate.settings')" to "os.environ.setdefault['DJANGO_SETTINGS_MODULE']= 'real_estate.settings'" or "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')" I tried running my website like this: "vim uwsgi/sites/real_estate.ini" and then opened my browser tab to this <my_vps_ip_address>:8000, but I get This: "Internal Server Error" and this in my error log: *** Operational MODE: single process *** Traceback (most recent call last): File "/home/allen/project/real_estate/real_estate/wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/allen/project/env/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/allen/project/env/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File … -
Which is a better alternative to the Django make_random_password Deprecated function?
This aswer suggests the use of the make_random_password, but it is deprecated since Django 4.2. I assume there is a good reason for eliminating this fuction, so what should I use instead? I searched for alternatives, but could not find any native to Django. I can create my own solution using hashlib, but should I? -
Django : MixIn or One-to-One for User
I have a Django project containing among others, 2 models : Contact and User. I want a contact to have the ability to be transformed into a user. I am hesitating between 2 choices : Using MixIn to make my User inherit from Contact Using One-to-One but in the reverse way from the documentation Here is option 1: #models.py from django.db import models from django.contrib.auth.models import AbstractUser class OwningCompany(models.Model): name = models.CharField(max_length=255) class Entreprise(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Contact(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) email = models.EmailField(max_length=255) class User(Contact, AbstracUser): pass And here is option 2 : #models.py from django.db import models from django.contrib.auth.models import AbstractUser class OwningCompany(models.Model): name = models.CharField(max_length=255) class Entreprise(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Contact(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) email = models.EmailField(max_length=255) class User(AbstractUser): contact = models.OneToOneField(Contact, on_delete=models.CASCADE) Might be of interest to know that I will always query for a single OwningCompany. What is the best way of doing this ? -
Running django app as a service and it failing to load the base templates
I have created this django appraisal app and I am running it on my company premises server and did not want to have to run in with cmd for obvious reasons. So I created this simple service that runs it on the a certain port. The problem is that all css fails to load and the base templates cannot be found when I run it. It is worth noting that when I run it from cmd everything loads perfectly but when I start the service, the base templates cannot be found. Here is the service I am using: <service> <id>appraisal</id> <name>Appraisal</name> <description>This service runs Pergamon Appraisal tool</description> <executable>C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe</executable> <arguments>C:\perg_appraisal\pergamon_appraisal\pergamon\manage.py runserver 0.0.0.0:9190</arguments> <logpath>C:\perg_appraisal\pergamon_appraisal\service_logs</logpath> <log mode="roll"></log> </service> Here is my BASE_DIR path in settings: BASE_DIR = Path(__file__).resolve().parent.parent Here is my templates: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and here is my static files urls: STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'static'] What could be making my base templates not visible when running it as a service? -
Django Model Error : Code is not getting renderd
So, I having a database in which there is html code which i wanna render i show you the model first model.py class Badge(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=700, default='<h5><span class="badge bg-primary ms-2">New</span></h5>') code_price = models.CharField(max_length=700, default='<s>{{product.price | safe}}</s><strong class="ms-2 text-danger">{{product.get_price_with_discount() | safe}}</strong>') # product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='badges') def __str__(self): return self.name class Product(models.Model): """A product.""" name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='static/img/' , default='/static/img/404.png') category = models.ForeignKey(Category, on_delete=models.CASCADE) type = models.ForeignKey(Badge, on_delete=models.CASCADE, related_name= "products") def get_price_with_discount(self): discount = (self.price) * (10 / 100) return self.price - discount now in Django it cant find the product.price since product is defined later or u can say it renders it but as a string i send the html page code now services.html <section> <div class="text-center container py-5"> <h4 class="mt-4 mb-5"><strong>Bestsellers</strong></h4> <div class="row"> {% for product in products %} <div class="col-lg-4 col-md-12 mb-4"> <div class="card"> <div class="bg-image hover-zoom ripple ripple-surface ripple-surface-light" data-mdb-ripple-color="light"> <img src="{{product.image.url}}" class="w-100" style="height: 500px;" /> <a href="#!"> <div class="mask"> <div class="d-flex justify-content-start align-items-end h-100"> {% comment %} <h5><span class="badge bg-primary ms-2">New</span></h5> {%endcomment %} {{product.type.code|safe}} </div> </div> <div class="hover-overlay"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div> </div> </a> </div> <div class="card-body"> <a href="" class="text-reset"> <h5 class="card-title … -
Django summernote text editor when edit the bullet point or number it's not showing on Django template?
SummerNote editor bullet point and number not showing on Django Template here my config setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'web.apps.WebConfig', 'django_summernote', ] X_FRAME_OPTIONS = 'SAMEORIGIN' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media/' here url.py settings path('summernote/', include('django_summernote.urls')), admin.py settings from django.contrib import admin from .models import Navmenu, NavSubmenu, WebPage, WebUrl, Seo,NewLatter, Project from django_summernote.admin import SummernoteModelAdmin class ProjectAdmin(SummernoteModelAdmin): list_display = ('name','sort_title','slug','create_by','create_at','update_at','status') summernote_fields = ('desc') admin.site.register(Project, ProjectAdmin) view.py settings def Projects_Details(request,slug): tags = Seo.objects.filter(pages_title__name = "Project-Details").first() pro_de = Project.objects.filter(slug = slug).first() context = { 'tags':tags, 'pro_de':pro_de, } return render(request,'web/project_detail.html', context) templates {{pro_de.desc | safe}} here editor pic. and here template output pic.