Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering different ModelForms based on dropdown field
I have several different profiles I want people to be able to create (let's call them special types of Apples). I am rendering the base Apple form, which contains a drop-down for the type of Apple, Red Apple or Green Apple. Based on this drop-down, I'd like to also display the RedAppleProfileForm, or the GreenAppleProfileForm, ModelForms based off the profiles. How do I conditionally render these forms? I have tried rendering both of them with display: none, and changing the display based on selected element value, but because the fields of the rendered forms are mandatory, I can't ever submit, even if the form has display: none. If there is a way around this, this is a solution. Relevant Stack: How to render django form differently based on what user selects? Notes on this stack: The solution with 4 upvotes seems to work for 2 profiles, such as Red and Green apples, but in my scenario I happen to have 5 different types of Apples, and I don't know how I'd make it work then. The accepted solution could work maybe but I don't fully grasp how? Would I just a BaseForm inherit all 5 of my ProfileForms? Python3.8, Django … -
Django, how to get attribute of forignkey related object
I have below models, class Model_1(models.Model) price = models.IntergerField() class Model_2(models.Model) product=models.ForeignKey(Model_1) quantity = models.IntergerField() @property def totalprice(self): return self.quantity * self.product__price arr = [obj1,obj2,obj3] # objects of Model_2 I am getting error that arr objects has no attribute 'product__price' -
Make push notification from celery function
I'm trying to show a message using Django message, but this alert should be executed when a certain event happened on @shared_task. This is my celery function code in tasks.py def show_message_in_time(self,response): while True: # get_info_to_show() this function will do something messages.info(response, 'Your email is added successfully!') sleep(2*60) and this is the function on views.py def index(response): show_message_in_time.delay(response) return render(response, "Sales.html", {'zipped_list': objs}) Below is the error I received Exception Value: Object of type 'WSGIRequest' is not JSON serializable I have tried to convert WSGIRequest to JSON and also that's not working. Any help would be appreciated! -
Add additional initializing arguments for forms.Form __init__
I am creating a form and want to add a dynamic argument as following: from django import forms def get_quantity_choices(avail_qty): return [(i, str(i)) for i in range(1, avail_qty)] class QuantityForm(forms.Form): def __init__(self, request, avail_qty, *args, **kwargs): self.avail_qty_choices = get_quantity_choices(avail_qty) quantity = forms.TypedChoiceField( choices=avail_qty_choices, coerce=int) so that I could do this form = QuantityForm(request.POST, available_quantity) where available_quantity is a variable dynamically generated elsewhere in my app. But I keep getting this error message "Undefined name avail_qty_choices" . What am I doing wrong? -
How to use javascript to query db and create array
I have a database with the following table: Product_table The product table has 3 columns; product_name, product_info, and product_cost I need to query the database in order to pull all product names out, and put them in an array. I know the SQL is 'SELECT product_name FROM product_table' but I don't know how to implement that in javascript. Any guidance would be greatly appreciated -
How do you get the name of an url in django [closed]
I have a for who gives me urls and I want to get the name of the url he clicked in to put it in a variable. Like here google I want it to take you to google.com but the name is ilias I have this but in a for so I don't know how to do. <ul> {% for entry in entries %} <li><a href="http://project1-1--ilianocorp.repl.co/wiki/test">{{entry}}</a></li> {% endfor %} </ul> -
How to create a custom filter tag for a Django object?
I have a model called Profile. I want to create a custom filter tag based on this idea: Profile.objects.filter(user=request.user) Then I can use this filter within the template. Just complete this function: ` from django import template register = template.Library() from ..models import Profile @register...... def filter_profile(): .... Then how to use it from the template. And thanks. -
Permission Error loading efficientnet model in django aws app
I'm working on deploying a Django app on AWS. The website open fine, but when i try to run a deep learning model it gives me the following error Permission Error. /severity is the page of the website where this occured. Any and all help is appreciated :) Error Displayed on Site Request Method: POST Request URL: http://radiology-ai-env.eba-wgmpba4k.us-west-2.elasticbeanstalk.com/severity/ Django Version: 3.0.8 Python Version: 3.6.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'main'] Installed Middleware: ['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'] Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/current/app/main/views.py", line 62, in severity results = severity_model(image, mask) File "/opt/python/current/app/main/ml_models.py", line 11, in severity_model return Image_based_severity_prediction.run_model(image, mask) File "/opt/python/current/app/main/Image_based_severity_prediction.py", line 70, in run_model model_eff = EfficientNet.from_pretrained('efficientnet-b0') File "/opt/python/run/venv/local/lib/python3.6/site-packages/efficientnet_pytorch/model.py", line 211, in from_pretrained load_pretrained_weights(model, model_name, load_fc=(num_classes == 1000), advprop=advprop) File "/opt/python/run/venv/local/lib/python3.6/site-packages/efficientnet_pytorch/utils.py", line 327, in load_pretrained_weights state_dict = model_zoo.load_url(url_map_[model_name]) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/torch/hub.py", line 480, in load_state_dict_from_url os.makedirs(model_dir) File "/opt/python/run/venv/lib64/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/opt/python/run/venv/lib64/python3.6/os.py", line 210, in makedirs makedirs(head, mode, … -
Django, requests-oauthlib and 403 Forbidden error when trying to use access token for protected resource
I'm having a weird issue in django 1.6.10 at the very end of the oauth2 conversation using requests-oauthlib 1.3.0. The Django app is the oauth client and Wordpress is the ID provider (i'm using the Wordpress OAuth Server plugin). Basically, i can exchange the auth code for an access token just fine, but when i try to then retrieve a protected resource from Wordpress (/oauth/me) using that access token, i get a 403 forbidden error in django. HOWEVER, when i take that same access token to Postman and issue a POST request to /oauth/me with Authorization=Bearer , i get the protected user info back from WP just fine. Maybe it's something to do with the headers, or maybe the client scope (which is 'basic')? ''' def wp_profile(request): wordpress = OAuth2Session(WORDPRESS_CLIENT_ID, token=request.session['oauth_token']) #this is failing with a 403 Forbidden user = wordpress.get('https://imsestage.wpengine.com/oauth/me') <--this is failing with a 403 Forbidden return json.dumps({user}) ''' -
'QuerySet' object has no attribute '_meta' Model Query to JSON format
Im trying to make the filtered model query into a JSON object so i can handle it better in my template. This is my code: @login_required(login_url='login') def myPostView(request): posts = BlogModel.objects.filter(user=request.user.id) serialized_posts = serializers.serialize('json', [ posts,]) print(serialized_posts) context = {'posts': posts, 'serialized_posts': serialized_posts} return render(request, 'frontend/myposts.html', context) Ive researched and found out that i needed to searialize the data first using the django.core serializer. But it gives me this error: Request Method: GET Request URL: http://127.0.0.1:8000/myposts/ Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute '_meta' Exception Location: D:\projects\app\env\lib\site-packages\django\core\serializers\base.py in serialize, line 94 Any ideas on what im doing wrong? Any help would be appretiated! -
how to use a django custom template tag as a variable and iterate it with for?
I try to iterate a list that returned by a custom template tag: template tag: def xrange(): first_post = Post.published.all().order_by('publish')[:1] for p in first_post: first_post_year = p.publish.year last_post = Post.published.all().order_by('-publish')[:1] for p in last_post: last_post_year = p.publish.year holder = [] for n in range(first_post_year, last_post_year+1): holder.append(n) return holder this return a list I want to iterate this list in my base template something like: {% for i in {% xrange %} %} ... do somtehing ... {% endfor %} but I know thats impossible what can i do? Note: I dont want to render my base.html with view -
How can I change the format of timezone.now in django?
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Article(models.Model): title = models.CharField(verbose_name="Title",max_length=50) content = models.TextField(verbose_name="Content") publish_date = models.DateField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title I have this bunch of code and in publish_date I want date to be shown as I want but I cant format it,any solution please? For now,it outputs the data like this 2020-07-17 but I want to show day or month first.Thanks -
js onclick function doesn't work django (python) project [duplicate]
i have django project and resgitration form and submit button (class="btn") i want when click btn after print text in console but doesn't work. this is my code --> var p = document.getElementsByClassName("btn"); p.onclick = showAlert; function showAlert(event) { aler("onclick Event triggered!"); } this is html ---> <input type="submit" name="register" class="btn"> -
Overriding django admin pagination along with url parameters
I would like to implement custom pagination for my admin panel. My url looks like the following: http://localhost:8000/admin/items/?group_id=20 On this URL I do some work to filter the results using the parameter group_id (by overriding get_changelist method). The page results are corrects, the problem is my pagination ending up like this http://localhost:8000/admin/items/?p=1 whereas I would like the URL to be http://localhost:8000/admin/items/?group_id=20&p=1 and keep the parameter. Basically I want the same result as How to paginate Django with other get variables? but using Django admin. How can I keep the parameter along with the pagination? I've tried overriding pagination.html file but without any success. Thank you. -
How do i clear a this field is required form error for uploading a file in a registration form
i'm trying to create a registration page where on of the multiple users has to be to upload a file when registering a page but after following most tutorials nothing has been fruitful,to ensure the file being uploaded is sucessful kindly assist if you can I have tried the uploaded_file = request.Files['document], fs = FileSystemStorage[], file upload way i have also tried the if request.method == 'POST' and 'document' in request.FILES: uploaded_file = request.FILES['document'] way too among others. so views.py def DistributorSignUpView(request): if request.method == 'POST': form = DistributorSignUpForm(request.POST, request.FILES) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) context = ({'form': form}) return render(request, 'dashboard.html', context) else: form = DistributorSignUpForm() return render(request, "distregister.html", context={'form': form}) **forms.py** class DistributorSignUpForm(UserCreationForm): Tax_compliance_certificate = forms.FileField(required=True) class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'password1', 'password2', 'Tax_compliance_certificate'] @transaction.atomic def save(self): user = super().save(commit=False) user.is_distributor = True user.save() distributor = Distributor.objects.create(user=user) distributor.Tax_compliance_certificate.add(*self.cleaned_data.get('Tax_compliance_certificate')) return user **HTML** <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{form.username}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{form.email}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> {{form.password1}} </div> <div class="input-group … -
how can i read an image from postgresql database table and use it in face_recognition function in django
This is models.py class GeeksModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media/") def __str__(self): return self.title This is the views.py function images = GeeksModels.objects.all() connection = psycopg2.connect(user ='#####' , password = '#####', host = 'localhost', port='5432', database='######') cursor = connection.cursor() query = "select img from authen_geeksmodel" cursor.execute(query) images = cursor.fetchall() for img in images: face_2_image = face_recognition.load_image_file(img) face_encodings = face_recognition.face_encodings(face_2_image)[0] check=face_recognition.compare_faces([face_1_face_encoding] , face_encodings) The error it shows that it cannot read the images it must be in 8bit or RGB SO HOW CAN I READ THE IMAGES FROM MY DATABASE AND THEN USE THAT IMAGE IN MY FACE_RECOGNITION FUNCTION The main doubt I have how cant i convert the fetched image itno a readable image format -
Structure json response in Django Rest Framework
I am trying to implement Nested serializer for the first time in django-rest-framework My requirement is i need the response data in below form :- { id: 0, title: "Fresh", data: [ [{ image: ".../assets/images/banana.jpeg", name: "Fruits", image_scaling: 2, API: "http://database_api" }, { image: "../assets/images/banana.jpeg", name: "Vegetables", image_scaling: 2, API: "http://database_api" }, { image: "../assets/images/banana.jpeg", name: "Exotic Vegetables", image_scaling: 2, API: "http://database_api" } ] ] } I am validating the token for the get api and listing the objects form DB. My current implementation of views.py is :- class home(APIView): def get(self,request,format=None): header_token = request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: token = header_token access_token=token.split(' ')[1] print(access_token) if(validate_token(access_token) == None): raise NotFound('user does exist') queryset=Fresh.objects.all() print(queryset) serializer = FreshSerializer(queryset,many=True) return Response(serializer.data) Serializer.py is :- class DataSerializer(serializers.ModelSerializer): class Meta: model=data fields = ('name','image_scaling','image') class FreshSerializer(serializers.ModelSerializer): data=DataSerializer(read_only=True, many=False) class Meta: model = Fresh fields = ('title','data') models.py is :- class data(models.Model): name=models.CharField(max_length=9,null=True) image_scaling=models.IntegerField(default=0,null=True) image=models.URLField(max_length = 200) def __str__(self): return str(self.name) class Fresh(models.Model): title=models.CharField(max_length=9) data=models.ForeignKey(data,on_delete=models.CASCADE,default=None, null=True) def __str__(self): return str(self.title)+" " +str(self.data) My current output is :- [ { "title": "vegetable", "data": { "name": "vegetable", "image_scaling": 2, "image": "https......jpg" } }, { "title": "exoticveg", "data": { "name": "exoticveg", "image_scaling": 2, "image": "https://.......jpg" } … -
How to add media_root and media_url in Django
I am using Django 3, and I have tried every solution available on the internet, but none of them worked for me. When I set DEBUG=False, I am unable to display an image on the HTML page. Here are my settings -root_app --main_app ---settings.py ---asgi.py ---urls.py ---wsgi.py --sub_app ---admin.py ---urls.py ---views.py ---static ----style.css ---templates ----home.html ---media ----images media path in settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'sub_app','media') MEDIA_URL = '/media/' Here what I have done to resolve it add context_processor django.template.context_processors.media' add +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in url_patterns of urls.py of sub_app I changed static storage to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage', otherwise I got 500 error. Check this comment But still, I am unable to display the image at home.html page. When I click on image source using inspect element, I got this /media/images/img.png -
Setting up crontab for my Django Application
I had an issue with setting up crontab for my Django application for a week and I have almost figured out the same. (Issue linked with Unable to make a function call using Django-cron) My crontab -e syntax is * * * * * /Users/ashwin/dashboard/proj_application/exec.sh >> /Users/ashwin/dashboard/proj_application/data.log 2>&1 And in my exec.sh, I have #!/bin/bash cd "$(dirname "$0")"; CWD="$(pwd)" echo $CWD python -c 'import proj_application.cron as cron; cron.test()' And in cron.py, from django.core.mail import send_mail from smtplib import SMTP from email.mime.text import MIMEText import datetime def test(): message = "<p>This is test mail scheduled to send every minute</p>" my_email = MIMEText(message, "html") my_email["From"] = "xxx@domain.com" my_email["To"] = "yyy@domain.com" my_email["Subject"] = "Title" sender = "person1@domain.com" receivers = ["person2@domain.com"] with SMTP("localhost") as smtp: smtp.login(sender, "yyy@1234") smtp.sendmail(sender, receivers, my_email.as_string()) Actual Problem: The crontab is now able to call the exec.sh file and I am able to print $CWD in echo, when the call comes to cron.py, It is unable to recognize django.core.mail and throws the following error. from django.core.mail import send_mail ImportError: No module named django.core.mail I think, I need to set up virtual environment or python variable path somewhere, but since I am new to crontab, I am not sure how to … -
Django Form File Upload using Ajax
I have a django modelForm to upload files that will eventually be linked to a service request form. Since the request form and file form are on the same page, the files need to be uploaded asynchronously, hence using AJAX. When I run the following code, the ajax success message is received, but the file is not uploaded to the database. I've tried multiple ways and never can get the file to upload to the database. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.esr_submit, name='esr_submit'), models.py class File(models.Model): files = models.FileField( verbose_name="Attachments", name="files", upload_to="files/") def __str__(self): return str(self.files) def delete(self, *args, **kwargs): self.files.delete() super().save(*args, **kwargs) views.py from django.shortcuts import render, redirect, reverse from .forms import ServiceRequestForm, FileForm from .models import ServiceRequest, File from django.http import JsonResponse from django.core import serializers def esr_submit(request): files = File.objects.all() response_data = {} # ADDED if request.user.is_authenticated: initial_data = {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'email': request.user.email, 'contact': request.user.phone, } request_form = ServiceRequestForm(initial=initial_data) file_form = FileForm() else: request_form = ServiceRequestForm() file_form = FileForm() if request.method == 'POST': if 'submit_request' in request.POST: request_form = ServiceRequestForm(request.POST) if request_form.is_valid(): request_form.save() return redirect('/esr_submit/') if 'file_upload' in request.POST: file_form = FileForm(request.POST, request.FILES) if file_form.is_valid(): instance = … -
How to intervene to Django allauth when adding new user
I've got two questions I would like to add a group whith basic permissions to every new user when this user authenticate through Allauth (Google OAuth2). The main question is how can I actually do this, what tools should I use? Can you give me any tips/ links/ examples? The actual question is how to intervene to Allauth proccess of adding new user. I've got one user already in my database without social connections yet. But if he uses Authentication through OAuth (with the same e-mail which is already in the system) he's being asked to use another e-mail because it's already in use. Is it possible to change this in the way that such user will be automatically connected to existing one. I know there are possible security risks but I'm planning to perform some additional measures on this. -
How can i create a download view in django
def download_file(request): # fill these variables with real values fl_path = ‘/file/path' filename = ‘downloaded_file_name.extension’ fl = open(fl_path, 'r’) mime_type, _ = mimetypes.guess_type(fl_path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response -
How redirect user from login page once they login from social auth in django?
I try this code. In my app only authenticate with Github Auth (login with the only github) from django.shortcuts import render, redirect from social_django.models import UserSocialAuth from django.contrib.auth import authenticate, login, logout def user_login(request): user=UserSocialAuth.objects.all() if user.is_authenticated: login(request,user) redirect("/") print("login") else: return redirect(request, "registration/login.html") -
Calculate the total in django model Device based of each DevicePart Model including qty
I want to calculate the total items for the device which includes quantity for each part. Not sure whether the approach I used here is going to work. Need guidance. Thanks class Device(models.Model): device_model = models.ForeignKey(DeviceModel, on_delete=None) sku = models.CharField(max_length=50) desc = models.CharField(max_length=200) # total_price = models.FloatField(blank=True, null=True) def get_total_cost(self): device_list = DevicePart.objects.all() sum = 0 for each_part in device_list: sum = sum + each_part.order_total() return sum order_total = property(get_total_cost) print(order_total) class DevicePart(models.Model): device_model = models.ManyToManyField(DeviceModel) device = models.ManyToManyField(Device) part_number = models.CharField(max_length=50, blank=True, null=True) part_description = models.CharField(max_length=200, blank=True, null=True) service_duration = models.IntegerField(blank=True, null=True) unit_list_price = models.FloatField(blank=True, null=True) unit_net_price = models.FloatField(blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) discount = models.IntegerField(blank=True, null=True) extended_net_price = models.FloatField(blank=True, null=True) def get_cost(self): return self.extended_net_price * self.quantity -
Efficient way of checking if a User has permissions from a list and converting results to a dictionary
i wish to be able to do the following : Pass in a list of permissions , for example: ['can_change_xxx' , 'can_add_xxx',...] The function would convert it to {'can_change_xxx':True,'can_add_xxx':False,...} as efficiently as possible. The reason for doing so would be to create a permissions field serializer whereby i would pass the boolean values to the front end to do some conditional rendering.