Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
What parameters to give an image tag to display an Django image from image.url in database
What keywords should I pass in to an img tag to display an image? my current line is like this: <img src="{{ skill.image.url }}"> models.py: from django.db import models # Create your models here. class Skill(models.Model): name = models.CharField(max_length=100) class Type(models.IntegerChoices): WEBDEV = 1 SOFTWARE = 2 DATABASE = 3 type = models.IntegerField(choices=Type.choices) image = models.ImageField(upload_to='img', blank=True) def __str__(self): return self.name -
React: TypeError: Cannot read property 'match' of undefined
I am using simple React-Django app. I have Django models orders, customer and products. Orders model have many to one relationship with customer and products. I successfully connect my frontend React with Django and able to show the Orders data in React. I want display single customers order and the data looks like this image. In React I made router home and customer Details like this in my app <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/customer/:id" component={PersonDetail} /> </Switch> </Router> After fetching the Order-list. I fetched customer's name and create one link and that link direct to Customer-detail page. From there I was trying fetch single user's product purchase detail but I am getting error: TypeError: Cannot read property 'match' of undefined and in my django backend I am getting this error : ValueError: Field 'id' expected a number but got 'undefined'. I don't what I am doing wrong This is my orderlist const [state, setstate] = useState([]) useEffect(() => { getData() }, []) const getData = async () => { const order = await fetch('http://127.0.0.1:8000/api/order-list/') const orderData = await order.json(); console.log(orderData); setstate(orderData) } return ( <> <div className="App"> { state.map((person: any, index: number) => { return … -
How to send notification to admin when data is stored
I (admin) want to create a way to be notified via email every time a user presses send with their question from the comment page. The site is not setup for a user to create a profile. I have been looking at django-signals but I can't find an example that fits my issue. -
Difficulty in implementing search feature for a django project
This is the path i've set to my urls.py file inside the encyclopedia directory: path("encyclopedia/search.html", views.search, name="search"), This is the view: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): querry = form.cleaned_data['querry'] data = util.search_entry(querry) if data is None: return HttpResponse("No matches found!") else: return render(request, "encyclopedia/search.html", { "result":data }) search.html extends layout.html and {{ result }} is simply passed inside the body block. Added the util function search entry as follows: def search_entry(querry): _, filenames = default_storage.listdir("entries") if querry in entries: return querry else: results = [] for entry in filenames: if re.search( querry, entry ): results.append(entry) if not results: return None else: return results And finally, the form template in layout.html: <form action="encyclopedia/search.html" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> {{ form }} </form> But whenever i enter anything, i get the same error " The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. " I am unable to figure this out... -
CSRF token in angular 2
I am coding a simple login,it is working with @csrf_exempt but when I remove it I get the forbidden error. I looked a lot but cant fix it, Please do explain and help me. Django code: @csrf_exempt # @api_view(['POST']) def login(request): if request.method == 'POST': print(request.COOKIES) sadmin_data = JSONParser().parse(request) print(sadmin_data) users = auth.authenticate(email = sadmin_data["email"],password = sadmin_data["password"]) if(users): auth_token = jwt.encode({'email':users.email}, settings.JWT_SECRET_KEY) serializer= LoginSerializer(users) data={ "user":serializer.data,"token":auth_token.decode('utf-8'),"type":users.usertype } return JsonResponse(data,status=status.HTTP_201_CREATED) else: content = {'message': 'Please Contact the developers'} return JsonResponse(content, status = status.HTTP_404_NOT_FOUND) Angular Code: <form (ngSubmit)="onSubmit()"> <div class="card-body"> <div class="example-container"> <mat-form-field appearance="standard"> <mat-label>Enter your email</mat-label> <input matInput placeholder="pat@example.com" [(ngModel)]="sadmin.email" name="email" required> <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error> </mat-form-field> </div> <div> <mat-form-field appearance="standard"> <mat-label>Enter your password</mat-label> <input matInput [type]="hide ? 'password' : 'text'" [(ngModel)]="sadmin.password" name="password" > <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide"> <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon> </button> </mat-form-field> </div> <button mat-raised-button class="login-btn" type="submit">Login</button> </div> </form> Also When I print the cookies I get {}. -
How to Get Last Inserted id in Django Slug?
I am trying to create a unique slug, on the basis of last inserted id in my Django Project, But I am unable to get last Inserted id in my Slug, Please elt me know Where I am mistaking. Here is my models.py file... class ProjectStatus(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, default= None, related_name="ProjectStatusCity", help_text=f"Type: Int, Values: Select City Name.") name = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") slug = models.SlugField(max_length=190, unique=True, default='', editable=False, help_text=f"Type: String, Default: None, Values: Enter Slug.") meta_title = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") def __str__(self): return self.name def get_absolute_url(self): kwargs = { 'pk': self.id, 'slug': self.slug } return reverse('article-pk-slug-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.name + "-" + "prsid" + "-" + "city" + "-" + "s" self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) I want the last inserted id after s in thsi line (value = self.name + "-" + "prsid" + "-" + "s"), And I have relation with city so I want city name also here, Please help me to solve this issue.