Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error I don't understand in my template
error: 'Manager' object is not iterable This is what it shows: 51 <div class="row"> 52 <div class="ads"> 53 {% for ad in ad_item %} 54 {% ifequal ad.redirect 'False' %} 55 <img src="{{ ad.pic }}"></img> 56 {% endifequal %} 57 {% ifnotequal ad.redirect 'False' %} 58 <a href="{{ ad.redirect }}"><img src="{{ ad.pic }}"></img></a> 59 {% endifnotequal %} 60 {% endfor %} 61 </div> 62 </div> This is my view: from django.shortcuts import render, get_object_or_404 from django.views.generic.list import ListView from videos.models import video, ad from django.template import RequestContext def show_vid (request, pk, pkv): video_ = get_object_or_404(video, pk=pk) ad_item = ad.objects return render (request, 'video.html', {'video_': video_, 'ad_item': ad_item}) This is my template: <div class="row"> <div class="ads"> {% for ad in ad_item %} {% ifequal ad.redirect 'False' %} <img src="{{ ad.pic }}"></img> {% endifequal %} {% ifnotequal ad.redirect 'False' %} <a href="{{ ad.redirect }}"><img src="{{ ad.pic }}"></img></a> {% endifnotequal %} {% endfor %} </div> </div> What's the error, and what do I need to fix? -
How to ensure async operation executed during transaction has access to data written within transaction?
I have transaction within which I send pub/sub message. Pub/sub message handler should read data written during transaction. It seems like sometimes pub/sub handler is being executed before transaction completion which results in missing data. How can I ensure that pub/sub handler has required data? I am using python + django and it provides on_commit handler which is performed after transaction committed. But if I send pub/sub message from there then it is possible that transaction commits but for whatever reason sending pub/sub message fails and then I end up in a state when database is updated but pub/sub handler was never executed. Any other mechanism I can use for this? -
django.db.utils.OperationalError: no such function: JSON_VALID
I literally don't know how deal with it and how it is happening I am getting this error when i run python manage.py migrate migrations was without error Mycode models.py from django.db import models import uuid from django.contrib.auth.models import User # Create your models here. class Orders(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) products = models.CharField(max_length=6000) zip_code = models.IntegerField() address = models.CharField(max_length=600) city = models.CharField(max_length=600) state = models.CharField(max_length=600) email = models.EmailField() date = models.DateTimeField(auto_now=True) views.py from django.core import serializers @login_required def checkout(request): user = User.objects.get(pk=request.user.id) cartItems = Cart.objects.filter(user=user) cartJson = serializers.serialize('json', cartItems) print(cartJson) price = 0 for cartItem in cartItems: price = price + cartItem.cart_item.price * cartItem.quantity message = "" if request.method=="POST": products = request.POST['products'] email = request.POST['email'] address = request.POST['address'] city = request.POST['city'] state = request.POST['state'] zip_code = request.POST['zip'] order = Orders(products=products, user=user, email=email, address=address, city=city, state=state, zip_code=zip_code) order.save() message = "Order Successfully Placed" cartItems.delete() context = { 'message' : message, 'cartItems' : cartItems, 'price' : price } return render(request, 'ecom/checkout.html', context) If you are able to solve the issue then answer and along with it also tell me any issue in my code or any bad practice in my code If at all answerer 😂! … -
Local host not opening up another page withing local host
i have a local host that i am running my mock website on and i am using python and django as well. i wanted the local host open another link which is the other page i have set up but how would i able to let the page that runs on local host to open the other link which should open up another page to the sign up page! would i need another local host server to open the other page? i have already tried redirect the other page to another local host number but still no avail. i hope i made myself clear any help would do. -
Use same login credentials for both app where Django is backend, more like SSO
I have a web app, which uses Django as a backend. Due to special requirement, we had to build a UI on the Django side as well. More like the existing Django Admin with limited functionality. We have two web app, one of which is developed using angular and the other using simple ajax and jinja template on Django. Now I need to redirect from the Web app at a click off button from the Angular app to the Django based web app passing the credentials as well side by side. We are trying to inhibit more of a single sign-on like feature. Is there a simple and efficient way to pass the credentials? Should I take the credentials from local storage where the other app has stored the credentials? -
How to setup OIDC for Django / Django-Rest-Framework
I need to build a Django web-app. My web-app needs to support authentication and authorization using OpenID Connect. It is my first time doing this. I have a service which requires clientId and clientSecret and the typical endpoint urls. I have no idea what library to use and how to configure it. I'm using Django 3.1.7. I'm open to answer questions if I missed something -
How do I count() only the distinct values on a specific field when returning a queryset
I have a function that returns a queryset that is a list of records that I would like to return the count() of the records which it does BUT I want to only count the distinct values from a specific field. I can easily do this in a SQLite query but cant seem to get it in Django. Here is the SQLite Query that works BUT I need to do this in a Django View: SELECT DISTINCT Host FROM inventory_scandata WHERE Project_Assigned LIKE '%Hooli%' AND Environment LIKE '%PROD%' Here is my current function that returns the non-distinct count: def HooliProject(request): prodAssets = ScanData.objects.filter(Q(Project_Assigned__icontains="Hooli_1") & (Q(Environment__icontains="PROD"))) prodAssetsHosts = prodAssets.distinct() prodAssetsDistinct = prodAssetsHosts.distinct() prodAssetsCount = prodAssetsDistinct.count() context = { 'prodAssets': prodAssets, 'prodAssetsCount': prodAssetsCount } return render(request, 'HooliProject.html', context) -
How to change language in Swagger-ui docs (Multi-lingual support)
Is there a way of changing swagger UI documentation to any language in Django -
Django SMTP not working even port is open
Hi I am using Django Version 3.1 and using send_mail() fnction of django. It is working perfectly fine locally and emails are being sent. But When i try it on VM instance of GCP it do not send emails instead i get error of Network Unreachable. all ingress and engress traffic is allowed in my instance i even then made a new rule for port 587 but still cant send email. All other python requests are working fine. I tested with telnet and my port is open as well. Any Help will be really appreciated. -
Profile() got an unexpected keyword argument 'user' while extending django's User model
Here I have extended django's user model with profile model and i want to add this fields to user model. Following are the files. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user_ref = models.OneToOneField(User, on_delete=models.CASCADE) pr1_points = models.IntegerField(default=0) pr2_points = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): user = instance if created: profile = Profile(user=user) profile.save() @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() register function in views.py is as follows : ''' def postregister(request): if request.POST: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username=username).exists(): messages.error(request, 'Username is Taken Please Try Again') return render(request,'signup.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'Email is Taken Please Try Again') return render(request,'signup.html') else: user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=password1) user.save() print('You are registered successfully, Please sign to continue.') return redirect('login') else: messages.error(request, 'Password is not matching Please Try Again') return render(request,'signup.html') else: return redirect('register') ''' so while creating new user it is giving error as: Profile() got an unexpected keyword argument 'user'. SO please anyone know the answer help me with this. -
Django pass a url kwarg into a form.Form
I'm trying to get initial values for a form.Form class form from url. urls.py path('nueva/<client_id>/', new_check_view, name='nueva valoración'), views.py def new_check_view(request, client_id): my_form = NewCheckForm() # print (client_id) if request.method == "POST": my_form = NewCheckForm(request.POST) if my_form.is_valid(): Check.objects.create(**my_form.cleaned_data) else: print(my_form.errors) context = { "form": my_form } return render (request, 'checks/new-check.html', context) forms.py class NewCheckForm(forms.Form): user_id = forms.ModelChoiceField( label='Nombre', queryset= Client.objects.all(), initial=client_id, ) However, I don't get how to pass that kwargs from the view to the class form. -
update view don't save the bank
I wanted to know how I do it here to update this form in the bank, I am using 2 forms with different models and every time I try to save the information they are not exchanged and I get an invalid form error. class PacienteUpdateView(UpdateView): queryset = Endereco_pacientes.objects.all().select_related('cpf') form_class = PacientesModelForm second_form_class = EnderecoPacientesModelForm template_name = 'pacientes/pacientesForm.html' #get_success_url = '.' def get_context_data(self, **kwargs): context = super(PacienteUpdateView, self).get_context_data(**kwargs) context['form'] = self.form_class(instance=self.object.cpf) context['form2'] = self.second_form_class(instance=self.object) print(context['form']) return context I can already display the information in HTML, but I cannot update I thank the attention -
Django Management Command Generating Model Entries Corrupts File if File Is the Same on Each Entry
I have a custom management command in Django that generates an email to be added to the "django-mail-queue" app MailerMessage model. This tool reads from an existing table for information. However I am having issues with attachments where the first one, the attachment is fine, but the second one the attachment is corrupted. My belief is that Django is queuing up all the SQL commands and executing them all at once and thus reading the attachment file all at the same time for every entry. I think this is causing a race condition that is corrupting the second attachment. This is the code for send_to_user in send_to_users: msg = MailerMessage() msg.subject = campaign.subject msg.from_address = from_address msg.to_address = send_to_user.email msg.html_content = f"some content" # ATTACH THE ATTACHMENTS if attachments: for attachment in attachments: msg.add_attachment(attachment=attachment.file_attachment) msg.save() How do I get it to save directly without causing this race condition? Shouldn't msg.save() save to the database right away at the end of the for loop and then process the next one? -
Convert Base64 format Images to single pdf file and store it to django model
I have several images in data: format I need to convert them into a single pdf file in landscape mode and store them in Django model filefield. How can I achieve this in Python? -
How do I fitler the intial table using django-tables2 and django-filter?
I'm using django-tables2 and django-filter to list employees from a model. I'm having trouble filtering the initial table rendered. It's including all records. I want the initial table to only include employees where status=1. Then, have the filter take over. views.py from .models import Employee from .tables import EmployeeTable from .filters import EmployeeFilter from .forms import EmployeeSearchForm class EmployeeListView(SingleTableMixin, FilterView): model = Employee table_class = EmployeeTable template_name = 'employees/employee_list.html' filterset_class = EmployeeFilter def get_table_data(self): return Employee.objects.filter(status=1) filters.py: from django.db.models import Value, Q from django import forms from .models import Employee class EmployeeFilter(django_filters.FilterSet): search = django_filters.CharFilter(label='Search', method='search_filter') inactive = django_filters.BooleanFilter(widget=forms.CheckboxInput, label='Inactive', method='include_inactive') def search_filter(self, queryset, name, value): return queryset.annotate(fullname=Concat('first_name', Value(' '), 'last_name')).filter( Q(fullname__icontains=value) | Q(g_number__icontains=value) ) def include_inactive(self, queryset, name, value): expression = Q(status__in=[1,2,5]) if value else Q(status__in=[1,5]) return queryset.filter(expression) class Meta: model = Employee fields = ['search', 'inactive'] tables.py: from django.utils.html import format_html from django.urls import reverse import django_tables2 as tables from .models import Employee class EmployeeTable(tables.Table): full_name = tables.Column(order_by=("first_name", "last_name")) g_number = tables.Column(linkify=True) selection = tables.columns.CheckBoxColumn( accessor='pk', attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False ) term = tables.Column(verbose_name=("Action"), empty_values=()) class Meta: model = Employee template_name = "django_tables2/bootstrap.html" fields = ("selection", "g_number","full_name", 'org', 'job', 'status', 'term') attrs = { "class": … -
Zappa project and virtualenv have the same name
When running zappa deploy dev I get this error: Warning! Your project and virtualenv have the same name! You may want to re-create your venv with a new name, or explicitly define a 'project_name', as this may cause errors. Would renaming virtualenv be a safer route or renaming the project? How do I define a project_name explicitly? -
How to display a queryset object name rather than a queryset object itself in Django?
Registered users of my app can create and delete expense tracking sub-accounts. When deleting, they get to pick which account to delete: The above image shows the current choices. I would like to display the name of the account, rather than the object which the name is referring to, but how? forms.py class UdaForm(forms.Form): # User Deleted Account Form def __init__(self, *args, user, **kwargs): super().__init__(*args, **kwargs) self.user = user self.fields['UDA_name'].queryset = UserMadeAccount.objects.filter(UMA_user=user) UDA_name = forms.ModelChoiceField(label="Account", queryset=UserMadeAccount.objects.all()) views.py def user_accounts(request, user_id): if request.user.is_authenticated: # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in user_made_accounts] if "UMA_form_name" in request.POST: if request.method == 'POST': uma_form = UmaForm(request.POST) uda_form = UdaForm(user=request.user) if uma_form.is_valid(): # Adds new user made account to the DB add_uma(uma_form, request.user) # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in user_made_accounts] return render(request, 'user_accounts.html', {"uma_form": uma_form, "uda_form": uda_form, "user_data": user_data}) if "UDA_name" in request.POST: if request.method == 'POST': uda_form = UdaForm(request.POST, user=request.user) uma_form = UmaForm() if uda_form.is_valid(): # Delete user made account from DB delete_uma(uda_form=uda_form, user_obj=request.user) # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in … -
Is it ok to include root django app in list of apps in settings
Say I create a django project called: recipes can I include that core folder (not a proper django app i think, with urls and core things) in my list of INSTALLED_APPS = [ 'recipes' ] This is so I can put things like management commands in a centralised place, rather than having to have an app called home or core, as I like to do normally. It seems to work are there any drawbacks with this? -
How to properly use front-end technologies liker webpack with Django?
We have a Django project using Bootstrap. I think this is common. Now I'm looking at adding more javascript functionality, e.g., hotkeys. Two options are Download the jquery plugin and load it directly using Django's static tag. I've set up ManifestStaticFilesStorage that does cache-busting on static assets. Set up a front-end technology stack: npm (or yarn), load my own jquery and bootstrap, likely compile it with Webpack. And .. rip out ManifestStaticFilesStorage because Webpack also does cache-busting? I'm not sure. Wouldn't that also break Django's static tag? I've read many different posts now, and the Django and front-end communities mostly seem to ignore each other. Maybe django-npm is the answer? How do people manage front-end assets in Django? -
Is there any function in python or can we create it in which we can give input (string) and in return output (dictionary)?
I am using OCR to read invoice from pdf and able to extract them in string format. now i want to store in Json format in Database. below is input in which i am able to extract key and value by: keys_=["None" if x == '' else x for x in unclean_data[2].lower().split(',')] print(keys_) key_: ['units ', 'item code ', 'description ', 'unit price (inc-gst) ', 'discount % ', 'total (inc-gst) ', 'None'] values_=["None" if x == '' else x for x in unclean_data[3].lower().split(',')] print(values_) value_: ['31.68 ', 'vhc ', 'amstel blanco 60x120 ', '$39.60 ', 'None', '$1', '254.53 ', 'None'] now using res_two = dict(zip(key_,values_) i am able to convert it, but i want to search key using regular expression in input and replace it with the keys show in the output. example **enter code here** "Item_Code","Description","Quantity","Unit_price_ex_GST","Value_ex_GST","GST","Discount%","Total(Inc_GST)" Input = Table: Table_1 Units ,Item Code ,Description ,Unit Price (inc-GST) ,Discount % ,Total (inc-GST) , 31.68 ,VHC ,Amstel Blanco 60x120 ,$39.60 ,,$1,254.53 , 1 ,D0001 ,Delivery Charge ,$145.00 ,,$145.00 , Expected Output = { "Item_Code":"VHC", "Description":"Amstel Blanco 60x120", "Quantity":3, "Unit_price_ex_GST":$39.60 , "Value_ex_GST":40.91, "GST":'', "Discount%":'', "Total(Inc_GST)":$1,254.53 }, -
Hot to display latest saved image from django form?
i'm uploading image in my django form and and displaying them all at same time. I want to know how to display latest image after submitting that form. Any help would be appreciated. models.py class Upload(models.Model): image = models.ImageField(upload_to='images') action = models.CharField(max_length=50, choices=CHOICES) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) forms.py class UploadModelForm(forms.ModelForm): class Meta: model = Upload fields = [ 'action', 'image' ] views.py def picture_create_view(request, pk=id, *args, **kwargs): if request.method == 'POST': form = UploadModelForm(request.POST, request.FILES) if form.is_valid(): form.save() context = {'form':form,'up':Upload.objects.order_by('-pk')[0]} return render(request, 'upload.html', context) else: form = UploadModelForm() return render(request, "upload.html", {"form": form}) I think problem is with line in views.py context = {'form':form,'up':Upload.objects.order_by('-pk')[0]} upload.html {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {%for i in up %} <img src ="{{i.image.url}}", alt=""> {%endfor%} {% endblock %} I know code in upload.html also have to change with views.py any suggestion will be appreciated also. I'm using neural network with image field and i'm sure it works correctly. I cant paste that code here. -
split a QuerySet in sublists/subsets
I am running a QuerySet that returns a list resembling this: {'name': 'A', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'A', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'A', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} ... {'name': 'B', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'B', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'B', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} ... {'name': 'C', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'C', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'C', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} Generated this way: Entries.objects .annotate(month=TruncMonth('date')) .values('name', 'month') .annotate(avg=Avg('value')) .order_by('name') So basically I have 12 entries per name, one per month. I was wondering if it was possible, via query, returning: [ 'A': { 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 316.684, }, 'B': { 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 316.684 }, ... ] or if the only way is to create another object … -
integration of a guacamole client into a django site
I would like to ask for help regarding the development of a guacamole client within a django site. Unfortunately, not being exactly an expert on the subject, I don't know if it is actually possible and looking on the internet I had no luck. With django it is possible to execute javascript code, so I believe there is a way. I have read the user manual on the Guacamole website, in particular the procedure explained in "Chapter 27. Writing your own Guacamole application" (http://guacamole.apache.org/doc/gug/writing-you-own-guacamole-app .html), however, I do not understand if it is a solution strictly achievable with the tools listed in the guide or if in some way it is possible to achieve the same thing in different environments. I have no obligations regarding the method or tools to use, so I am open to all solutions, even the most imaginative. Thanks in advance -
django.db.utils.OperationalError: no such column: users_student.user_id
Is there any error in the student's model? I am unable to add a student in the admin site. I got this error after adding this student model. No issue with the one-to-one field in the Student model. I do have id in the user model Models.py class User(AbstractUser): CATEGORY_CHOICES= [ ('STUDENT','STUDENT'), ('TEACHER' ,'TEACHER') ] name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) category = models.CharField(max_length=100, choices= CATEGORY_CHOICES,default='STUDENT') registrationDate=models.DateField("RegistrationDate", auto_now_add=True) profile_pic=models.ImageField(default='default.png',blank=True) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class Student(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key= True) study_class = models.IntegerField() bio = models.TextField(blank=True) Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/users/student/add/ Django Version: 3.1.7 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', '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 "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (no such column: users_student.user_id) was the direct cause of the following exception: File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, … -
Dynamic django forms from JSON field
My department model has a JSON field (see the example below). I am trying to create a Django form for an inventory item which will change depending on the user-chosen department. This means I want my form to change and render data from the given JSON field. Also, read rules, like, is required or not, is a checkbox or not, and render appropriately. I have no idea how to achieve this goal. Chances are, it's manageable, but I need a solid lift. Thanks in advance { "make": { "type": "ckeditor", "label": "Make", "rules": "required" }, "model": { "type": "ckeditor", "label": "Model" }, "title": { "type": "ckeditor", "label": "Title", "rules": "required" }, "colour": { "type": "ckeditor", "label": "Colour" }, "year_age": { "type": "ckeditor", "label": "Year/ Age" }, "body_type": { "type": "select2", "label": "Body Type", "options": [ { "key": "Automatic", "value": "automatic" }, { "key": "Manual", "value": "manual" }, { "key": "Semi-automatic", "value": "semi_automatic" } ] }, "condition": { "type": "select2", "label": "Condition", "options": [ { "key": "New", "value": "new" }, { "key": "As New", "value": "as_new" }, { "key": "Excellent", "value": "excellent" }, { "key": "Good", "value": "good" } ] }, "dimensions": { "type": "ckeditor", "label": "Dimensions" }, "vin_number": { "type": …