Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking for many-to-many relation OR a property
How can I check whether a many-to-many relationship exists or another property is fulfilled? When I try the query, it returns some rows twice! Given a model from django.db import models class Plug(models.Model): name = models.CharField(primary_key=True, max_length=99) class Widget(models.Model): name = models.CharField(primary_key=True, max_length=99) shiny = models.BooleanField() compatible = models.ManyToManyField(Plug) I have the following items in my database: from django.db.models import Q schuko = Plug.objects.create(name='F') uk = Plug.objects.create(name='G') Widget.objects.create(name='microwave', shiny=True).compatible.set([uk]) Widget.objects.create(name='oven', shiny=False).compatible.set([uk]) Widget.objects.create(name='pc', shiny=True).compatible.set([uk, schuko]) Now I want all names of widgets that are shiny and/or compatible with Schuko: shiny_or_schuko = sorted( Widget.objects.filter(Q(shiny=True) | Q(compatible=schuko)) .values_list('name', flat=True)) But to my surprise, this does not return ['microwave', 'pc']. Instead, 'pc' is listed twice, i.e. shiny_or_schuko is ['microwave', 'pc', 'pc']. Is this a Django bug? If not, how can I set up the query that I get 'pc' just once? -
How to run your dev instance over HTTPS and expose your local app on internet
Please have a look on my medium post-: https://medium.com/@rimehrotra1997/hack-for-running-your-dev-instance-over-https-and-expose-your-local-app-on-internet-cff52766caf -
Django historical records not showing up in admin
I am setting historical record for some of my models. It works, the table is created and behaves as expected, however, I can not get it to appear in my admin tables. models.py class Test(models.Model): ... history = HistoricalRecords() In admin.py I have a TestAdmin(admin.ModelAdmin) such as: class TestAdmin(admin.ModelAdmin): list_display = ('test', 'id') list_filter = ['test'] admin.site.register(Test, TestAdmin) #1 # admin.site.register(Test, SimpleHistoryAdmin) #2 When I use the #1 line I have everything working well except that I don't have the historical table. When I use the #2 line I don't get it neither and my format doesn't work anymore. When I set both I get an error django.contrib.admin.sites.AlreadyRegistered: The model Test is already registered with 'test.TestAdmin' (that makes sens). What am I missing to get the historical record table appears in my admin? Thanks for your time. -
How do I get the value of an dictionary for Django?
I am using aggregate to average out some values in a table. It returns as: How would I display 3.5 in the template? I am passing rating as a dictionary to the template. -
API call that handle data from 2 apps
This is my project layout . What I am trying to do is executing an API call that use data from account and address. Where should I put the views.py file that handle the request? -
Django altering multiple objects with the same attribute on a form
I am trying to alter the attribute for several objects using a single input. The model setup is as follows: class Entry(models.Model): Person = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) group = models.CharField(max_length=20, blank=True, null=True, choices=Constants().group()) station = models.CharField(max_length=20, blank=True, null=True, choices=Constants().station()) The idea is that each person can enter an event and is assigned a group. Each group has multiple people. Then each group is assigned a station. I attempted to create another relational model so each instance of the Entry class did not contain the group-station assignment however I could not get that to work. The goal is to display on a table with the following columns: Group Station Entrants then for each row of the table the group # is displayed followed by the station as a drop down menu of numbers followed by the list of all the entrants in the model that have the same group #. Then when the form that the table is in is saved, the station is assigned to all the individual entry objets. -
Fitlter concatted fields by list in Django ORM
I need to filter concat of two string values which is in a list: from django.db.models.functions import Concat brands_to_search = ['Mercedes Benz', 'Opel Corsa'] result = models.VehicleModels.objects.filter( Concat('brand.manufacturer_description', ' ', 'model_description') # in brands_to_search ) -
Using AJAX to update data in Django templates
I have a simple messaging system built. I want to update the inbox div whenever there is a new message. html: <div id="inbox"> <h6>Inbox</h6> {% for message in inbox %} <ul> <li title="{{ message.sender.username }}">{{ message.sender.first_name }}: {{ message.msg_content }} <button onclick="myFunction()">Reply</button> </li> <small>-{{ message.timestamp }}</small> <hr> </ul> {% endfor %} </div> Views: def user_messages(request): time_now = datetime.datetime.now() user = request.user if request.method == "POST": sender = request.user receiver_name = request.POST.get('msg_receiver') receiver = User.objects.get(username=receiver_name) msg_content = request.POST.get('msg_content') Messages.objects.create(sender=sender, receiver=receiver, msg_content=msg_content) inbox = Messages.objects.filter(receiver=user).order_by('-timestamp') outbox = Messages.objects.filter(sender=user).order_by('-timestamp') context = {'inbox': inbox, 'outbox': outbox, 'time_now': time_now} return render(request, 'accounts/messages.html', context) Whenever there is a new message in inbox, i.e inbox length is greater I want the div (id=inbox) to update. I added a script in the html file: $('.inbox').click(function () { $.ajax( { type: "GET", url: "{% url 'messages' %}", data: { }, }) }); How do I check changes in the objects model? -
Django - display multiple views in one template
I am currently working on a Django project, in which I want to build a kind of dashboard, which may have actually two bootstrap columns (in the future maybe 3-4). In each column, content from a database is to be displayed. Currently, this means that I want to show two tables. One which shows all entries for a model and a table which shows the last history entries (django-simple-history). The tables are rendered using django-table2. First of all I tried to solve the problem with the MultiTableMixin. Unfortunately without success. My current idea is to logically split the content into two views and then add a view for each column. I tried to have the views displayed inside iframes. Also, this not working as good as thought. What are the options for my problem. Or am I thinking too complicated and getting lost? -
Add field to form. Django
I have a form (username, password1, password2) from django.views.generic.edit import FormView from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterFormView(FormView): form_class = UserCreationForm success_url = "/login/" template_name = "register.html" def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) How to add email field and use it for login instead of username -
How to sum OneToMany related records Django
I have two models class Salary(models.Model): date = models.DateField(_('date')) user_id = models.IntegerField(_('user_id')) earned = models.IntegerField(_('earned')) prepayment = models.IntegerField(_('prepayment')) ... created_at = models.DateTimeField(_('created at'), auto_now_add=True) class WebsitePayment(models.Model): website_id = models.IntegerField(_('website_id')) amount = models.IntegerField(_('amount')) salary = models.ForeignKey(Salary, related_name="payments", on_delete=models.CASCADE, null=False, blank=False) What I need is data contains grouped by date or by user Salary values with sum for each field from Salary. I did it this way acc = Salary.objects.filter(date__range=[start_at, end_at]) acc = acc.values('date').annotate( earned=Sum('earned'), prepayment=Sum('prepayment'), ) The problem is that I need not only Salary sums. I need to take all related WebsitePayment from Salary records I filtered, group them by website_id and sum amounts -
ModuleNotFoundError: No module named 'storages.backends.s3boto'
So, I have installed django storages and boto + boto3. They are in my requirements.txt and I made sure to install it while in my virtual environment. requirements is in my root obviously. Why am I still getting this error? requirements.txt beautifulsoup4==4.8.2 boto==2.49.0 boto3==1.14.16 botocore==1.17.16 dj-database-url==0.5.0 Django==2.2.3 django-bootstrap4==1.1.1 django-storages==1.9.1 djangorestframework==3.10.2 docutils==0.15.2 gunicorn==20.0.4 jmespath==0.10.0 Markdown==3.1.1 pbr==5.4.5 Pillow==7.0.0 psycopg2-binary==2.8.5 pygame==1.9.6 python-dateutil==2.8.1 pytz==2019.1 s3transfer==0.3.3 six==1.14.0 soupsieve==2.0 sqlparse==0.3.0 stevedore==1.32.0 urllib3==1.25.9 virtualenv==16.6.1 virtualenv-clone==0.5.4 virtualenvwrapper==4.8.4 whitenoise==5.1.0 settings.py import six import os from boto.s3.connection import OrdinaryCallingFormat from storages.backends.s3boto import S3BotoStorage -
Restricting tenants from base URL
I have a set of URLs I wouldn't want to be accessed by tenants. For example, a sign-up page for creating new tenants. I only want it to be accessible from the base URL. How do I go about it? -
How do I check if a Django user exists in a many-to-many field?
I have a Device model that has a many-to-many relationship to the built-in User object of Django. I'd like to override get_queryset() so that it only returns Device objects associated with the logged-in user. models.py: class Device(models.Model): maintainers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="devices", ) admin.py: class DeviceAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(maintainers=request.user) However, this code still shows all Device objects even if it is not associated with the logged-in user. I've also tried maintainers__contains=request.user but the problem persists. What am I doing wrong? How do I correctly filter the QuerySet? -
Django forms validation : cleaned_data within the "is_valid()" call [ fairly new to Django & Python]
It said in the Django docs that cleaning methods are run when the is_valid() is called. Which means, the cleaned_data is available only if this validation is over. My doubt is, what if I want to use the cleaned_data of this form [say, i need to know if that particular field is checked or not] within this is_valid() call ? i.e, As part of this validation in the call .is_valid(), I also need to validate that, if the check box in the form is checked, then validate a particular column of the uploaded csv file as well. How would i achieve this within the is_valid() function? One of the reason I wish to do this way is, I guess I can then raise the ValidationError, as per the doucment. Below is an overview of the part of the project where my validation happens. Please note, it's a properly working project, although I have trimmed down much of the codes (like skipping import statements, class definitions etc) here to make it as simple as possible to represent my question. File: create_report_view.py from project.project_core.forms import BrandModelForm class CreateReportView(LoginRequiredMixin, View): def post(self, request): brand_form = BrandModelForm(request.POST, request.FILES) if brand_form.is_valid(): # Validation call file_name_errors, … -
build a simple rest api that fetch the data from local postgres sql data base and serialize the data in django
Given a bank branch IFSC code, get branch details Given a bank name and city, gets details of all branches of the bank in the city DATA SET : https://github.com/snarayanank2/indian_banks PLEASE FOLLOW THE ABOVE LINK FOR THE DESCRIPTION THE DATA IS STORED IN THE LOCAL DB , READ DATA FROM THERE AND SERIALIZE THE DATA follow the link to see the bank branch details follow the link to see the bank details *API end point * 127.0.0.1:8000/api/branch/?name=STATE BANK OF INDIA&ifsc=ABHY0065001 OUTPUT { 'ifsc':'ifsc_value', 'branch':'branch', 'satte':'state_name', 'district':'district_name' } { 'ifsc':'ifsc_value1', 'branch':'branch1', 'satte':'state_name1', 'district':'district_name1' } ..... -
How to nest for loops in django and shift index in inner loop?
I have a list of fruit and I'm trying to get user input for how they feel each fruit compares to the others. Example: given a fruit_list of apples, oranges, bananas, and kiwis, I want to ask the user a question for each comparison without redundancy. (i.e. Ask: How do apples compare to oranges? and Don't ask: How do oranges compare to apples?) In non-django, the general idea would be an outer for loop & an inner loop like this for i in range (0, n): for j in range(i+1, n): but I'm not sure how to do this in a django form. I know an outer loop could look like {% for fruit in fruit_list %} but I'm not sure how to capture the inner loop. I am very new so any explanations you have are much appreciated. -
How do I go about setting a path for a file with the same parent folder (Django)?
I have a urls.py file where I'm creating paths, and I'm not sure how to go about it when the file I'm trying to set a path to is not in the same folder. urls.py is within the webserver folder, while the file I want to write the path for is in the library folder. They're both within the same parent folder, which is why I'm sure there's a way to do this. Any advice would be greatly appreciated. -
Moved ngrok executable to /usr/local/bin but when I run './ngrok http 8000' it returns 'zsh: no such file or directory: ./ngrok'
Not familiar with ngrok, I am reading a book on Django and am trying to set it up. Another question on here (ngrok command not found) said to put the executable in usr/local/bin. I put it here but when I run ./ngrok http 8000 it returns zsh: no such file or directory: ./ngrok Somethings I can add, I am using a virtual environment and echo $PATH returns the following: /Users/justin/Desktop/djangoByExample/sm/env/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin Not sure if I provided enough, please let me know if anything is missing and thanks for any help. -
How to display images from a Django CharField?
I'm building an ecommerce site and there is a selection of images to use as photos for each item. The problem I'm having is displaying the selected photo in the html. The photos arn't uploaded but rather are stored in the static files folder Here's my model class Item(models.Model): PHOTO_CHOICES = [ ('Fishing Rod', "fishing_rod.png"), ('Fishing Net', 'fishing_net.png'), ('Tackle Box', 'tackle_box.png'), ('Lure', 'lure.png'), ('Line', 'line.png'), ('Hook', 'hook.png'), ] name = models.CharField(max_length=25) price = models.DecimalField(max_digits=9, decimal_places=2) description = models.CharField(max_length=140) photo = models.CharField(max_length=25, choices=PHOTO_CHOICES, default='Fishing Rod') And here's the html displaying it {% for item in items %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="{% url 'item-detail' item.id %}"><img class="card-img-top" src="{% static 'Photos/{{ item.photo }}' %}" alt="" id="photo"></a> <div class="card-body"> <h4 class="card-title"> <a href="{% url 'item-detail' item.id %}">{{ item.name }}</a> </h4> <h5>${{ item.price }}</h5> <p class="card-text">{{ item.description }}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> {% endfor %} -
django form.as_p no longer rendering for seemingly no reason
Its one of those. It was working a second ago, with no code changes. my form in django being rendered by {{ form.as_p }} was working and now without any code changes it is not. Here is my html: <!doctype html> <html lang=en> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <meta charset=utf-8> <title>Christopher Jakob</title> </head> <body> <h4>Shipping Choices</h4> <form action="{{ request.path }}" method="get"> {{ form.as_p }} <button class="btn btn-primary" type="submit">Show options</button> </form> <hr> <table class="table"> {% for choice in shipping_choices %} {# TODO: show choices here #} <tr> <th>Code</th> <th>Name</th> <th>Price</th> <th>Estimated Arrival Date</th> </tr> <tr> <td>{{choice.code}}</td> <td>{{choice.name}}</td> <td>{{choice.shippingprice}}</td> <td>{{choice.shippingdate}}</td> </tr> {% endfor %} </table> </body> </html> here is my view: from django.views.generic import TemplateView from countries.models import * from shipping.helpers.calculate_shipping_helper import calculate_shipping_options from .forms import ShippingTestForm class ShippingTestView(TemplateView): template_name = 'index.html' def get_context_data(self, *args, **kwargs): context = super(ShippingTestView, self).get_context_data(*args, **kwargs) form = ShippingTestForm( data=self.request.GET or None ) if form.is_valid(): subdivision = form.cleaned_data['subdivision'] subtotal = form.cleaned_data['subtotal'] choices = calculate_shipping_options(subdivision, subtotal) shipping_choices = choices context.update({ 'form': form, 'shipping_choices': shipping_choices }) return context here is the form: from django import forms from countries.models import Country, Region, Subdivision class ShippingTestForm(forms.Form): region = forms.ModelChoiceField(queryset=Region.objects.all(), required=True) country = forms.ModelChoiceField(queryset=Country.objects.all(), required=True) subdivision = forms.ModelChoiceField(queryset=Subdivision.objects.all(), required=True) subtotal = … -
Celery RabbitMQ queues overload
I am currently using RabbitMQ as messaging broker to pass the jobs to celery in my django app. Although there are no running celery tasks, the CPU is clocking more than 149% for rabbitmq PID's last when I checked using htop linux command. Following are the screenshots for htop and rabbitmq queues. There are 2387 queues in the rabbitmq admin page as shown in the below image, is this the reason? do i have to clean up these queues regularly and make sure there will 0 count of All queues? are these memory leaks? Please help me understand and how to proceed. -
Convert datetime to UTC to store in DateTimeField Django
I have an accounts page which lets you put in a DateTime as follows: <input type="date" class="form-control" placeholder="Date" name="date" autocomplete="off" required> <input type="time" class="form-control" placeholder="Time" name="time" autocomplete="off" required> When the form is submitted, I want to convert them from PST (which is what they were entered in) to UTC (what my backend is in). How can I do this? Thanks! -
Django iterate queryset just n number of times in templates
My issue is quite simple. I am using Django taggit. I want to iterate this only 2 times. Means to display only 4 tags in templates. {% for tag in data.tags.all %} {{tag}} {% endfor %} I have tried this, but it is not making any sense: {% for tag in data.tags.all|ljust:"2" %} {{tag}} {% endfor %} Can anyone suggest how can I achieve it? -
Postgres removed id sequence in django table? How to restore it?
I have a django model while the django application is running on a postgres database. I had been getting the error psycopg2.IntegrityError: null value in column "id" violates not-null constraint While debugging, I came across a few articles that asked me to check the latest sequence which is present in the model. Thus, considering my table name to be table_name, I did the following: from django.db import connection cur = connection.cursor() cur.execute("SELECT setval(pg_get_serial_sequence('\"table_name\"','id'), coalesce(max(\"id\"),1), max(\"id\") IS NOT NULL) FROM \"table_name\";") cur.fetchall() The above command gave me the result [(None,)]. I tried the same thing with a different empty table, and got the output [(1,)] If I have understood correctly, this issue is because the sequence from which this has to be created is trying to append sequence values to null when getting the ids of new instances. As a solution, I tried doing : cur.execute("SELECT setval(pg_get_serial_sequence('\"table_name\"','id'), 1, true) FROM \"table_name\";") and also cur.execute("SELECT setval(pg_get_serial_sequence('\"table_name\"','id'), 1, true);") But in both of the above cases, I got the same result as [(None,)]. Would be really helpful, if someone could suggest how to solve this issue. And also, if possible that in which conditions does someone usually face this issue?