Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTPServerDisconnected at /student/reset-password/
please run connect() first Request Method: POST Request URL: http://127.0.0.1:8000/student/reset-password/ Django Version: 3.1.8 Exception Type: SMTPServerDisconnected Exception Value: please run connect() first i am trying to send email confirmation in a django project and cant get over this error -
Should i store pulled API data inside a database?
I am starting a django project which is a website that will display data and analytics of fantasy premier league (FPL) players. I get this data from the FPL website using its API. (https://fantasy.premierleague.com/) My question is should at least some of this data be stored inside my own database to save pulling data multiple times that do not change. For example if i pull the data on a specific player i will want their name, points_scored_each_week , etc... In this case the value of name will never change so could possibly be stored inside a database instead of fetching name multiple times whereas the value of points_scored_each_week will change each week so should i bother storing this field inside a database and updating the field each week. Is this efficient? or should i store ALL data inside a database or fetch ALL data upon an API call -
How can I have an external script that tracks changes in database?
I am using Django and have a skeleton website with a single button that increments an IntegerField in my database. I want to have an external script which continually reads this IntegerField and reports when a change has been made. models.py class Counter(models.Model): count = models.PositiveIntegerField(default=0) views.py def index(request): ctr = Counter.objects.get(id=1) pre = ctr.count print(f"pre: {pre}") if request.method == 'POST': if request.POST.get("increment"): Counter.objects.filter(id=1).update(count=F('count') + 1) post = ctr.count print(f"pre: {pre}") return render(request, 'increment.html') I thought I could simply achieve this inside the view function but I've had difficulty detecting a change because the pre & post values above are the same when I print them even though post is clearly created after the field is incremented. I have a watcher.py file inside my app directory where I am trying to program a script that would run in the background and report changes to the database. Here's what I have so far: from django.conf import settings settings.configure(DEBUG=True) import django django.setup() import models import time from ahelper import settings from threading import Thread def watcher(): ctr = models.Counter.objects.get(id=1) pre = ctr.count print(f"{pre}") print("start loop") while (1): temp = time.time() post = ctr.count if pre != post: print("Change detected") response_time = (time.time() … -
How can I update my table with adding new field in model?
I have have model class like this, class Member(models.Model): firstname = models.CharField(max_length=255, verbose_name='Adı') lastname = models.CharField(max_length=255, verbose_name='Soyadı') email = models.EmailField(verbose_name='E-posta') companyname= models.CharField(max_length=300, verbose_name='Şirket Adı') companynumber = models.IntegerField(verbose_name='Vergi Numarası') def __str__(self): return self.firstname When i tried to add new field like this; companysize = models.IntegerField(verbose_name='Şirket Büyüklüğü') and running these command to migrate: py manage.py makemigrations py manage.py migrate My model doesn't update in db tables. This is my db settings for postgresql: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbedusite', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } How can i update table with migrations? -
Getting Error in Jinja using in Django Project
I am Facing an error in jinja while working on tables. I have a model name HOD which uses user as foreign key and contains other details about Hod such as mobile no, department, year, etc. Now I have a table in my html code in which I used jinja to load all hod details in the table using jinja for loop but I am unable to get first name and last name of hod. This is my code: <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Department</th> <th scope="col">Year</th> <th scope="col">Mobile No</th> </tr> </thead> <tbody> {%for hod in hods%} <tr> <th scope="row">{{hod.id}}</th> <td>{{user.hod.first_name}}</td> <td>{{user.hod.last_name}}</td> <td>{{hod.hod_of_department}}</td> <td>{{hod.hod_of_year}}</td> <td>{{hod.mobile_no}}</td> </tr> {%endfor%} </tbody> -
Django - Passing the creator of a form to the form
I am making an auction site. I need to know per listing who the creator was (so the creators will have the possibility to delete the listing). It works for me to manually change the user in Django Admin, but I want it to be automatically saved when someone creates a new listing. How do I pass the creator of a form to the form? These are the relevant models: class User(AbstractUser): pass class AuctionListing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=512, default="") starting_bid = models.DecimalField(max_digits=6, decimal_places=2, default=0.01, validators=[MinValueValidator(Decimal('0.01'))]) url = models.URLField(max_length=200, blank=True) category = models.CharField(max_length = 20) user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name="items") def __str__(self): return self.title Here is my forms.py: class CreateListing(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="No category") class Meta: model = AuctionListing fields = ('title', 'description', 'starting_bid', 'url', 'category', 'user') widgets = { 'title': forms.TextInput(attrs={'placeholder':'Write your listing title here...'}), 'description': forms.Textarea(attrs={'placeholder':'Write your comment here...', 'rows':3}), } And here was my attempt for the view: def create_listing(request): form = CreateListing(request.POST, user=request.user) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: print("RIP") return render(request, "auctions/create_listing.html", { "form" : CreateListing }) auctions/create_listing.html looks like this: <h1> Create new listing </h1> <form action="" method="POST"> {% csrf_token %} <label>Name*</label> <br> {{ form.title }} … -
PasswordResetView: context variable protocol return http instead of https
I use Django registration module in one of my app stack : django/postgresql/docker I override password reset view: class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'registration/password_reset_form.html' email_template_name = 'registration/password_reset_email.html' subject_template_name = 'registration/password_reset_subject.txt' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('home') and following template for reset password: Someone asked for password reset for email {{ email }}. Follow the link below: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} PS : Please do not reply to this email but email template context protocol return http instead of https what's wrong? -
How do I get some result in django models.py file in migrations
I'm new to django, I'm trying to get some output in the models.py file in migrations how do I fix the error in the models.py file. I have deleted my 0001_initial.py file and db.sqlite3 file and have run python manage.py makemigrations, python manage.py migrate, python manage.py inspectdb hospital Calculo.But It does not help. Database I'm using DATABASES = { 'default': { enter code here'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Tables in my 0001_initial.py file class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Calculo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('registration_date', models.DateTimeField(auto_now_add=True)), ('latitude', models.FloatField()), ('longitude', models.FloatField()), ], ), migrations.CreateModel( name='Hospital', fields=[ ('ID', models.IntegerField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('YEAR', models.IntegerField()), ('CLUES', models.CharField(max_length=15)), ('INSTITUTION_KEY', models.CharField(max_length=10)), ('MUNICIPALITY_KEY', models.IntegerField()), ('LATITUDE', models.FloatField(max_length=15)), ('LONGITUDE', models.FloatField(max_length=15)), ('DISTANCE', models.FloatField(max_length=5)), ('TRANSFER_TIME', models.FloatField(max_length=5)), ('NAME_OF_THE_UNIT', models.CharField(max_length=255)), ('TOTAL_OFFICES', models.IntegerField(null=True)), ('TOTAL_BEDS_IN_HOSPITALIZATION_AREA', models.IntegerField(null=True)), ('TOTAL_BEDS_IN_OTHER_NON_HOSP_AREAS', models.IntegerField(null=True)), ('TOTAL_GENERAL_PHYSICIANS_AND_SPECIALISTS', models.IntegerField(null=True)), ('NUMBER_OF_NURSES_IN_CONTACT_WITH_THE_PATIENT', models.IntegerField(null=True)), ], ), ] Error in the model.py file in migrations # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior … -
Django generate file and save it to model
My Django app generates a file. It takes img1.png and watermark.png and past them together and saves it again in the folder. Everything works as expected. This is the function: def generate(): img1 = Image.open(f'{current_path}/media/pdf/img1.png') img2 = Image.open(f'{current_path}/media/watermark.png') img1.paste(img2, (150, 250), img2) img1.save(f'{current_path}/media/pdf/generatedfile.png') When working locally on my computer everything is good with specifying the path. However, in production it does not work anymore. I need to save the generatedfile.png directly on AWS S3. For this reason I have create a simple model: class pngUploadModel(models.Model): auto_increment_id = models.AutoField(primary_key=True, default=True) image = models.ImageField(null=True, blank=True, upload_to="png/") I am able to upload images to this model using the admin interface. Everything still works as expected. Now to my struggle. I need to generate the image, and saving it "directly" to the model. Without saving it first to the path (because this will not work in production). Approach: def generate(): img1 = Image.open(f'{current_path}/media/pdf/img1.png') img2 = Image.open(f'{current_path}/media/watermark.png') img1.paste(img2, (150, 250), img2) img1.save(f'{current_path}/media/pdf/generatedfile.png') try: filename = pngUploadModel.objects.create() filename.image = img2 print('worked!') except Exception as e: print(f'this is the error message: {e}') Output: It creates an object in my model which I can see on my admin panel, but the model is empty, there is no image. … -
Permission Denied 401 when sending axios request between localhosts (React and Django)
I set up a django backend and a React frontend. The dango app renders the index.html where the production ready JS created with react is found. But when developing locally, I develop the react frontend on my localserver:3000. Now I am trying to fetch data from my django backend, but I keep on getting a 401 Permission error. I know the problem is because the request comes from different hosts, but I don't know how to solve it. My backend apis use token authentication, but even if I send the bearer token in the headers, I still get the same error: My code for the request is simple: axios .get(`http://localhost:8000/path/to/data/`, { headers: { 'Content-type': 'application/json', Accept: 'application/json', Authorization: `Bearer ${'here is my token'}`, }, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); When my react app makes this a production ready bundle and executes this on localhost:8000 there is no permission error, but I need to make it work from localhost:3000 because this is where I develop my app. Help is very much appreciated. Thanks in advance -
Project root or Document root for template
I want to make link as https://example.com/forjump in template. Making the link to forjump from root html. It works https://example.com/forjump However when from /temp directory, the link becomes like this. https://example.com/temp/forjump I am thinkig a few ways. Get root directory by Javascript Give project root from python to template. What is the best soltion? -
add padding to xml prettify function in python django
i'm a junior on python,i worte an xmlfunction for prettify xml using xml.dom.minidom this is the function : def payload_xml_prettified(self, instance): """Function to display pretty version of our xml data""" import xml.dom.minidom dom = xml.dom.minidom.parseString(instance.payload_xml) xml_pretty_str = dom.toprettyxml() return xml_pretty_str payload_xml_prettified.short_description = "payload_xml" it works fine but without a padding the reult like this : : <?xml version="1.0" ?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> how can i update the code to show the xml on the right way with padding to shown like this : <?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies and thanks for support -
django url accepts None
My url is like this below. it accepts /tracks/1 ,/tracks/2 path('tracks/<int:pk>',views.tracks,name='tracks'), However I want to accept /tracks without pk value. How can I do this? -
Django freezes when reading data from request.body
Let's say we have a simple Django view: def my_view(request): content = request.body # some actions with content varible response = HttpResponse('<h1>It work!</h1>') And a simple api client, let's say based on the requests library, sending malformed Django view data: headers = dict() headers['Accept'] = '*/*' headers['Content-Length'] = '13409' headers['Content-Type'] = 'application/x-compressed' headers['Expect'] = '100-continue' headers['Host'] = '127.0.0.1:8000' headers['User-Agent'] = 'Api client' headers['content-encoding'] = 'gzip' url = 'http://127.0.0.1:8000/api' request_body = '' r = requests.post( url, data=request_body, headers=headers ) As you can see, request_body contains an empty string, but the Content-Length header stores the value 13409. When such a request arrives, Django hangs on the line reading request.body. No exceptions occur. How to solve this problem? I cannot influence the client, so the only thing I can do is rewrite the Django view. Django version 3.2.15 is used. -
Django model field custom validation
I am using Django 3.2 I have a model Foo, which has a field roles, that is a CharField, but I want to add custom validation on that field, so that it only accepts valid python class/variable names in a comma delimited string. This is what I have so far: from django.core.validators import RegexValidator from django.db import models # For now, keeping things simple and only accepting alphanum starting with alpha char CSV_Validator=RegexValidator('^[a-zA-Z][0-9a-zA-Z]*(?:\s*,\s*[a-zA-Z][0-9a-zA-Z]*)*$') class Foo(models.Model): roles = models.CharField(max_length=256, blank=True, null=True, validators=(CSV_Validator,) ) in testing however, the following strings are being passed successfully: "Foo/?" "FooBar" Clearly, the validation is not being applied. For the second case, I want to write a clean() method for the field (like is done in Forms), but I can't find how to do that in the documentation - also, not sure, if the clean() will work if model access via shell (I don't want to override save() if possible - unless that's the best place to do all this). Question is - why is my custom validation not working? -
Swagger with django - why am I getting a missing coreapi.Document error?
I'm trying to get a nice swagger UI working for a django webserver, but am running into a cryptic error. urls.py from django.urls import path from djangofun import views from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer schema_view = get_schema_view(title='API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('', schema_view), path('hello/', views.hello) ] views.py from django.http import HttpResponse from django.views.decorators.http import require_http_methods @require_http_methods(["GET"]) def hello(request): return HttpResponse("Hello world") The error, displayed as a webpage at localhost: I am unsure how to correct this issue, perhaps I am missing something obvious? The documentation (that I found) didn't help. Note that if I remove the renderer_classes kwarg from the get_schema_view function, there is no error, but I am not given the swagger UI I am looking for. -
How to stay on Same Product after Add to Cart?
I make my E-Commerce Website using Django. When I use Add to Cart functionality on the website refresh the page & I go to the top of the page. But I want the user to stay on the same Product after Add to Cart. Add To Cart function is made using Session in Django, not JS. So I want when users use Add To Cart Function user stay on the same product. I think this thing is possible using JS. This is Add to Cart button <form action="{% url 'cart:AddCart' %}" method="POST">{% csrf_token %} <input hidden type="text" name="product" value="{{i.id}}"> <button id="clickMe" class="main-btn cart cart-btn" style="padding: 5px 32px">Add <i class="fa-solid fa-cart-shopping"></i></button> </form> -
Django perform custom SQL directly
This is my first time to execute custom SQL directly, How to add dynamic string value inside the sql query? I try some of the example and docs from django sql but still not working. def insert_sql(): dn = datetime.today() - timedelta(days=1) dn = str(dn) date_input = datetime.strptime(dn[:-7],'%Y-%m-%d %H:%M:%S') date_input= date_input.strftime('%Y-%m-%d') sql = '''INSERT INTO table name( ........................ more sql here WHERE item IS NOT NULL AND disc <> '-' AND date= '{date}' ''' with connections['db_2'].cursor() as cursor: cursor.execute(sql) row = cursor.fetchone() return row The error is: django.db.utils.ProgrammingError: syntax error at or near "{" LINE 485: AND date= {date} please help me. Thnank You! -
Is there a way to render a Django formset in Jinja2 using the batch filter to create a grid?
I'm looking to render a Django formset similar to a spreadsheet with rows and columns. I was hoping to use the Jinja2 filter "batch" to create the columns but I'm not sure if that is possible. I know I can render the formset using for loops in Jinja but it's getting very messy as I've also got to add non-form information at points in the rendering and the position of that information is dynamic. Ideally, I would like to set the column loop up with "batch", then apply another set of loops to render the actual column forms and non-form data, then repeat this for each column. I appreciate any input or insights you may have. -
Python Threading blocks the django server when using thread.join
I'm looking to run a function without blocking the whole server. import threading def heavy_function(my_args): # heavy stuff here . . A solution for me would be to create a thread to allow the server to respond to user requests t = threading.Thread(target=heavy_function,args=(my_args,),daemon=True) t.start() t.join() #once thread is over do some other stuff . . . t.join() should wait for a thread to finish. Except that it blocks the whole server. Is there something equivalent that allows me not to block the server while waiting for the thread to end? Celery is not at all suitable for what I do, thank you for not proposing this solution -
how to integrate django-parler and django-polymorphic in the right way
I tried to follow the django-parler documentation to integrate django-parler with django-polymorphic, and was doing something like this class TestQueryset(TranslatableQuerySet, PolymorphicQuerySet): pass class TestManger(TranslatableManager, PolymorphicManager): queryset_class = TestQueryset class Test(PolymorphicModel): price = models.CharField(max_length=30) class TestChild(Test,TranslatableModel): default_manager = TestManger but the problem is that I want to have the translated fields in the base class Test, how can I exactly do that, because in the documentation i only found a way to add it to the subclasses -
Formatting ouput table in template from django.model
I am creating a currency exchange rate aggregator app. I have got next models. class Bank(models.Model): bank_name = models.CharField( max_length=30, blank=False, unique=True, ) class ExchangeRate(models.Model): USD_in = 'USD_in' USD_out = 'USD_out' EUR_in = 'EUR_in' EUR_out = 'EUR_out' RUB_in = 'RUB_in' RUB_out = 'RUB_out' USD_EUR_in = 'USD_EUR_in' USD_EUR_out = 'USD_EUR_out' exchange_choise = [ (USD_in, 'USD_in'), (USD_out, 'USD_out'), (EUR_in, 'EUR_in'), (EUR_out, 'EUR_out'), (RUB_in, 'RUB_in'), (RUB_out, 'RUB_out'), (USD_EUR_in, 'USD_EUR_in'), (USD_EUR_out, 'USD_EUR_out'), ] datetime = models.DateTimeField( auto_now_add=True, blank=False, ) exchange_type = models.CharField( max_length=12, choices=exchange_choise, ) rate = models.FloatField() bank_id = models.ForeignKey( Bank, on_delete=models.CASCADE, ) quantity = models.IntegerField( default=1, ) Basically two tables. One stores bank names, another exchanging currencies and their rates. So if I will output data from model as it is I will get next picture: Notice, that each currency exchange rate takes one row (datetime, currency, rate, bank). And I want to display rates in the format in table on webpage. I wonder, how can I do this? Do I need to perform some join operation or to write code in template to format it like this. -
How to implement custom redirects?
I have an eCommerce web app. A user may browse items while being logged in. If a user is logged in and registered, but hasn't entered their shipping address information (not required for initial account creation) and tries to purchase an item by clicking on the 'purchase' button which is mapped to a checkout view in my views.py, I want to first redirect that user to a shipping address form that I have set up in a different view and template, and then after they have successfully entered their shipping address info I have a boolean field for the user called address_verified which I will then set to True, redirect them back to the purchasing page so they can proceed with the purchase. Basically, I want to implement the same functionality of Django's @ login_required(login_url='/account/login') decorator that creates this redirect url query: '?next=/redirect/to/url' -
python program question, use django as example
I think this question is about python program, it is not how to use django. I am confused about QuerySet, what is it? # print(Hotel.objects.all().values()) # output <QuerySet [{'x': 1}, {'y': 2}]> # type print(type(Hotel.objects.all().values()) #output <class 'django.db.models.query.QuerySet'> # like list print(type(Hotel.objects.all().values()[0]) #output {'x': 1} Why print(Hotel.objects.all().values()) , it is not just return [{'x': 1}, {'y': 2}]? And why it could be operate like list, but type() show it is not list? JsonResponse(Hotel.objects.all().values(), safe=False)) show TypeError: Object of type QuerySet is not JSON serializable I think it like list [], so it could be serializable. But, actually, it could not be serailizable. However, it could work like list. ex: list methods all work, also iteration. -
What kind of expectation I have to put in this error? (SSLCertVerificationError)
Sometimes I get this error and want to know which expectation I should set to try sending the query again: HTTPSConnectionPool(host='x.x.x', port=443): Max retries exceeded with url: /api/x/x/x/x (Caused by SSLError(SSLCertVerificationError("hostname 'api.exmple.com' doesn't match either of '*.azureedge.net', '*.media.microsoftstream.com', '*.origin.mediaservices.windows.net', '*.streaming.mediaservices.windows.net'"))) my code : if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,auth=(username, password),verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,verify=True) exemples: except ssl.SSLCertVerificationError except ssl.SSLError List ssl.CertificateError Thank you in advance