Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
should pulled API data be stored inside a database
I am creating my own django project to show stats of fantasy premier league players (FPL) where i use API data from another website. In my own website i want users to be able to search and query these players based on certain attributes such as goals scored, minutes played etc... Am i best to store these values inside my own database to make the querying process easier and more efficient OR just filter out certain players from the API data in the json format OR do a combination of both methods -
Save python output into Django Models
I have this code in my views.py: def home_output(request): commandRun = 'python script.py' data = os.system(commandRun) print(data) return render(request, 'home-view.html', {'data': data}) So when I open the page in Django, there is button to run the above code. When I run the server, and click the button, I get errors on the screen, but I can see the output in my terminal, which means, button worked and ran the script. All I want is to capture that output, and show it on the web page. I'm new to Django, so I don't know how to approach this problem. Do I have to modify my script to go to django.models and save some data? Or should I do something in Django to capture the data? I need some guidance like how to go forward.. -
Django oscar cannot import 'Basket' and 'Order'
i'm running into an issue where the oscar library attempts to import 'oscar.apps.orderoscar'. throwing the following error: File "/usr/lib/python3.10/importlib/init.py", line 139, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'oscar.apps.orderoscar' It seems to me that the logical import should be 'oscar.apps.order' but it somehow won't trigger that import. I've ran the following command to grab all the 'oscar.apps.orderoscar' occurences within my django project: $find ./ -type f -exec grep -H 'oscar.apps.orderoscar' {} ; It outputs the following occurences: ./shop/shop/pycache/.settings.cpython-310.pyc.swp: binary file matches ./shop/shop/pycache/settings.cpython-310.pyc: binary file matches The .pyc files seem to be immutable from a security perspective as far as i could tell I've attempted to set a breakpoint in the '/usr/lib/python3.10/importlib/init.py' def import_module(name, package=None): if name == 'oscar.apps.orderoscar': name = 'oscar.apps.order' set_trace() This breakpoint is never reached. Any help or tips … -
django cors HTTP/1.1 200 OK
Can someone help me for this cors django problem. I request a link to get value but cors won't let me do this. image1 image2 function get_log_modal(id) { clearInterval(logInterval); $('#log_container').html("") $(location).attr('href', '#analysis_log'); logInterval = setInterval(function () { console.log("id", id) $.ajax({ url: `https://blablablabla/${id}/`, method: "GET", success: function (res) { . . . That is my cors problem -
Django admin list : how to specify custom field instead of model __str__ method?
I have a model that has multi attributes rendered in __str__ method. I only want to display the name attribute in the admin list display. How do I achieve this without overriding __str__? In the example below I have tried using list_display in the admin model but Django still renders the attributes in __str__ defined for the model. Model class Product(models.Model): """ Product """ id = models.PositiveBigIntegerField(primary_key=True) attributes = models.JSONField() labels = models.JSONField() name = models.TextField() relative_url = models.TextField() image = models.URLField() delivery = models.TextField() online = models.BooleanField() is_customizable = models.BooleanField() is_exclusive = models.BooleanField() url = models.TextField() max_price = models.PositiveIntegerField() min_price = models.PositiveIntegerField() currency = models.ForeignKey(Currency, on_delete=models.CASCADE) discount_percentage = models.PositiveSmallIntegerField(default=0) recommended_retail_price = models.PositiveIntegerField() def __str__(self) -> str: product_str = ( f"id: {self.id}\n" f"attributes: {self.attributes}\n" f"labels: {self.labels}\n" f"name: {self.name}\n" f"relative_url: {self.relative_url}\n" f"image: {self.image}\n" f"delivery: {self.delivery}\n" f"online: {self.online}\n" f"is_customizable: {self.is_customizable}\n" f"is_exclusive: {self.is_exclusive}\n" f"url: {self.url}\n" f"max_price: {self.max_price}\n" f"min_price: {self.min_price}\n" f"currency: {self.currency}\n" f"discount_percentage: {self.discount_percentage}\n" f"recommended_retail_price: {self.recommended_retail_price}\n" ) return product_str def get_absolute_url(self) -> str: return reverse("web:product-detail", args=[self.id]) class Meta: db_table = "product" ordering = ["recommended_retail_price"] Admin class ProductAdmin(admin.ModelAdmin): list_display = ("name",) form = ProductForm Form class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" -
pass a parameter into serilazer under ListModelMixin
I am passing a parameter to a serilaizer like this: serializer = AttractionTicketSerializer(attraction, context={'api_consumer':request.auth.application}) I have a view which inherits from ListModelMixin, I need to pass this context param to the serilizer as well. here is a summarized view: class AttractionView(mixins.ListModelMixin, generics.GenericAPIView): authentication_classes = AUTHENTICATION_CLASSES permission_classes = [IsAuthenticatedOrTokenHasReadWriteScope] queryset = Attraction.objects.all() serializer_class = AttractionSerializer def get(self, request: Request, *args, **kwargs): attractions: Dict[str, Any] = self.list(request, *args, **kwargs) return attractions Is there a way to do it? Thanx in advance -
How to stock a list in a Django Model?
I'm trying to stock a list in a Django Model like this : class Search(models.Model): result = models.CharField(max_length=100, null=True, blank=True) name = models.BooleanField(default=True) eotp = models.BooleanField(default=True) reference = models.BooleanField(default=True) date = models.BooleanField(default=True) contains = [] But I don't think that it's the best way to stock a list, because I have an error when i want to create an element (like this): new_search = Search(result=result, name=name, eotp=eotp, reference=reference, date=date, contains=contains) "Search() got an unexpected keyword argument 'contains'" Do you know if there is a better way to stock lists in django models or if I have to do this in another way ? Thanks -
Django Problem with count of model objects
I need to disable adding new users in the admin panel once the number of users exceeds a particular value. The code below works to remove the "add user" button when I test it with hard coded integers. However, this line does not appear to be returning the count of users without hard coding a count: usercount = CustomUser.objects.count() Any ideas for getting the count of users already added? The model: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group from django.contrib import admin from django.db.models import Count from django.db.models.signals import post_save class CustomUser(AbstractUser): full_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1) is_active = models.BooleanField(null=False, default=True) # disable add new user in the admin panel class RemoveAddNew(admin.ModelAdmin): usercount = CustomUser.objects.count() if usercount > 5: def has_add_permission(self, request, obj=None): return False The admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser, RemoveAddNew class CustomUserAdmin(RemoveAddNew, UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'email', 'full_name', 'age', 'is_staff', 'is_active'] fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('full_name', 'age', )}), ) add_fieldsets = UserAdmin.add_fieldsets + ( (None, {'fields': ('email','full_name', 'age', 'employee_type', … -
Why static files for drf views dont work on my hosing site, but on local it works
There is how it looks on hosting: enter image description here There is how it looks on local: enter image description here -
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.