Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access existing MySQL data table using Django
I am new in Django. I have some data table in MySQL, how can I access and query data from existing table. Thanks. -
Writing a user registration form that doesn't extend UserCreationForm, having trouble with clean() function not executing at all
So as the title says, I have to make my own form to register a user as a learning task. The form works as intended however i want to validate the data that is entered(right now only that pwd1 and pwd2 match). I wrote a clean function but it does nothing and reports no errors. form.py: from django import forms import phonenumbers from phonenumber_field.formfields import PhoneNumberField class RegisterForm(forms.Form): email = forms.EmailField( label='email address', max_length=255) f_name = forms.CharField(max_length=30) country = forms.CharField(max_length=30) mobile = PhoneNumberField(region="IN") address = forms.CharField(max_length=300) pwd1 = forms.CharField(max_length=32, widget=forms.PasswordInput) pwd2 = forms.CharField(max_length=32, widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() pwd1 = cleaned_data.get("pwd1") pwd2 = cleaned_data.get("pwd2") if pwd1!= pwd2: raise forms.ValidationError("Passwords don't match", code='password_mismatch',) views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] f_name = form.cleaned_data['f_name'] address = form.cleaned_data['address'] country = form.cleaned_data['country'] mobile = form.cleaned_data['mobile'] password = form.cleaned_data['pwd1'] pwd2 = form.cleaned_data['pwd2'] user = User.objects.create( email=email, f_name=f_name, address= address, country= country, mobile= mobile, ) user.set_password(password) user.save() return redirect('/accounts/login/') else: return redirect('failure') else: form = RegisterForm return render(request, 'register.html', {'form':form}) return redirect('/register/') register.html <!DOCTYPE = 'html'> <html> {% load static %} <link rel="stylesheet" href="{% static 'accounts/file.css' %}"> <head> <div class="header"> <a href="/" class="logo">task1</a> <div class="header-right"> <a href="/">Home</a> … -
How to pass an object to celery in django request?
Here i initialize an object which can't be serialized in django view. I want to share this object among different requests and celery. Among requests i share the object with middleware. But I get problem when passing this object to celery. I have tried singleton. In middleware, I instantiate the singleton and assign value (a dict of {uuid:object} ) to member of it from request. But when i get the singleton in celery task, I got empty dict. How can i get the dict in celery? -
Django admin view design error/acting funny
Anyone faced this before? I have never. I installed Django 3.1 along with Python 3.9 and started facing this(see the image). Even when I scroll up, the top half stays there, its fixed, only the bottom half scrolls. I am using ckeditor for the body field in my app. Could that package be the reason? -
Dynamically removing a form from Django formset with Ajax
I would like to remove form dynamically when I press remove link. I have tried this solution but the problem with this solution is that it only removes form from html, it does not remove form from formset. So, I tried to alter from this solution and from this blog. Here is my progress: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} <h3>Ingredients</h3> {{ formset.management_form }} <div class="form-list"> {% for form in formset.forms %} <div class='table'> <a class="remove-form" href="#">remove</a> <table class='no_error'> {{ form.as_table }} </table> </div> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $('#id_' + type + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' … -
ImportError: cannot import name 'ProductDetails' from 'pages.views'
I have written test case for views for details page. Here is below code I have written, When I am runing pytest in terminal i t raising these error. My project structure is as below vikreya mysite .cache .idea .pytest_cache logs media mysute init.py manage.py settings.py urls.py wsgi.py pages .cache migrations static templates tests test_views.py init.py admin.py apps.py cron.py Forms.py functions.py models.py urls.py views.py ``` from django.test import RequestFactory from django.urls import reverse from django.contrib.auth.models import User from pages.models import vk_customer from mixer.backend.django import mixer import pytest from pages.views import ProductDetails @pytest.mark.django_db class TestViews: def test_product_detail_authenticated(self): mixer.blend('pages.vk_master_table') path = reverse('detail', kwargs={'pk': 1516}) request = RequestFactory().get(path) request.user = mixer.blend(vk_customer) response = ProductDetails(request, pk=1516) print(response) assert response.status_code == 200 ``` This the error i am getting..... ____________________________________________________________ ERROR collecting pages/tests/test_views.py ____________________________________________________________ ImportError while importing test module 'H:\vikreya\mysite\pages\tests\test_views.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: c:\users\user\appdata\local\programs\python\python38\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) pages\tests\test_views.py:8: in <module> from pages.views import ProductDetails E ImportError: cannot import name 'ProductDetails' from 'pages.views' (H:\vikreya\mysite\pages\views.py) Please help me out to solve this error, Thank you, ~Salima -
Django Expire Session on Tab Close
I am making a project in Django to practice authentication. I am using sessions and have enabled SESSION_EXPIRE_AT_BROWSER_CLOSE But still the session remains if I close the browser tab. It works when I quit the browser, but I wanted it expire after tab is closed. I am unable to find a solution. Thanks in advance -
Requests python [closed]
How could I paginate this results from API with the requests library I would like to know how to do it because I will implement this on django project. Thanks import requests path = 'https://api.themoviedb.org/3/movie/popular?' api = 'my-api' url = '{}api_key={}&language=en-US&page=1'.format(path, api) response = requests.get(url) obj = response.json() results = obj.get('results', []) if results: for pelicula in results: titulo = pelicula['title'] print(titulo) imagen = pelicula['poster_path'] print(imagen) votos= pelicula['vote_average'] print(votos) -
asgiref AsyncToSync explanation
# https://github.com/django/asgiref/blob/master/asgiref/sync.py class AsyncToSync: """ Utility class which turns an awaitable that only works on the thread with the event loop into a synchronous callable that works in a subthread. If the call stack contains an async loop, the code runs there. Otherwise, the code runs in a new loop in a new thread. ############### DON'T UNDERSTAND #################### Either way, this thread then pauses and waits to run any thread_sensitive code called from further down the call stack using SyncToAsync, before finally exiting once the async task returns. """ Can anyone help to explain the bolded text? thanks in advance! -
Django: Problem serializing and posting nested JSON data, "id already exists."
I'm facing a weird error while serializing a nested dictionary in Django. Here's what I've done I've created a view using DRF that processes and builds a nested dictionary after which this dictionary will be used by the serializer to post the data. views.py .... actual_data = generate_data() test_data = { 'album_name': 'The Grey Album', 'album_id': 1234, # I've defined this as my primary key in my models.py 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ] } # test_data == actual_data -> (True) # type(test_data) == type(actual_data) ->(True) serializer = AlbumSerializer(data=actual_data) # This statement gives error serializer = AlbumSerializer(data=test_data) # This statement works and return serialized data serializer.is_valid() serializer = AlbumSerializer(data=actual_data) # This statement gives error if I pass actual_data to the serializer, then the serializer failes and throws and error saying { "album_id": [ "album with this album id already exists." ] } serializer = AlbumSerializer(data=test_data) # This statement works and returns serialized data I checked my models.py, serializer.py; everything looks fine because the test_data works just fine. Any leads as to why this is happening would … -
pass non-english letters in urls django 3.1
I have a website showing some news. Some of the article's names are not in English language and they are Persian. If I click on the title of a news, it should show the details of that news.When I test it on local host, it works fine. But on the real host I get internal server (500) error. Does anyone know how should I pass Persian names in the url? I use Django version 3.1. This is the model of News app: class News(models.Model): name = models.CharField(max_length = 500, default="-") This is the url: path('details/<word>/', views.news_details, name="news_details"), It is the template: {% for i in news %} <a href="{% url 'news_details' word=i.name %}"><img class="img-full" style="width: 390px; height:300px;" src="{{i.picurl}}" alt=""></a> {% endfor %} and it is views.py: def news_details(request,word): news = News.objects.get(name = word) return render(request, 'front/news_details.html',{'news':news}) -
Django annotation case when
I have the following model: class Room(models.Model): # model fields class Table(models.Model): room = models.ForeignKey( Room, [...], related_name='tables' ) preparation_time = models.BooleanField(default=False) class Seat(models.Model): table = models.ForeignKey( Table, [...], related_name='seats' ) timestamp = models.DateTimeField(auto_now_add=True) is_vip = models.BooleanField(default=False) The code itself checks that per room there is a maximum of one table with preparation_time=None. Which is always the .last() one in the queryset. I would like to get the latest timestamp based on the following rules: 1.) If all tables of a room are prepared, return the latest preparation_time (the preparation_time of the latest table in the room) 2.) If there is a table without preparation_time, return the latest timestamp of a seat with a vip on it. I am getting the latest seat for case 2 like this: Room.objects.annotate( latest_activity=Max( 'tables__seats__timestamp', filter=models.Q(tables__seats__is_vip=True)) ) Then I tried to implement the first rule like this: .annotate( last_activity=Case( When(~Exists(Q(tables__preparation_time__isnull=True)), then=Max('tables__seats__timestamp', filter=Q(tables__seats__is_vip=True)) ), default=Table.objects.filter(room=OuterRef('id')).last().preparation_time, output_field=DateTimeField() ) For some reason this fails as I can not use the Q query in the exists. What would be the best way to achieve my goal? -
field id expected a number but got <function id of ---- > django
I was trying to add products detail view function by using the objects.get(pk = id) method. Since while I link it to the template I get above error with one plus point that I get I'd number on the end of url. Hope I get the solution for this soon -
Django - Not able to connect with Ldap Active Directory
I am a total newbie and this is my first Django web-app. This will be used in an intranet of the org I am working for. I need to connect my web-app with Active Directory for SSO authentication. For starters I followed the following tutorial. And since I don't have the access to the org's AD right now, I am using a free LDAP test server I found online. I followed the exact steps as mentioned in the tutorial, but I don't know what changes I should be expecting. From what I have seen, after a successful connection with LDAP server, the Users model on django-admin should be populated. But in my case I am seeing no changes in the Users model. Here is my settings.py file(refer the end of this code)(as this is the only file I have added the connection code in): import os import ldap from django_auth_ldap.config import LDAPSearch from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'kt_j(tvya@9r+ef8%+5$4y#h$jl%u-^!!pxeo0h5t=j)w23361' # SECURITY WARNING: don't run … -
Django: Remove duplicate data
I am using Django and React for my app. I am really new in Django rest frame work. I have made three models, they are order, customer and products. Order models have many to one relationship with customers and products. I fetched the data successfully to React frontend. But the problem is when I make new entries, for example: when user order new product. It give each time same user's name is frontend like this. I checked some documentation and stackover-flow questions but did not find the right answers. I know i need do something in my views.py's Order query but don't know how. This is my models class Customer(models.Model): name = models.CharField(max_length=200, null= True) email = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=20, null=True) date_created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name= models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY=( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ) name= models.CharField(max_length=200, null=True) price= models.FloatField(null=True) category=models.CharField(max_length=200,null=True, choices=CATEGORY) description= models.CharField(max_length=200,null=True, blank= True) date_created=models.DateTimeField(auto_now_add=True, null=True) tags= models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS =( ('Pending', 'Pending'), ('Out of delivery', 'Out of delivery'), ('Delivered', 'Delivered'), ) status= models.CharField(max_length=200, null=True,choices= STATUS) date_created=models.DateTimeField(auto_now_add=True, null=True) customer = models.ForeignKey(Customer, null= True, on_delete= models.SET_NULL, related_name='orders') product = models.ForeignKey(Product, null= True, on_delete= … -
filter to be applied even when pagination
class ActionView(View): def get(self, request): client = request.user.client page_number = request.GET.get('page', '1') status_filter = request.GET.get('status', '') jobs = Job.objects.filter( client=client, action_status__isnull=False).order_by('-due_date') if status_filter in ['open', 'dismissed', 'done']: jobs = jobs.filter(action_status=status_filter) paginator = Paginator(jobs, 3) try: page = paginator.page(page_number) except PageNotAnInteger: # If page is not an integer, deliver first page. page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. page = paginator.page(paginator.num_pages) return render(request, 'action_required.html', {'jobs': jobs, 'page': page, 'status_filter': status_filter}) template: action_required.html Job No. Date Title Customer Address Action required Action Action By {% if jobs|length %} {% for job in page %} <td> {{ job.job_number }}</td> <td>{{ job.due_date|date:'d/m/Y' }}</td> <td>{{ job.title }}</td> <td>{{ job.contact }}</td> <td>{{ job.contact_info }}</td> {% endfor %} {% endif %} {% bootstrap_pagination page %} Here when apply filter and do pagination my filter is getting loosed.Now i want if status filter is selected as 'done' and applying pagination all status are getting displayed but it should display only 'done' status even after applying pagination. -
How to get sql data at template in Django?
I want to get SQL data directly to a template in Django with below code {% if {{item.image_amount}} > 0 %} But error message appears Could not parse the remainder: '{{item.image_amount}}' from '{{item.image_amount}}' In order to get SQL data directly to template, how can I write code? models.py class TestEu(models.Model): id = models.TextField(blank=True, primary_key=True) national = models.TextField(blank=True, null=True) image_amount = models.IntegerField(blank=True, null=True) view.py class DbList(ListView): model = TestEu paginate_by = 100 ... ... sql += " where eng_discription ~* '\y" +n_word+"\y'" object_list = TestEu.objects.raw(sql) return object_list testeu_list.html {% for item in object_list %} {% if {{item.image_amount}} > 0 %} <td><img src="{% static 'rulings_img/' %}{{item.item_hs6}}/{{item.id}}-1.jpg" width="100" height="100"> {{item.image_amount}}</td> {% endif %} -
Django - How to annotate count() of distinct values
I have the following model: class Bank(model.Model): name: models.CharField .... Using the following sample data: ╔══════════════╗ ║ Row ID, Name ║ ╠══════════════╣ ║ 1, ABC ║ ║ 2, ABC ║ ║ 3, XYZ ║ ║ 4, MNO ║ ║ 5, ABC ║ ║ 6, DEF ║ ║ 7, DEF ║ ╚══════════════╝ I want to extract distinct bank names like so: [('ABC', 3), ('XYZ', 1), ('MNO', 1), ('DEF', 2)] I have tried using annotate and distict but the following error is being raised: NotImplementedError: annotate() + distinct(fields) is not implemented. I've also come accross the following question on SO: Question 1 Which has answers on using models.Count('name', distinct=True) but it's returning duplicate values. How can I handle this using Django ORM? -
How to dynamically select storage on the basis of model fields?
This is a duplicate question to this Django dynamic models.FileField Storage, but the question is not answered with correct solution yet. I also have the similar use case. I need to dynamically change the storage on the basis of the model field. I have tried using the callable for storage https://docs.djangoproject.com/en/3.1/topics/files/#using-a-callable. But I think this callable gets called before the model field values are initialized. Please suggest how can I do this. -
why when I click a different user returns me back to the current request user?
sorry, I had to take some screenshots to explains what is going on with me. now, I have much profile that has many different users and when I log in with one of it I'll assume the username is: medoabdin like you find on the screenshot now (medoabdin) and the name of it is (Origin) for me is a current user request. so, now I have also many different questions created by the different users, and when I want to enter any other profile let's suppose the user is (abdelhamedabdin) by current request user it returns me back to the current request (medoabdin) and not returns me back to abdelhamedabdin. however, when I check the link URL I find the link is correct and when I log in with (abdelhamedabdin) user I see the same thing occurs to me against (medoabdin) so, can anyone tell me what is going on guys? these are screenshots: current request (medoabdin), several questions, show the link url for different users, accounts/profile.html {% extends 'base.html' %} {% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %} {% block body %} <!-- User Profile Section --> {% if user.is_authenticated %} <div class="profile"> … -
how to create a link which points to the a potion of a chapter by using ebooklib python
I developing an application in DJango python to create EPub fies dynamically. I am using CKEditor and ebooklib. But I have a doubt with TOC, My intention is to create a link in TOC which points to the a potion of a chapter. We can create the same as section and link to chapter but when i create so section load as a separate page,see its sample code below Please see the sample code c2 = epub.EpubHtml(title='About this book', file_name='about.xhtml') c2.content='<h1>About this book</h1><p>Helou, this is my book! There are many books, but this one is mine.</p>' c2.set_language('hr') c2.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none') c2.add_item(default_css) # add chapters to the book book.add_item(c1) book.add_item(c2) # create table of contents # - add manual link # - add section # - add auto created links to chapters book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'), (epub.Section('Languages'), (c1, c2)) ) But when I execute I will get section in a separate page.My intention is to point to the section of the chapter, not as a separate page. (its like pointing to a subheading in chapter) and add section link in TOC (table of contents). Please help ? Thanks -
How to setup a AWS Cloudwatch scheduled Event to call a function in Django(AWS Lambda)
I am running a Serverless Django Rest API on AWS Lambda. I would like to call a specific function in Django regularly. How should I setup the scheduled call by using Cloudwatch event? I can select the Lambda function in the Cloudwatch trigger but I can't specific the function that I want to use? How to pass the parameters to the Lambda function? Is there any suggestions? Thanks~ -
Unblocking the web server?
I am using the below given function in python flask to download file stored in telegram cloud.Everything is working fine, the problem arises when size of file is large, it blocks whole web server until the download is complete. So please tell me how I can make it run parallel without blocking the server. def ping_me(chat_id,user,im_name): os.system('tgcloud -m download -n admin_helper -u "assignment_collector_bot" -p "portal/static/documents/users/"'+str(user.telegram_id)+'"/temp/" -c "'+im_name+'"') return Response('ok',status=200) -
aws media files not showing
I'm using aws s3 to store media files for a Django app, I install boto3 and django-storages. It uploads files to aws but the file does not render. I opened the link and see this message <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>15134F3A4F5CCB2B</RequestId> <HostId>ieKre9JIipHoSqal7QUt/jTPQY5hdrsfI95cyLQAtVIjM8r+OnjhDIGYH6cDpJQr1wXu71foxek=</HostId> </Error> My configs are: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None I really don't have much to go on from the error message, where do I use this AWS4-HMAC-SHA256 on aws? Any help will be appreciated. -
Styling non field errors with django crispy form?
I am using crispy forms to style my form.But I want to customize non field error.It's showing as list.I know how to modify with custom CSS.But is there any other way to do this. I want the non field error to be shown as in second image