Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update Django ImageField through .update() ORM
Similar questions have been asked here: Update ImageField without forms in django, and Django ImageField is not updating when update() method is used But the answer has always been the same ("use .save() instead") - this solution does work, but because of signals on the model which I can't control, I would like to know if there are any work-arounds that can be used instead. # serializers.py from drf_extra_fields.fields import Base64ImageField from rest_framework import serializers class ProfileSerializer(serializers.Serializer): email = serializers.CharField(required=False, allow_null=True) image = Base64ImageField(required=False, allow_null=True, max_length=None, use_url=True) # views.py def get_as_base64(url: AnyStr): if url is None: return None, None full_name = url.split("/")[-1] my_base = base64.b64encode(requests.get(url).content) return my_base, full_name def do_profile_update(profile: Dict): b64_image, file_name = get_as_base64(profile.get("url")) if b64_image and file_name: *_, file_ext = file_name.split(".") b64_image = f"data:image/{file_ext};base64,{b64_image.decode('utf-8')}" build_dict = { "email": profile.get("email"), "image": b64_image, } serializer = ProfileSerializer(data=build_dict) serializer.is_valid() # returns True # serializer.validated_data = {'email': 'test@example.org', 'image': <SimpleUploadedFile: 11735acf-6d96-4c62-9e6a-8ebb7f7ea509.jpg (image/jpeg)>} Profile.objects.filter(pk=pk).update(**serializer.validated_data) # This saves the *name* of the image to the database, but no image file I understand that a ImageField is basically a CharField, and I can see the name of the image in the database, but the image isn't written to the server. My question boils down to: … -
Is there a way to install pymssql with the python2.7?
Collecting pymssql Using cached pymssql-2.2.2.tar.gz (170 kB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'C:\Python27\python.exe' 'C:\Python27\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'c:\users\connor~1\appdata\local\temp\pip-build-env-jbbmyu\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=54.0' 'setuptools_scm[toml]>=5.0' 'wheel>=0.36.2' 'Cython>=0.29.22' cwd: None Complete output (3 lines): DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. ERROR: Could not find a version that satisfies the requirement setuptools>=54.0 (from versions: 0.6b1, 0.6b2, 0.6b3, 0.6b4, 0.6rc1, 0.6rc2, 0.6rc3, 0.6rc4, 0.6rc5, 0.6rc6, 0.6rc7, 0.6rc8, 0.6rc9, 0.6rc10, 0.6rc11, 0.7.2, 0.7.3, 0.7.4, 0.7.5, 0.7.6, 0.7.7, 0.7.8, 0.8, 0.9, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 1.0, 1.1, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.1.7, 1.2, 1.3, 1.3.1, 1.3.2, 1.4, 1.4.1, 1.4.2, 2.0, 2.0.1, 2.0.2, 2.1, 2.1.1, 2.1.2, 2.2, 3.0, 3.0.1, 3.0.2, 3.1, 3.2, 3.3, 3.4, 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.5, 3.5.1, 3.5.2, 3.6, 3.7, 3.7.1, 3.8, 3.8.1, 4.0, 4.0.1, 5.0, 5.0.1, 5.0.2, 5.1, 5.2, 5.3, 5.4, 5.4.1, 5.4.2, … -
I am using XPATH on selenium in python and I understand the issue selenium.common.exceptions.JavascriptException: Message: Cyclic object value
First, I am a newbie in Selenium in Python. I am working on a website in Django Framework. I want to do unit tests in order to make the website project with an higher quality. The Error selenium.common.exceptions.JavascriptException: Message: Cyclic object value Introduction I do my test in tests_functionals.py which is a file containing selenium. I use XPATH in order to retrieve elements on the DOM. In the index.html of the website, I have those links : <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="/home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/corpora">Corpora</a> </li> <li class="nav-item"> <a class="nav-link" href="/approaches">Approaches</a> </li> <li class="nav-item"> <a class="nav-link" href="/ML">Machine Learning</a> </li> </ul> I use BaseX software to test my XPATH paths. I have sorry but I cannot show you pictures because I am new in stackoverflow so I don't have enough reputation to show pictures. Here if ou want to learn more about BaseX I use this path : //header/nav/div/ul/li/a/@href And on BaseX I have this result: href="/home" href="/about" href="/corpora" href="/approaches" href="/ML" My problem in Django I will show you a piece of this code in order to make you understand what I am talking. from selenium import webdriver from … -
How to have a backend_model be associated to a Django model
I have a Ticker Model - class Ticker(models.Model): symbol = models.CharField(max_length=50, primary_key=True) company_name = models.CharField(max_length=50) def __str__(self) -> str: return f'{self.symbol}-{self.company_name}' And class Model(models.Model): ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE) test_loss = models.FloatField(null=True) def __str__(self) -> str: return f'{self.ticker.symbol}' I want to add this function to Model - def predict(self, pred_date): return self.backend_model.predict(pred_date) Where - self.backend_model = LstmModel(symbol) How do I add this backend_model to Model? These are the solutions I have thought of - Have a custom Model Manager. Override save() method of Model. Add a classmethod to Model Which one should I use, or if someone can suggest a better way? -
Django dynamic formset only saving last entry
I have created a page where users can enter details to forms relating to a parent model (Patient) and two child models (CurrentMed and PastMed) linked to that parent. Both the child forms use dynamic formsets where the user can add or delete rows to the form. My problem is only the last row of the currentmed and pastmed formsets is saving to my database when the user submits the form? models.py class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Med(TimeStampedModel): med_name = models.CharField(“med name“, max_length=20) dose = models.IntegerField("Dose (mg)", default=0) timepoint = models.CharField( "timepoint", max_length=20, choices=[('current','current'), ('past', 'past')], default='unspecified') patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Meta: abstract = True class CurrentMed(Med): timepoint = models.CharField( "", max_length=20, choices=[('current','current'), ('past', 'past')], default='current') class PastMed(Med): timepoint = models.CharField( "", max_length=20, choices=[('current','current'), ('past', 'past')], default='past') forms.py from .models import CurrentMed, PastMed, Patient CurrentmedFormSet = inlineformset_factory( Patient, CurrentMed, fields=("med_name", "dose",), extra=2) PastmedFormSet = inlineformset_factory( Patient, PastMed, fields=("med_name", "dose",), extra=2) class PatientForm(ModelForm): class Meta: model = Patient fields = ['name', 'sex', 'age', 'diagnosis'] views.py class PatientAddView(LoginRequiredMixin,TemplateView): model … -
how to show date in url django
im trying to return objects based on date (yyyy-mm-dd) but it returns this : Reverse for 'daily_detail' with arguments '(datetime.datetime(2021, 8, 19, 0, 0),)' not found. 1 pattern(s) tried: ['my/url/for/(?P\d{4}-\d{2}-\d{2})$'] this is my views.py #my lists def daily_list(request): lists = MyModel.objects.annotate(day=TruncDay('date')).values('day').order_by('-day') #this is my day detail def daily_report(request,day): daily_report = MyModel.objects.annotate(day=TruncDay('date')).filter(day=day).order_by('-pk') context = { 'daily_report':daily_report } and this is my urls.py path('list/daily',daily_list,name='daily_list'), path('list/daily/<str:day>',daily_report,name='daily_report'), but it returns the above error and this is my template {% for i in lists %} <!--other informations --> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple"> <a href="{% url 'myAppUrl:daily_report' i.day %}"><button><i class="fas fa-eye"></i></button></a> </tr> {% endfor %} thank you for your suggestions ... -
How to return and display multiple tables as JsonResponse in Django?
I'm trying to display the result of two queries in different tables at my Django project. I have the following view: cursor = connections['trades_db'].cursor() sql = """Select investor from a; """ sql_II = """Select price from b; """ d = db.fetchDataDict(cursor, sql) e = db.fetchDataDict(cursor, sql_II) return JsonResponse({'d':d, 'e':e}, safe=True) I want to display the result of both queries in different HTML tables, How is possible to access to each element of the JsonResponse? so far, I was able to access to just one element by returning it individually: return JsonResponse(d, safe=True). However, I don't know to access each element when returning both queries. $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); var table = $('#maintable').DataTable( { "ajax": {"type":"GET", "url" :"/data/trades/request/", "data":function( d ) { d.placeholder = "asdf"; } }, -
Django modal popup on a list link
I would like to develop a popup on a list link (please see the screenshot) click. popup will be a list also. So far this is my code below Model class: class PSCInscpection(models.Model): vessel = models.ForeignKey(Vessel, on_delete=models.CASCADE, null=True) inspection_id = models.CharField(max_length=100, null=False, unique=True) followup_inspection = models.BooleanField(null=False, default=False) date = models.DateTimeField(null=True, blank=True) port = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) number_of_defects = models.PositiveIntegerField(null=True, blank=True) days_detained = models.PositiveIntegerField(null=True, blank=True) class PSCInscpectionDefects(models.Model): pscinscpection = models.ForeignKey(PSCInscpection, on_delete=models.CASCADE, null=True) inspection_id = models.CharField(max_length=100, null=False, blank=False) defect_code = models.CharField(max_length=50, null=True, blank=True) defect_text = models.CharField(max_length=255, null=True, blank=True) class_is_responsible = models.CharField(max_length=50, null=True, blank=True) defective_item_code = models.CharField(max_length=50, null=True, blank=True) My list binding from this "PSCInscpection" object and popup will bind from "PSCInscpectionDefects" object. Any help regarding please ? Thanks ! {% for inspection in inspections %} <tr> <td>{{ inspection.date }}</td> <td>{{ inspection.country }}</td> <td>{{ inspection.port }}</td> <td> {% if inspection.defects %} <a href="#">{{ inspection.defects }}</a> {% else %} {{ 0 }} {% endif %} </td> <td>{{ inspection.detained|default:0 }} Days</td> </tr> {% endfor %} -
Django CustomUser deploying and getting error: relation "accounts_customuser" does not exist
I am deploying my django to VSP using Dokku. I have the project working on my local computer but when I deploy to dokku, I'm getting errors when it tries to do the migrations. The dokku is deployed with git push dokku main:master and migrations are in my .gitignore, so migrations on my local computer are not being pushed. I am using a CustomUser model which extends AbstractUser. The problem looks to be django.db.utils.ProgrammingError: relation "accounts_customuser" does not exist. full logs/trace PS C:\> git push dokku main:master Enter passphrase for key '/c/Users/name/.ssh/id_rsa': Enumerating objects: 331, done. Counting objects: 100% (331/331), done. Delta compression using up to 16 threads Compressing objects: 100% (326/326), done. Writing objects: 100% (331/331), 1.18 MiB | 2.24 MiB/s, done. Total 331 (delta 71), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (71/71), done. remote: -----> Cleaning up... remote: -----> Building app from herokuish remote: -----> Adding BUILD_ENV to build environment... remote: -----> Python app detected remote: -----> Using Python version specified in Pipfile.lock remote: cp: cannot stat '/tmp/build/requirements.txt': No such file or directory remote: -----> Installing python-3.8.11 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing dependencies with Pipenv 2020.11.15 … -
django get path to previous parent directory on template tag
i want to extends from an base.html that is before(previous?) the parent directory. the path estructure is this: templates: base base.html <--- file i want to extends. pages general home.html <--- file from where i got the error the problem is TemplateDoesNotExist at / pages/general/base/base.html and here is the html code from home.thml in template/pages/general/base.html for call .base.html {% extends "../base/base.html" %} i dont know how i can go to the previous folder from parent directory, and i dont even know how to find documentation referenced to that, im not native english speaker so its hard to find and answer. -
Django S3 : Saving images doesn't work when calling serializer
I need to create an API to upload images on a website. I've already created in my models the save method to upload and resize images. It's working correctly by the django administration page. Unfortunately, when I use my serializer, the image does not save. Here is my model : models.py class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7) message = models.TextField(null=True, blank=True) banner = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): try: """If we want to update""" this = Shop.objects.get(id=self.id) if self.banner: image_resize(self.banner, 300, 300) if this.banner != self.banner: this.banner.delete(save=False) else: this.banner.delete(save=False) except: """If we want to create a shop""" if self.banner: image_resize(self.banner, 300, 300) super().save(*args, **kwargs) def delete(self): self.banner.delete(save=False) super().delete() def __str__(self): return self.name banner is the imagefield that I have to save. Here is my serializer : serializers.py class ShopSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() isOwner = serializers.SerializerMethodField() banner = serializers.SerializerMethodField() class Meta: model = Shop fields = '__all__' def get_links(self, obj): links = Link.objects.filter(shop=obj) data = LinkSerializer(links, many=True).data return data def get_banner(self, obj): """Get a link for the banner""" if obj.banner: url = f"https://myurl/v1/images/{obj.banner.name}" return url def get_isOwner(self, obj): … -
How to add product to cart on a page with many products in E-commerce Vue.js / Django Rest Framework?
I am building an e-commerce website with Vue.js and Django Rest Framework. I have a page with all the latest products, that works well and fetches all the data. I can visit the details of each product and add them to the cart (on each product's page). The problem is that I don't know and can't get to add those products from the general products page where there are multiple products and get the number of products of each one of them. I created a dynamic Id for number input, but when I try to use it it says "Cannot read property 'value' of null" I understand that the number of products should be related to each one of the products, but I can't seem to understand how to do that. To sum things up: How can I add products to the cart on a page with multiple products fetched via v-for? Thank you! This is my Vue.js Products page code: <template> <div id="productapp"> <!-- Intro Section --> <div class="row" id="home__screen"> <div class="col-lg-12 text-center align-self-center decorator__spacing"> <h1 class="mt-5 mb-4 text-white">Conoce nuestros productos</h1> <button type="button" class="btn btn-light pl-3 pr-3 fw-bold main__text__color">VER MÁS</button> </div> </div> <!-- About Section --> <div class="w-100 bg-white … -
Django ORM And Multiple Dynamic Databases
Disclaimer: I am still pretty new to Django and am no veteran. I am in the midst of building the "next generation" of a software package I built 10 years ago. The original software was built using CodeIgniter and the LAMP stack. The current software still works great, but it's just time to move on. The tech is now old. I have been looking at Django to write the new software in, but I have concerns using the ORM and the models file getting out of control. So here's my situation, each client must have their own database. No exceptions due to data confidentiality and contracts. Each database mainly stores weather forecast data. There is a skeleton database that is currently used to setup a client. This skeleton does have tables that are common across all clients. What I am concerned about are the forecast data tables I have to dynamically create. Each forecast table is unique and different with the exception of the first four columns in the table being used for referencing/indexing and letting you know when the data was added. The rest of the columns are forecast values in a real/float datatype. There could be anything from … -
Django/Heroku deployment problems: Won't work on Debug = False
I got my app to deploy, but pages that require an id in session are not rendering. When I set debug = true, everything works fine. Otherwise, I get error 500 message. I've tried many different solutions to no avail. I imagine the problem is somewhere in my settings.py so I have included that below. I was also able to log the startup so that is included as well. The main page and pages that don't get a request.session passed into them work fine, as well as functions that update the database. Only pages that require an id passed into the path are not working. import dj_database_url import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'wiki_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'coding_dojo_final_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'coding_dojo_final_project.wsgi.application' ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '****', } } WHITENOISE_USE_FINDERS = True ... LOGGING … -
There is a problem that several products are floating in Django. I think it's an if and for tag problem
I am a student who is learning Django. I want to show the purchase history of the product in the html file, but if I use the for statement to load the join_detail and element, the same syntax keeps repeating. I really don't know what's wrong. How can I modify it so that I can express it's? Please help me. I'm really desperate. I can only move forward if I solve this problem. html <div class="container"> <h4 style="margin-top:20px; margin-bottom: 30px;"><b>구매</b></h4> <div class="table-wrap"> <table class="board all-open"> <caption></caption> <colgroup> <col> <col style="width:15%;"> <col span="3"> </colgroup> <thead> <tr> <th scope="col">상품번호</th> <th scope="col">상품정보</th> <th scope="col">상품명</th> <th scope="col">수량</th> <th scope="col">가격</th> <th scope="col">옵션</th> <th scope="col">구매일자</th> <th scope="col">링크</th> </tr> </thead> <tbody> <tr> {% for product in products %} {% for join in join_objects %} {% if join.product_code.product_code == product.product_code %} {% for designated in designated_object %} {% if designated.product_code.product_code == product.product_code %} {% for join_detail in join_detail_objects %} {% if join.join_code == join_detail.join_code.join_code %} {% for element in element_object %} {% if element.designated_code == join_detail.designated_code %} <td class="num">{{join.join_code}}</td> <td class="name"><a href="{{product.get_absolute_url}}"><img style="width: 90px" height= 90px" src="{{product.image.url}}" alt="상품 이미지"></a></a></td> <td class="subject">{{join.product_code}}<a href="#" class="ellipsis"> </a><a href="#" title="{{product.name}}"></a> </td> <td class="hit">{{join_detail.quantity}}</td> <td class="date">{{join_detail.price}}</td> <td class="date">{{element.value_code}}</td> <td class="name">{{join.part_date|date:"Y-m-d"}}</td> <td class="name"><a href="{{ … -
Change django array field size depending on another field?
I am building an app that displays different courses. For each course there is a list of the different classes it has. Some courses have two classes, somo have eight, some have just one or in the future some courses may have 10 classes. It's up to the app's administrator when they register a new course class Curso(models.Model): clases = models.IntegerField(default=1) content = ArrayField(models.CharField(max_length=30),blank=False) This model will only be for the administrator. I want to store the different classes (just their names) in an array. But theres no need to show 8+ fields if the admin is just going to fill one in... Or is that the correct approach? I want the admin to have an integer field where she types in how many classes the course has and depending on that the array fields will be displayed. I understand ArrayField has a size attribute where I can say how long the array is. Right? So my question is: Is there a way to dinamically change the array size depending on what the admin types in in the "clases" field? I need this to work in the admin app. I am new to django and I'm finding the admin app … -
New fields are not saving in django admin
I’m making a register form for my app and also it work pretty well.But the bug is whenever user log into application it will not save data of new fields and also in register page full register form can be seen.First_name and Last_name other data like username and email are save without any problem.And I migrate database as well.Here is picture of admin of app. here is my code forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate, logout from django import forms class RegisterForm(UserCreationForm): email = forms.EmailField() First_name = forms.CharField() Last_name = forms.CharField() class Meta: model = User fields = ["First_name", "Last_name","username", "email", "password1", "password2"] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('A user has already registered using this username') return username views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm from django.contrib.auth import login, authenticate, logout def register(request): if request.method == 'POST': #if the form has been submitted form = RegisterForm(request.POST) #form bound with post data if form.is_valid(): … -
I can't connect static files to my django project on hosting (directAdmin)
I have an error when I try to load static files on my django project. My site is working, all pages are loading but images, JavaScript and CSS files don't connect. I'm using directAdmin on hosting. This error show me in Chrome console. Refused to apply style from 'https://cvvaiu.ru/static/home/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. My code in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' My code in index.html: <link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}"> ... <script src="{% static 'home/js/script.js' %}"></script> Static files and templates are located in the same folder where located manage.py What can I do? Help me please P.S This is my first experience with DirectAdmin. Please correct my mistakes. -
How to pass list containing dictionary in html template and access its values
In django i have this list my_list=[{'id':1,'username':'sometext'},{'id':2,'username':'someothertext'}] now i am passing this list into the template return render(request,'template.html',{'mylist':my_list}) This is my template.html {% for i in mylist.items %} <tr> <td>{{ mylist.id }}</td> <td>{{ mylist.username }}</td> </tr> {% endfor %} But by doing this i didn't get the value of id and and username. Please suggest if someone have solution. -
Django ignore/ disable Invalid HTTP_HOST header
Using sentry for tracking issues with my Django app, I get a lot of reports of the following style: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS.. As this seems pretty suspicious (if I understand correctly this would mean that somebody poses as my site) I would like Django to disable this entirely. I have a fixed set of ALLOWED_HOSTS and wouldn't want to use up my sentry capacities with this error message. Using nginx on the server I already added the following to my config: if ($host !~* ^(mysite1.com|mysite2.com)$) { return 444; } The error still persists. I also added in Sentry settings "allowed domains" but this only affects the origin and referrer headers not the host header. -
Different Timezones in Django Model
Is there a way to store dates with different timezones in DateTimeField In settings.py, i currently have timezone turned on and set to: TIME_ZONE = 'US/Pacific' When i save date in the model: class DateStore(models.Model): date = models.DateTimeField() the date is automatically converted to US/Pacific zone which is fine, but when i try to save date with timezone set to UTC, those dates are also converted to US/Pacific. I need the timezone info saved and not be replaced with the set timezone in settings.py Note: I already know we can have a text field that stores zone information and then we can localize accordingly, but my question is that can we preserve timezone info from datetime when saving instead of replacing it with saved TIME_ZONE. -
An issue making addition through models.py making a simple calculation
Hello guys im practicing on django by now developping a simple expense tracker for a main project expample: Buying a flippable car for X amount and adding all the other expenses to get a single total. my operation is mainly done in my model.py models.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) amount = models.FloatField() description = models.TextField(blank=True, null=True) def __str__(self): return self.title class Expenses(models.Model): project = models.ForeignKey(Project, related_name='expenses', on_delete=models.CASCADE) title = models.CharField(max_length=100) amount = models.FloatField() def __str__(self): return self.title def get_total_project_amount(self): return self.amount + self.project.amount What i wanna do is adding the main project and all the expenses togheter, but im not using the proper way, when i render the resuld it renders like this: main project: 50$ expenses added from a model form : 2(new) expense: 13(new) expense: 25(new) the total is: 52 total: 63 total: 75 when i wanna di is render the main project and all the expenses to get a single result, something like 50+2+13+25 total : 90$ total amount soent to fix the car. Anyone that understand addition lojic help please and thank you . -
How to serialize DateTimeField in Django
How can I serialize dob field to achieve dob to be in the format; 03/Jan/2020 or 05-Feb-2021 class PersonSerializer(): .... ........ dob = serializers.DateTimeField(format="%d/%m/%Y") class Meta: model = Person fields = "__all__" -
python - Trailer slashes at the end of a Django URL
I was making an application that has parts to update and delete objects (cats) from my database. Before, the URL for Updating a cat data was written in urls.py in urlpatterns as : # in cats/urls.py path('updatecat/<int:cat_id>',views.Cat_Update.as_view(),name="update_cat"), and the view was similar to this : # in cats/views.py class Cat_Update(LoginRequiredMixin, UpdateView): model = Cat fields = "__all__" success_url = reverse_lazy("cats:main") template_name = 'cats/updatecat.html' def get_query_set(self, request): return Cat.objects.filter(id=escape(request.GET['cat_id'])) #I was editing the get_query_set because I wasn't sure what the name of the argument #needed to be written in the URL to be passed to the UpdateView is, and I want to finish as soon #as possible. But I think now that the name may not be too important, right? If it is not #allowed to answer more than one question, it's okay. the template was like: <!--in cats/templates/cats/updatecat.html--> <html> <body> <h1>Edit Cat</h1> <form action = "{% url 'cats:update_cat' object.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <input class="cats_sbmt" type="submit" value="Submit"/> </form> </body> </html> and when I go to this url, it gives me the error as Generic detail view Cat_Update must be called with either an object pk or a slug in the URLconf. And when I added a … -
Loading multiple keras models in django
I have 5 trained keras models with their weights saved. To get predictions, I first create the model with same architecture and then load the saved weights. Now, I wanna get predictions from all these models in django and return them as json response. Where should I load the models so that they are loaded only when the server starts?