Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get daily number of call API
I have django rest framwork support android, ios, web with some version different api and different version mobile app. Now i hope know how many time each api call in 1 day, 1 month....for optimize and remove unused api. My question is: how to know each api call how many time in 1 day? Have any library support it or any way do it. Thank you! -
Django query implementation of Wilson Score algorithm
I'm trying to determine the best way to implement the Wilson Score algorithm in a Django project. The project is a mashup of typical forum features and reddit's upvotes/downvotes/trending page. Each forum has threads, and users can upvote/downvote a thread. Should I score and sort my threads in a database query, and if so, how would I do that using Django's DB models? My current solution is to fetch the forum's threads, and then sort in python. wilson_score.py from datetime import datetime from math import log epoch = datetime(1970, 1, 1) def epoch_seconds(date): td = date.replace(tzinfo=None) - epoch return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000) def score(ups, downs): return ups - downs def hot(ups, downs, date): s = score(ups, downs) order = log(max(abs(s), 1), 10) sign = 1 if s > 0 else -1 if s < 0 else 0 seconds = epoch_seconds(date) - 1134028003 return round(sign * order + seconds / 45000, 7) models.py from . import wilson_score class ForumThread(models.Model): category = models.ForeignKey(ForumCategory, on_delete=models.CASCADE) up_votes = models.IntegerField(default=0) down_votes = models.IntegerField(default=0) @staticmethod def get_trending_threads(category): return sorted(ForumThread.objects.filter(category=category), key=lambda x: wilson_score.hot(x.up_votes, x.down_votes, x.date_created), reverse=True) views.py threads = ForumThread.get_trending_threads(category)[offset:offset + 20] -
Convert this html template into Django
I am currently learning django, and at the moment I want to convert this page https://colorlib.com/etc/lf/Login_v6/index.html into django. I have tried heaps of times, still can't make everything right. Let me show you my work structure below. My problem is about using css and js under static/vendor fold. Seems the way I used got a bit problem, I have also attached my code for invoking the css and js under vendor. Thanks for any help. MyFirstDjangoWeb --project --setting.py --urls.py --wsgi.py --init.py --project_app --template --myHtml.html --migration --0001_initial.py --init.py --__init_.py --admin.py --apps.py --models.py --test.py --urls.py --views.py --static --css --images --js --vendor manage.py '''html ''' -
Adding functionality to a button in HTML
I am creating a web-page for an online supermarket using Python and Django framework and for each of those products is an "Add to Cart" option.I want to make the code such that when the button is clicked it increases the quantity of that product by 1. This is the code for the the whole product Card :- <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> -
NoReverseMatch pattern not found in django2
NoReverseMatch found for a url i have tried and {% url '/feedback/form/' %} i am using a feedback app. #feedback\urls.py from django.urls import path, include from .views import request_feedback urlpatterns = [ path('form/', request_feedback, name = 'get_feedback' ), ] #feedback\views.py def request_feedback(request): if request.method == 'POST': feedback_form = FeedBackForm(request.POST) if feedback_form.is_valid(): feedback_form.save() return redirect('') else: feedback_form = FeedBackForm() return render(request, 'feedback/feedbackform.html', {'feedback_form':feedback_form}) #webapp\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('feedback/', include("feedback.urls")), path('user/',include("user.urls")), ] i am getting this error NoReverseMatch at /feedback/form/ Reverse for '' not found. '' is not a valid view function or pattern name i am using python 3.7 and django 2 i do mitigate this problem -
Can't fix "zipimport.ZipImportError: can't decompress data; zlib not available" when I type in "python3.6 get-pip.py"
I was trying to install Django. Turns out that course's teacher said that we will be working with Python 3.6 I install Python 3.6. Now it's my default, it somewhat replaced the last version I had; which is Python 3.5. Everything ok until that. But when I want to install Django doing "pip3 install django", it tells me that the module is already satisfied and therefore installed. I run "python3" command into my terminal. It runs Python 3.6. I try to import Django, and boom... "No module named 'django'". Then I realized pip3 was actually installing my modules into Python 3.5 and not 3.6. So what I do is to install pip in Python 3.6. I download get-pip.py and proceed to execute it with Python 3.6 typing in "python3.6 get-pip.py". Here is when the damn "zipimport.ZipImportError: can't decompress data; zlib not available" goes in. I've tried a ton of things and no one of them fixed the %^$! problem. I'm really tired. What I have already tried: python3.6 -m pip install django, which output is "/usr/local/bin/python3.6: No module named pip" apt install zlib, which output is "E: Unable to locate package zlib" apt install zlib1g-dev, which says that it's already … -
Passing model fields into functions as parameters to create other fields django
I following up with my question Creating new objects under specific parameters . I was trying to find out how to write functions into my django models to create default values on fields. I know how to do that, but now would like to take it a step further by adding parameters to the functions and using previous fields as the parameters. So far I have tried the following and each have given their own error messages when I try and migrate them. class NewTest(models.Model): score = models.IntegerField(default=0) def num(score): # Want the score parameter to be the score field new_num = score return new_num last_score = models.IntegerField(default=num(score)) Error: int() argument must be a string, a bytes-like object or a number, not 'IntegerField' class NewTest(models.Model): score = models.IntegerField(default=0) def num(self): new_num = self.score return new_num last_score = models.IntegerField(default=num(self)) NameError: name 'self' is not defined class NewTest(models.Model): score = models.IntegerField(default=0) def num(): new_num = self.score return new_num last_score = models.IntegerField(default=num) NameError: name 'self' is not defined Does anybody know how to do this, or know where there is documentation on this? -
[Django]The logged in person wants to download the file
I would like to provide the files in the django media url to the logged in users. However, in general media, if you know url, you can access without permission. What is the best way to solve it? The code below is 'views.py', which allows users to download files to the bulletin board. Please let me know if there is another solution. I also want to maintain good performance because it is a large file. views.py @login_required def index(request): files = os.listdir(settings.MEDIA_ROOT) # file full path # print(os.path.getsize(os.path.join(settings.MEDIA_ROOT, files[0]))) filelist = [(i, os.path.getsize(os.path.join(settings.MEDIA_ROOT ,i)), '/media/'+i) for i in files] print(filelist) return render(request, 'download/index.html',{'filelist' : filelist}) -
AttributeError at / 'tuple' object has no attribute 'get'
Estou iniciando meus estudos em Django e Python, no momento estou tentando criar um blog, mas quando tento executar a aplicação ocorre o erro: AttributeError at / 'tuple' object has no attribute 'get' AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /home/pedro/Documents/projects/django_pratice/myvenv/lib/python3.6/site-packages/django/middleware/clickjacking.py in process_response, line 26 Python Executable: /home/pedro/Documents/projects/django_pratice/myvenv/bin/python Python Version: 3.6.8 Python Path: ['/home/pedro/Documents/projects/django_pratice', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/pedro/Documents/projects/django_pratice/myvenv/lib/python3.6/site-packages'] Server time: Thu, 11 Jul 2019 21:35:35 -0300 Espero ver a pagina html -
How to set up multiple schema in django with oracle as a database?
My workplace is planning to use Python/Django as a backend framework and React on the front, on top of oracle db from ASP classic. Since our oracle db structured from the beginning of the company, we decided to keep it as is. From my understanding, schemas in oracle are typically accessed by username/password, thus need to have user/password for each schema to have an access and our oracle db has about 30ish schemas, containing numerous tables inside for each. Django, on the other hand, seems it only supports one schema at a time, based on app that is installed in settings.py, which sounds like the databases configuration need to have different user/password set up in settings.py for each app installed. So far, I've tried class Meta and DATABASES in settings.py; // class Meta class SomeModel(models.Model): ///some fields and data types... class Meta(): managed=False db_table=u'"schema\".\"table"' // DATABASES DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'multi_schema_db', 'USER': 'django_user', 'PASSWORD': 'secret', }, 'data': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'multi_schema_db', 'USER': 'data_user', 'PASSWORD': 'secret', }, } My questions is, is there any workaround to have an access into multiple schema where django has only one app installed? P.S. Correct me on any misunderstandings that … -
How to use Django + DJ Stripe to add user to group after they pay for a subscription
I have a Django web app using a custom user model based on AbstractUser. Users sign up and they can upload audio files which then fill an audio player. I want to have two tiers--free and paid. Free users can only upload 5 audio files. Paid users can upload unlimited. I will offer 3 subscription plans, Monthly, Semi-Annually (6 months), and Yearly. Currently there are two Groups in my django project. "Free User" and "Gold Member". In the upload view, there is a check that if a user has uploaded 5 files and they are a member of the "Free User" group, they are redirected to a page that says they must be a member. This page would have the three options I will mention below. . . I have created my plans in Stripe, and installed dj-stripe. I was thinking to have the process go like this: User signs up and they are automatically a member of "Free User" group. I have code to do this. After successful sign up, they would be redirected to a subscriptions page where they are presented the option to pick monthly, semi-annual, or yearly subscription. There would three columns with features/pricing and a … -
django unique object (not unique field)?
how to make a unique object (not unique per field) e.g: name : honda category : car success name : honda category : bike success name : honda category : bike failed coz all field have same value to another object if i use unique at the field, the second case will be failed, coz honda (name) already created my code : class Category(models.Model): name = models.CharField(max_length=127,unique=True) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=127,unique=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.name -
Customize error messages using django-rest-auth
I am using django-rest-auth for login and registration. If I try logging in using a wrong password, I get Request failed with status code 400. and the same message is shown if I signup trying to use a username that already exists. How would I get some more exact error messages to show in these different scenarios? -
Sub inline_formset django
I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store) A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User") The second is "Product" that has as foreignKey the "ProductPlace" model The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model I created formsets associated to these three models in the "forms.py" file. #forms.py from django import forms from .models import * from django.forms.models import inlineformset_factory, modelformset_factory from django.contrib.auth import get_user_model User = get_user_model() class ProductPlaceForm(forms.ModelForm): name = forms.CharField(label='Nom', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Nom du point de vente' })) num_road = forms.IntegerField(label='Numero', widget=forms.NumberInput( attrs={'class': 'form-control', 'placeholder': 'Numero de la rue'})) name_road = forms.CharField(label='Nom de la rue', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Nom de la Rue' })) postal_code = forms.IntegerField(label='Code Postal', widget=forms.NumberInput( attrs={'class': 'form-control', 'placeholder': 'Code Postal'})) city = forms.CharField(label='Ville', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Ville' })) country = forms.CharField(label='Pays', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Pays' })) class Meta: model = ProductPlace fields=['name', 'num_road', 'name_road', 'postal_code', 'city', 'country'] ProductPlaceFormSet … -
JPEG image with filename patern DSC*.JPG are not rendered
I am using django 2.2 to upload imaged files. Files are uploaded correctly in MEDIA_ROOT. Most images are rendered as expected. Except for the ones with filename like "DSC*.jpg" which were not rendered even though the image tag as seen in inspect correctly pointing to actual files in the media directory. Anyone experienced this problem before? I would really appreciatred it if anyone could shed some light into this problem. There were no error messages. The images just weren't rendered. I am at a lost and ready to implement a clean_filename method for these DSC* files, or change the filename before saving. But only if it is absolutely necessary. pax -
MySQL display data with Django
I'm a beginner at Django and Python. I'm trying to query a MySQL database. Entering the data from the admin section works fine. Queering the database doesn't give an error, but it doesn't work. I tried querying from shell, and it worked perfectly. However, querying from the code section doesn't. The models.py looks like this: class Courses(models.Model): course_title = models.CharField(max_length=200) course_image = models.ImageField(upload_to='course_images/') course_duration = models.TimeField() def __str__(self): return self.course_title The views.py looks like this; from django.shortcuts import render from .models import Courses def homepage(request): cos = Courses.objects.all() context={ 'courses': cos } return render(request, "main/home.html", context) The home.html looks like this: {% for cos in courses %} {{cos}} {% endfor %} I tried using Courses.objects.all and also Courses.objects.all() but it still won't work. I really need some assistance. -
Get all users with userGroups
I am trying to write a method which can return all the users from django defaultDb. The following would result in giving me all the users: User.objects.all() Now, I want to add usergroups to each of the user as part of my response. I know I can parse every user and get usergroup like: user.groups.values_list('name',flat=True) But I feel this is very expensive operation as it involves n read from Db for n users. Is there any other better way to do this? -
Django (DRF): filter inside of page when using pagination
I need to perform some not so trivial filtering on the database objects, including splitting the QuerySet into two parts, manipulating one of them, and then returning them as a list. This is the starting point: def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if not page: # I need to filter on the objects returned by `page` The thing is, because I don't want to iterate over all instances, I don't want to use queryset (which is the list of objects before we apply the pagination). On the other hand, page, while it does contain only the instances that we do want to iterate on, isn't a queryset but a list, so we can't use filter() on it. Here's what I came up with for now, but this feels hacky, and __in is known not to scale to well: if page is not None: post_ids_in_page = [x.id for x in page] # now we have the relevant post ids q = Post.objects.filter(id__in=post_ids_in_page) # get the queryset # now filter other_posts = q.filter(scopes__isnull=True) member_posts = q.filter(scopes__isnull=False) # we later perform some additional manipulation on one of these querysets # on a per-object/per-user basis, hence the need to … -
Django annotate multiple objects based on multiple fields on a M2M relationship
I want to efficiently annotate Model A objects based on some fields on model B which has a M2M to A. I tried this but it's not correct: a_qs = A.objects.filter(id__in=ids) ordered_qs = a_qs.order_by('-b__created_timestamp') oldest_qs = Subquery(ordered_qs.values('b__name')[:1]) result = list(a_qs.annotate(name=oldest_qs)) This annotates every A with the same oldest name of B across all B's related to A, but I want the oldest B among those Bs associated to each A. -
Django and a custom subscription payment gateway - how to get started?
I want to create a simple subscription payment system for my personal project (single price + trial). I decided to use Django. Unfortunately, everything I find is about Stripe and I don't know how to get started. I live in a country that Stripe doesn't support so I need to use something else. How can I implement a custom gateway? Payment gateway I decided to use is a little different than Stripe. Every time I want to get the payment I need to run a script that is sending a request to the gateway's API (it is basing on ID from previous payments). I choose the period (so I think I need to run scheduled tasks) and the payment amount. I think that I can write a single task, ran every day, which could look for database records with expired licenses. Also, I want to offer a trial period for my clients and I need to have a possibility to check the license status by API, but I think I can somehow figure it out with a basic plan of the subscription system -
How to import multiple images to a Django app
I have a simple model with a title and an asset field. asset is a FileField. This is not something user facing, it's only available through the Admin and I can import the images there, one by one. But there's hundreds of them and I'm looking for a way to do bulk import/upload with the title being the filename without the extension. Is something like this available in Django? -
On hover include more detail about object PVIZ
I am using the genentech/pviz github to display proteins and peptides. I have gotten a nice graphic and have used a hover feature in the css portion to change the color of the rectangle when hovered over. However, I want to display additionally information about the peptide and or protein when hovering over it as well. g.feature.psms.normal:hover rect.feature { fill: black; } seqEntry.addFeatures(fts.map(function(ft) { return { //we could also use te categoryType property, for height purpose, but not grouping purpose category : 'psms', type : ft[2], //This would be "normal" in most cases start : ft[0], end : ft[1], text : '', } })); I am not sure how to display information because I cannot find any good documentation. How would I be able to display text when hovering over the peptide rectangles? -
Flutter Chat Application, Check for changes in the API (Django-Rest-Framework)
I have built a chatt App using Django And Flutter, so I do a get request to get the information, also a post request from any user in the chat room to send new information(chats). My Question is how do I detect changes in the api? Is it possible to update let's say every 10 seconds, also have a pull to refresh, and just call a new get request on those? Also just Make a get request right after the post request so you can se your own messages? -
Django filter does not exclude results of negative look ahead regex
I'm working on a Django app where the database is currently being searched using regular expressions. The returned results seem to be correct, except for when I search with negative look ahead (I would like to be able to exclude some results through filtering with a regex). For example, the database has a column with many entries of 'None', and I would like to exclude those results when the database is searched. I tried the regex ^(?!None).*$ in an online regex tester, and it passes my tests ('None' strings are not matched, every other string is). However, when the results are returned with Django, the 'None' rows are not excluded. The backend for the DB is SQLite, which according to here should allow anything re allows, but I have not had success. Here is the filter() call I am using for the regular expression: previousFilters.filter(models.Q(myColumn__regex = r'('+input_expression+')')) Does Django allow the exclusion of results through a negative look ahead in a regular expression? -
How to optimize lazy loading of related object, if we already have its instance?
I like how Django ORM lazy loads related objects in the queryset, but I guess it's quite unpredictable as it is. The queryset API doesn't keep the related objects when they are used to make a queryset, thereby fetching them again when accessed later. Suppose I have a ModelA instance (say instance_a) which is a foreign key (say for_a) of some N instances of ModelB. Now I want to perform query on ModelB which has the given ModelA instance as the foreign key. Django ORM provides two ways: Using .filter() on ModelB: b_qs = ModelB.objects.filter(for_a=instance_a) for instance_b in b_qs: instance_b.for_a # <-- fetches the same row for ModelA again Results in 1 + N queries here. Using reverse relations on ModelA instance: b_qs = instance_a.for_a_set.all() for instance_b in b_qs: instance_b.for_a # <-- this uses the instance_a from memory Results in 1 query only here. While the second way can be used to achieve the result, it's not part of the standard API and not useable for every scenario. For example, if I have instances of 2 foreign keys of ModelB (say, ModelA and ModelC) and I want to get related objects to both of them. Something like the following works: …