Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to compare list of dict contains same values and generate new list contains similar items [closed]
list 1 [{"code":"1",},"code":"2",}] list 1 [{"id":"2"},{"id":1}] Expecting Result: [{"code":"1","id":"1"},{"code":"2","id";"2"}] -
Send randomly generated 6 digit otp via mail after each login in Django class based views
I'm using Django Class based views to develop a application. I have used Django-allauth for User login,Signup and Logout . Now i want to send a randomly generated 6 digit number as an otp via mail to user whenever user login. In function based view i know how to do it but dont know how to do that is class based view using django-allauth. please help me out , Thankyou -
How do I add SSL certificates to Docker container which have Django with UWSGI Postgres connected and reverse Proxy?
I am totally new to Docker but I set up everything for development and deployment that you can see in the below image. I have followed this tutorial for that. Here you can see the file structure and default.conf.tpl file I am also sharing Other file screenshots. This is docker-compose-deploy.yml file screenshot-1 This is docker-compose-deploy.yml file screenshot-2 I used docker-compose.yml for development and docker-compose-deploy.yml for deployment. Docker file which is located inside the proxy folder. Docker file which is located in the root folder. Last file which is run.sh Browsing result with https is this site can't be reached. I can share just 8 links. Browsing result with http I think I have shared all the necessary Screenshots. Please tell me what I do to set up SSL certificate? Anyone can also contact me to help. sumitdhakad2232@gmail.com Thank you in advance. -
django rest framework request vs self.request
in djnago rest framework what is difference between self.request and request in why we cant always use request and exactly in what situations we need to use self.request or request class MyView(APIView): def post(self, request, format=None): data = self.request.data login(request, user) i try to print them and both of them return same thing <rest_framework.request.Request: POST '/url/sub_url'> so why we user like data = self.request.data login(request, user) -
How can i retrieve the currencies in Django moneyed and diaplay them on a react frontend?
I have been trying to get the list of currencies from django moneyed by importing either the CURRENCIES or list_all_currencies function and sending that list to the frontend to populate a dropdown but I always get Serializer errors E.g. TypeError(f'Object of type {o.class.name} ' TypeError:Object of type Currency is not JSON serializable -
How to add a notification in admin panel in django
I want to build a notification panel in django admin panel. It should work like, when a customer book a order a notification/push- notification pop up in django-admin panel that shows a user had booked this item. I have no idea how to implement it, or which python package help me to doing this, can anyone suggest me how should I implement this. Thank you in advance. -
I need to know where i can find a error in code?
class UserAccountInfo(View): @staticmethod def details(user): result = { "user_id": user.id, "profile_id": user.userprofile.id, "name": user.userprofile.name, "phone": user.userprofile.phone return result -
Django Send Email Identify email reply
Im using Django send_email for sending an email to multiple user. There is a way to identify the reply of some Recipient? What I need is, If the recipient didn't reply with in allotted time the system send another email for follow-up. Follow-up email for those recipient didn't reply for the email. this is my send email code subject = 'System Automated Email' html_message = render_to_string('email.html',data) plain_message = item.number recipient_list = [item.email] from_email = 'System Automated Email <system@gmail.com>' mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False) -
How to add a DropDown list to edit a table in JS/Django-Ajax?
Hopefully I can get some help with this. I've basically got a page on my site with a table, and the table is populated from the database with one of my models. I'd like to have a dropdown list to allow the user to edit one of the columns of the table according to a fixed list of options. Right now, I was able to edit any of the fields by double-clicking them but didn't have luck adding the dropdown list over one of the columns. Any sort of example or guidance would be greatly appreciated :) Here's what I have so far: JS: $(document).ready(function() { $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); var table = $('#maintable').DataTable( { "ajax": {"type":"GET", "url" :"/TableEditor/request/", "data":function( d ) { d.placeholder = "asdf"; } }, "columns": [ { "className": 'show-details-control', "orderable": false, "data": null, "width": "12px", "defaultContent":'<button class="btn btn-sm btn-success" type="button"><span class="glyphicon glyphicon-chevron-down"></span></button>' }, { "className": 'edit-control', "orderable": false, "data": null, "width": "12px", "defaultContent": '<button type="button" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-edit"></span></button>' }, { "className": 'delete-control', "orderable": false, "data": null, "width": "12px", "defaultContent": '<button type="button" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span></button>' }, { "data": "investor", "class":'investor-ed'}, { "data": "amount", "type": "num-fmt" , "class":'amount-ed'}, { "data": "code" … -
Django Heroku: remaining connection slots are reserved for non-replication superuser connections
I recently deployed an app to Heroku using Postgres free tier as database. I am using Django 3.2 Everything was working fine until I started getting a mail with the following error: Internal Server Error: / OperationalError at / FATAL: remaining connection slots are reserved for non-replication superuser connections This happens anytime I open the site. It just started doing this. I thought waiting a while would solve the problem, but it didn't. What does this error mean? What causes the error? How can I solve it? My CONN_MAX_AGE is set to 500. -
get the select options from an update form django
I am working with django I need to do an update form, I already created the view and the form and everything but still this select options in my template I am stuck in this one. <select name="gender"> <option value="{{request.user.profile.gender}}">{{request.user.profile.gender}}</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> the user should see his gender and he still can see the other option so he can update his gender, you know what I mean. the list is really bad now because I have now 3 options and I should have only 2options Male and Female. -
Python Django url method regex for comma separated string in single quotes
Attempting to regex match a string like so: '1,2' Using Django rest framework url method to parse incoming string, I tried this: url(r'^path/to/api/end_point/(?P<player_ids>"\'1,2\'")/', PlayerResultsView.as_view(), name='get_players) The error I get: django.core.urlresolvers.NoReverseMatch: Reverse for 'get_players' with arguments '()' and keyword arguments '{'player_ids': '1,2'}' not found. 1 pattern(s) tried: ['path/to/api/end_point/(?P<player_ids>"\'1,2\'")/'] Overall Goal: pass comma separated string ('1,2,3,4') to REST endpoint, split on the comma and continue processing. -
Configure Django Rest Framework to populate user field with logged in user before serializer validation
I have an API endpoint that supports the POST method which works if I include the user in the request payload. I would like to eliminate this from the request payload and have DRF just use the logged in user. I am getting the following error when I omit the user from the request body: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "user": [ "This field is required." ] } This appears to be coming from when the framework calls serializer.is_valid(). How do I configure DRF to populate the user from request.user so that serializer validation doesn't fail? models.py class Task(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) domain = models.CharField(max_length=settings.MAX_CHAR_COUNT) serializers class TaskSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField(queryset=CustomUser.objects.all(), slug_field='email') class Meta: model = Task fields = ['id', 'created', 'domain', 'user'] views.py class TaskApiViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated,] serializer_class = TaskSerializer task_service = TaskService() """ GET /api/tasks """ def get_queryset(self): user = self.request.user if user.is_superuser: return Task.objects.all() return Task.objects.filter(user=self.request.user) """ POST /api/tasks """ def create(self, request): domain = request.data['domain'] can_create_task = self.task_service.can_create_task(user=request.user, domain_name=domain) if not can_create_task: raise PermissionDenied(code=None, detail=None) return super().create(request) -
Easy way to deal with models Django?
The problem I'm trying to create many functions in my project that let me easily create, delete and alter data using Model.objects.function(), but I have just learned that you cannot access 'manager' via instances: AttributeError: Manager isn't accessible via Address instances. I had a function to turn the string of a model into the actual model e.g. if model == 'author: return Author so that I could use them as the inputs to other functions but this doesn't seem to work. I can't seem to input classes into functions either, so I'm not sure how to resolve this. Any help would be greatly appreciated. Context I am trying to create these functions as commands in myproj/management/commands. Currently the code looks like this: myproj/management/commands/insert_random_data.py from django.core.management.base import BaseCommand, CommandError from ._private import * class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('model', type=str) def handle(self, *args, **options): model = options['model'] if model == "all": ad = format_data("address", generate_data("address")) ra = format_data("rating", generate_data("rating")) . . . myproj/management/commands/_private.py from myproj.models import * import string import random def string_to_model(string): string = string.lower() if string == "author": model = Author elif string == "seller": model = Seller elif string == "address": model = Address elif string == "rating": … -
How can I maintain Date Range Searched Result in Django views and Pagination
I have a date range search query with the total of the result which is displayed in django templates using loop in a table with pagination. And whenever the date range result exceeds one page and I click on the next page, the following page now display all the list of query that was initialize firstly in the views thereby loosing the whole Date Range Result. Here is my views code: def SearchIncomeRange(request): listIncome = Income.objects.all() searchForm = IncomeSearchForm(request.POST or None) if request.method == 'POST': listIncome = Income.objects.filter(date__range=[searchForm['start_date'].value(), searchForm['end_date'].value() ] ) else: searchForm = IncomeSearchForm() paginator = Paginator(listIncome, 5) page = request.GET.get('page') paged_listIncome = paginator.get_page(page) #Calculate total amount of Date Range Result total = listIncome.aggregate(total = Sum('amount')).get('total') or 0 context = { 'listIncome':paged_listIncome, 'searchForm':searchForm, 'total':total, } return render(request, 'cashier/search_income_range.html', context) If you take a look at the code very well, the first query fetches the whole income whereas the second query in the if statement does the date range search and any time I click on next page in the template it is the result of the first query for all income list that returns instead of displaying only the records in the following page. Thanks for your anticipated answers. -
How to fix ModuleNotFoundError: No module named 'rest_framework' in Ubuntu
I'm trying to deploy a django application on AWS EC2 for the first time. I'm using Ubuntu server, but it happens that the packages I installed are not recognized, the packeges have already been added to the INSTALLED_APPS. The error I'm getting is: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' The error references any package that comes first in the INSTALLED APPS. In this case restframework comes first. If it is corshearder that comes first in the installed apps the error will be ModuleNotFoundError: No module named 'corsheaders and so on. I know this behaviour occurs because the code is interpreted from top to bottom of settings.py file. I installed those packeges using sudo pip … -
Store messages after showing in the template
I would like to store the last 100 messages to get a chance for the user to check it again. How can I save it, after show? before show? Do I need to implement a db model? -
How to keep empty lines in a textarea in Django admin UI?
I have a field on an object, and I render it with a textarea in the Django (3.2) admin UI using this code, something like: class MyObject(models.Model): some_text = prompt = db.CharField(max_length=10000) # .. class MyObjectAdmin(admin.ModelAdmin): list_display = ('id', 'some_text') def formfield_for_dbfield(self, db_field, **kwargs): """Use Textarea for some_text. See also https://stackoverflow.com/a/431412.""" formfield = super().formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'some_text': formfield.widget = forms.Textarea(attrs={'rows': 10, 'cols': 80}) return formfield When I edit in the Django admin UI, if I add empty lines (hitting enter several times), when I save, they all are gone. So, while editing, empty lines: But after it's saved, no newlines: How do I get the Django admin UI to keep the empty lines (as newlines)? If I have non-empty lines, it keeps all the newlines. While editing: After editing (dumped out to a file), with newlines: -
proper way to order in window method (with two or more fields)
I make annotation with cumulative sum: MyObject.objects.annotate(cumsum=Windows(Sum(F'sum'),output_field=MoneyField(), orderby=F('timestamp').asc() but unfortunately timestamp isn't unique. So i want to order by timestamp (asc) AND id.asc In normal queries this would be order_by('timestamp','id'). -
APScheduler with Django - why it doesn't work this way?
Here is my Django app tree: . ├── admin.py ├── apps.py ├── forms.py ├── __init__.py ├── management │ └── ... ├── migrations │ ├── ... ├── models.py ├── scheduler │ ├── __pycache__ │ │ ├── jobs.cpython-39.pyc │ │ └── scheduler.cpython-39.pyc │ └── scheduler.py ├── static │ └── ... ├── tests.py ├── urls.py └── views.py When I have in scheduler.py file this: from apscheduler.schedulers.background import BackgroundScheduler from auctions.models import Listing, Bid scheduler = BackgroundScheduler() def close_listing(id): listing = Listing.objects.get(id=id) bids = Bid.objects.filter(listing=listing).all() listing.closed = True if bids: listing.winner = bids.last().user listing.save() and in views.py this: from .scheduler.scheduler import scheduler, close_listing @login_required(login_url='/login/') def create_listing(request): if request.method == "POST": form = ListingForm(request.POST) if form.is_valid(): new_listing = form.save() new_listing.owner = request.user new_listing.current_price = new_listing.starting_price new_listing.save() # this is important line scheduler.add_job( close_listing, 'date', run_date=datetime.now() + timedelta(seconds=5), args=[new_listing.id]) return HttpResponseRedirect(reverse("listing", kwargs={'id': new_listing.id})) else: return HttpResponse('invalid') else: form = ListingForm() return render(request, "auctions/create_listing.html", { 'form': form }) When I create listing and and the job is to be done (in five seconds) I get this error: Job "close_listing (trigger: date[2021-09-07 20:39:25 UTC], next run at: 2021-09-07 20:39:25 UTC)" raised an exception Traceback (most recent call last): File "/home/andrej/Dokumenty/Programming/CS50 Web/commerce/venv/lib/python3.9/site-packages/apscheduler/executors/base.py", line 125, in run_job retval = job.func(*job.args, … -
Operation not permitted error when uploading a file DJango
I have a API based on Django REST working properly over Azure Web Service but it fails when trying to upload a file into the container's mount volume. I´m doing the upload process by a POST request and in my local environment it's works with no trouble. The model I used to upload the file to the DB is this: from app.controllers.users.models import User class QueueJob(models.Model): class Tasks(models.TextChoices): COLLABORATORS_UPDATE = 'CB_UPDATE' WITHDRAWALS_UPDATE = 'WD_UPDATE' EXPATS_UPDATE = 'EP_UPDATE' class Statuses(models.TextChoices): PENDING = 'PENDING' PROCESSING = 'PROCESSING' DONE = 'DONE' FAILED = 'FAILED' user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=20, choices=Tasks.choices, blank=False, null=False) file = models.FileField(upload_to=r'reports/', null=False) extra_data = models.CharField(max_length=1024, blank=False, null=True) execution_comment = models.CharField(max_length=255, blank=False, null=True) status = models.CharField(max_length=20, choices=Statuses.choices, null=False, default=Statuses.PENDING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Queue Job' verbose_name_plural = 'Queue Jobs' ordering = ['created_at'] class QueueJobSerializer(ModelSerializer): class Meta: model = QueueJob exclude = ['id', ] The weird thing is that the file actualy loads up and I can access to it over the volume as you can see here but still failing when it runs the save() method when creating the DB record with the serializer returning the next error: [Errno 1] Operation not … -
What is the difference between permission_classes and authentication_classes in django rest framework generic API Views
I know what permissions and authentication means. Authentication identifies the user and permissions decide what action can be done by the user. I have implemented a token authentication in django rest framework. The problem is when i specify both permission_classes and authentication_classes in ListAPIView i cant log in to the account in browsable page. It only works when i delete authentication classes in the view. The following view doesn't raise any exception, but gives { "detail": "Authentication credentials were not provided." } response. Also not logging in. class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAdminUser,) authentication_classes = [TokenAuthentication] But after deleting the authentication_classes = [TokenAuthentication] the page works. PS: curl and httpie works without any problem. So what could be the issue here? What is the difference between those two classes? -
Procfile not declared Django Heroku
Procfile not getting delacared Not Declared File Location -
Get the real name of saved file (Model) after upload - Django
I'm trying to get the real name of the uploaded file in Django. It turns out that if a file name already exists inside the Model, the Django will create another name aleatory. For example, if 'abc.xls' is inside the Model database and I try to upload 'abc.xls' again, Django will create a file called 'abc_123456.xls'. That's not the problem! My question is: how can I get this name ('abc_123456.xls') inside my view.py? def index(request): if 'GET' == request.method: form = DocumentForm() return render(request, 'auditoria_app/index.html', {'form': form}) else: form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() # I'd like to get the correct file name here! mediaFolder = settings.MEDIA_ROOT fileName = f"{mediaFolder}/SAE/{form.cleaned_data['file'].get_alternative_name}" # .xlsm (Excel file) splitFileName = fileName.split('.') zipFileName = f"{splitFileName[0]}.zip" # .zip My model: from django.db import models from django.core.validators import FileExtensionValidator class Document(models.Model): file = models.FileField(upload_to='SAE/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.file) -
How to take limited amount of related (many to one ) objects. django
So I have these three models: class Database(models.Model): fields... class DatabaseFieldsToCheck(models.Model): data_base = models.ForeignKey(Database, on_delete=models.CASCADE, related_name="sql_requests_to_check") class DatabaseMonitoring(models.Model): sql_request = models.ForeignKey(DatabaseFieldsToCheck, on_delete=models.DO_NOTHING, related_name="sql_request_results") class Result(models.Model): result = models.ForeignKey(DatabaseMonitoring, on_delete=models.CASCADE, related_name="results") so my relation looks like this database ---many---> DatabaseFieldsToCheck ---many--> DatabaseMonitoring -->result So in my view i want to get for each database only last 10 results. how can i do it? should i try raw sql ? or mby write some data transfer objects ?