Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a "save and add another" button and show on Wagtail admin model page
Was wondering if it is possible to add a custom button within a Wagtail model page that will allow me to save (create) the current data fields and move on to another page. The "save and add another" button was already available in django and I want to have something like that on the Wagtail model page. Thanks. -
How to make analytics of likes from one time period to another
Analytics about how many like's was made. Example url/api/analitics/?date_from=2021-03-03 &date_to=2021-03-20. API should return analytics aggre gated by day. models.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likes', null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.PositiveIntegerField(default=0, null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') date = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True, null=True, blank=True) #date_from = django_filters.DateTimeFilter(field_name='date', lookup_expr='gte') #date_to = django_filters.DateTimeFilter(field_name='date', lookup_expr='lte') @property def day(self): return self.date.count() serializers.py class LikesSerializer(serializers.ModelSerializer): #days_since_joined = serializers.SerializerMethodField() date = serializers.DateTimeField() likes = serializers.IntegerField() class Meta: model = models.Like fields = ('date', 'likes')#, 'days_since_joined') views.py class LikesView(ModelViewSet): queryset = models.Like.objects.extra(select={'date': " date(posts_like.date)"}).annotate(likes=Count('pk')).order_by('-date') serializer_class = serializers.LikesSerializer conclusion [ { "date": "2022-01-05", "likes": 1 }, { "date": "2022-01-05", "likes": 1 }, { "date": "2022-01-05", "likes": 1 } ] But it is necessary that all 3 likes are summed up in 1 and so on from different users [ { "date": "2022-01-05", "likes": 3 }, ] -
Django-unittest-OneToOne relation between two app models
I have two applications in my project which are login and approval. When I give username for login that user should be available in approval Employee table. In my login user table i have employee field which has onetoone relation with Employee table. I have tried I dont get proper solutions. Here, when i write test code for login it will search that employee instance. I could not create that instance also. In this case what should i do?? How can i test my code??? Expecting guidance from anyone,... -
Count foreignkey objects in django
suppose class Product(models.Model): user = models.ForeignKey(User,...) ... class Sold(models.Model): post = models.ForeignKey(post,...) buyer = models.ForeignKey(User,...) Now how do i get no of items sold using User model Something like User.objects.all().annotate(nbuy=Count("?")) Putting "sold" at place of "?" gives number of items user have bought. What should i do to get no of items user have sold? -
Djangos data cannot be imported into the database, is my code wrong?
I am new to Django, and I'd like to ask some questions I used the model layer to create the model with fields in it,it can create user_id,movie_id field in the database. class Rating(models.Model): user_id = models.CharField(max_length=16) movie_id = models.CharField(max_length=16) rating = models.DecimalField(decimal_places=2, max_digits=4) rating_timestamp = models.DateTimeField() type = models.CharField(max_length=8, default='explicit') def __str__(self): return "user_id: {}, movie_id: {}, rating: {}, type: {}"\ .format(self.user_id, self.movie_id, self.rating, self.type) class Cluster(models.Model): cluster_id = models.IntegerField() user_id = models.IntegerField() def __str__(self): return "{} in {}".format(self.user_id, self.cluster_id) Execute this statement using Python xxx.py,I want to populate the database but it doesn't work import os import urllib.request import django import datetime import decimal from tqdm import tqdm os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() from analytics.models import Rating def create_rating(user_id, content_id, rating, timestamp): rating = Rating(user_id=user_id, movie_id=content_id, rating=decimal.Decimal(rating), rating_timestamp=datetime.datetime.fromtimestamp(float(timestamp))) rating.save() return rating def download_ratings(): URL = 'https://gitee.com/zhangyoushang/wokkk/blob/master/latest/ratings.dat' response = urllib.request.urlopen(URL) data = response.read() print('download finished') return data.decode('utf-8') def delete_db(): print('truncate db') Rating.objects.all().delete() print('finished truncate db') def populate(): delete_db() ratings = download_ratings() for rating in tqdm(ratings.split(sep="\n")): r = rating.split(sep="::") if len(r) == 4: create_rating(r[0], r[1], r[2], r[3]) if __name__ == '__main__': print("Starting MovieGeeks Population script..." ) populate() But I found that my database was empty and there was no data in it. … -
How to fix using raw function MAX in queryset API not getting maximum marks?
views.py class MaxMarks(generics.ListAPIView): queryset = Marks.objects.raw('select student_id, subject_id, sem_marks, id, internal_marks, MAX(total_marks) from collegedetails.college_marks ') serializer_class = MarksSerializers I'm trying to figure out max marks using raw funtion in views.py after mapping to URL pattern and start run server but it getting only one record but still there more records which haveing max marks, Can any one suggest me what to do? -
request.POST data not in forms' cleaned_data
When creating a new instance of my model I fail to transfer the data from request.POST into the forms clean method on is_valid(): class cView(TemplateView): template_name = "store/new_product.html" def post(self, request, *args, **kwargs): print(request.POST) # correctly prints <QueryDict: {'number': ['8'], 'name': ['myproduCT'], 'price': ['2']}> obj = Product.objects.create(number = request.POST["number"], data = {}) form = ProductForm(request.POST, product = obj) form.is_valid() # validates to True The form looks like: class ProductForm(forms.Form): class Meta: model = Product fields = ["id", "number", "data"] def __init__(self, *args, **kwargs): product = kwargs.pop("product") super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) for key in product.data.keys(): self.fields[key] = forms.Charfield(requiered = False) def clean(self): cleaned_data = super().clean() print(cleaned_data) # only prints {'number': 8} ... Why is the rest of the request.POST data not in cleaned_data? Is this happening because the forms __init__() method gets an empty product.data attribute? How would I avoid this, when the Product is just now created and not filled with (validated) data? Product looks like this: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() -
Django download the right file from model
I created a web app that allows users to extract geometrical and other data from a 3D model in ifc format. So the user uploads the 3D model, the app gives him some basic info about the model and lets the user decide which data he wants to download in which format (xlsx or csv) For the uploaded file I have an upload form from the model. And then when the user decides what he wants to download I retrieve the uploaded file using the objects.latest query. But that can lead to problems, right? If multiple users are uploading files at the same time it can lead to a mismatch. What would a better practice of solving this problem be? How do I associate the page visitor withe the file he uploaded? -
Should I use Django or Flask for a microservice? I want to convert or generate any website into apk through microservices in python
Sir, I want to convert any website in apk through microservices in python, could you suggest to me which platform I'll used? and any suggention about microservices, please advice me cos I'm beginner in microservices..! -
how to check username exit or not two different table in djnago rest framework
while register new user in Tempdriver table need to varify username already exist or not in tempdriver table and appuser table, if check tempdriver table username its working but if i check appuser table getting error, pls someone help me out. models.py- add models Tempdriver and Appuser class Tempdriver(BaseModel): name = models.CharField(max_length=255) username = models.CharField(max_length=20,unique=True,null=True, blank=True) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) password = models.CharField(max_length=100) class AppUser(BaseModel): username = models.CharField(max_length=50) seriliazers.py class TempDriverUserSerializer(serializers.ModelSerializer): class Meta: model=Tempdriver fields=('username','mobile') def validate(self,username): user=Tempdriver.objects.filter(username=username) user_exists = AppUser.objects.filter(username=username) if user.exists() and user_exists.exists(): raise serializers.ValidationError("UserName already exists") def validate_mobile(self, mobile): mobile=Tempdriver.objects.filter(mobile=mobile) if mobile.exists(): raise serializers.ValidationError("Mobile Number already exists") views.py class Tempuserapi(APIView): parser_classes=(MultiPartParser,FormParser) def post(self, request, format=None): serializer = TempDriverUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_200_OK) else: return Response(serializer.errors, status= HTTP_200_OK) trace report ERROR Internal Server Error: /api/tempusercheck/ Traceback (most recent call last): File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\10dec_everestfleet\everest_jarvis\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File … -
How to apply other bootstrap and html properties to Django form fields
{{ form.firstname|as_crispy_field}} I want to know how further I can add bootstrap classes to this Django form field and also I want to add a placeholder thank you -
Django CheckConstraints to check start_date greater than or equal today
from django.db.models.functions import Now, TruncDay class Foo(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() class Meta: constraints = [ name="start_date must be greater than or equal today", check=CheckConstraints(start_date__gte=TruncDay(Now())) ] like above code, I want to add CheckConstraint to check whether start_date is greater than or equal with today. but, after makemigration and migrate, error happened. functions or expression 'CURRENT_TIME' cannot be userd in check clause How can I check start_date with today? -
How to group data in Django serializer?
I have two models one for Collection and the other for Services and what I want is to return each collection with its services. Here is my code: class Collection(models.Model): name = models.CharField(max_length=50, verbose_name=_('Name')) enabled = models.BooleanField(default=True, verbose_name=_('Enabled')) def __str__(self): return self.name class Meta: verbose_name_plural = _('Collection') class MoreWorks(models.Model): collection = models.ForeignKey(Collection, on_delete=models.PROTECT) title = models.CharField(max_length=50, verbose_name=_( "Title"), blank=True, null=True) description = models.TextField( verbose_name=_('Description'), validators=[MaxLengthValidator(1000)], blank=True, null=True ) image = models.ImageField( verbose_name=_("Image"), upload_to='more_works/' ) enabled = models.BooleanField(default=True, verbose_name=_("Enabled")) class Meta: verbose_name_plural = _('More Works') I want to return each collection with its services using DRF. -
Stripe: 'payment_intent.succeeded' is also triggered when subscription gets renewed
I have two APIs for Stripe webhooks in my backend (Django). "Subscription" webhook: /api/subscriptions/webhook/ "Add Balance to Wallet" webhook: /api/wallet/webhook/ In the subscription webhook, I listen for invoice.paid and invoice.payment_failed events and in the wallet webhook I listen for payment_intent.succeeded event. The problem is whenever the subscription webhook gets called, the payment_intent.succeeded event is also triggered for the wallet webhook. I think that's because payment intents are also created for subscription as well. I need a way to differentiate these two (one-time payment [aka add balance to wallet] and subscription) so I don't end up with extra credit in user's wallet whenever their subscription get renewed. -
How do you return a complete url with get_success_url(self) in django?
How do you return a url using get_success_url(self) in django without using reverse for a generic view? Basically, I want to have something as below. def get_success_url(self): url = self.object.url # This is a charfield with "https://stackoverflow.com/questions/ask" return url I know that people often use reverse when returning a url, but I would like do it like above. Thank you, and please write any questions you have. By the way, I never tested the above code, but I don't know if it will work properly. -
Can we check whether a user is part of an Organizational Units instead of Groups in Django LDAP?
In my LDAP directory, Users are added to Organizational Units instead of groups. How can I check whether a user is a part of an Organizational Unit using Django LDAP ? My settings.py file: AUTH_LDAP_SERVER_URI = 'ldap://qwery' AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_BIND_DN = 'dndndn' AUTH_LDAP_BIND_PASSWORD = 'pwdpwd' AUTH_LDAP_USER_SEARCH = LDAPSearchUnion( LDAPSearch('ou=abbb,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ammmm,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=addddd,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), LDAPSearch('ou=ahhhhh,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"), ) AUTH_LDAP_CACHE_TIMEOUT = 0 AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "name": "cn", "username": "sAMAccountName", "department":"distinguishedName" } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=addddd,DC=xxx,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=*)") AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_USER_MODEL = 'login.Account' AUTH_LDAP_USER_FLAGS_BY_GROUP= { "is_it": "OU=IT,OU=ahhhh,DC=xxx,DC=net", } Thank you -
ResfFrameWork Invalid username/password error when no auth setting is set
I made rest-frame-work API server, I didn't set any auth setting. It works well on local, but on server, it shows below. HTTP 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } My server setting is like this below. application is on Nginx-unit and proxy is on Nginx When I access Nginx-unit directly, it doesn't show this error. However accessing Nginx, it shows the error. http://myserver.com:8888/api/balls Nginx url # it works http://myserver.com:8010/api/balls Nginx-unit url # it shows the error. Why does this happens or where should I fix?? My setting.py is here. from pathlib import Path from decouple import config import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().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 = 'o9nbo46qbraxo1qw$gauk!uznxhzy4pmt^9w2p1pu*h943(wpr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'defapp.apps.DefappConfig', 'django_extensions', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': … -
How to upload a json file in Django REST API
I am new in backend stuffs. I am trying to learn DJANGO rest api. I have to upload a json(from local) file to DJANGO REST API which contains all training prediction log. I tried to create app and did setting part, but I am kind of stuck here. It would be easier if I get some hints for my question. How can I make django model and django view which pulls json file from json file from trainng folder and visualize the prediction result? Thank you. my json file format: [{ "datetimeAt":"2021-12-24 21:00:00", "loss":0.2538179466, "rolling_mean":0.3990683079, "total":0.0 }, .............. ] -
how can we download all images as zip file in my model Django
how can we download all images as zip file in my model Django class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name -
Gunicorn cannot release cpu usage after response
I use Gunicorn to start my Django project, here is the command. command=gunicorn myproject.asgi:application --workers 4 --threads 3 --timeout 1200 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:778 However, I found my CPU load is around 100% one or two minutes after responding a GET request. As a compare, I changed to python manage.py to start my project, the same request reponsed, the CPU load is not higher than 10%. I have a total of 16 CPUs in my system. Anyone knows the reason? Thanks in advance. -
How to get a value of particular field inside loop Django
I want to print values of 'sm' inside loop alist = [ {'price': '700', 'sizes': {'sm': True, 'md': False, 'lg': True, 'xl': True} }, {'price': '900', 'sizes': {'sm': False, 'md': True, 'lg': True, 'xl': True} } ] for i in alist : print(i.get('sizes'['sm'])) -
How to make a query using multiple foreign key fields of Django models?
Hi all! New in Django, and confused, help is appreciated! I'm trying to create table, like: | Organization | Appeal Form | Amount of appeals in this form | | -------- | -------------- | -------------- | | Organization 1 | In written form | 5 | | Organization 2 | In oral form | 17 | Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: | organization_name | | -------- | | Organization 1 | | Organization 2 | Objects of AppealForm model: | form_name | | -------- | | In written form | | In oral form | Objects of Appeal model: | organization | appeal_form | applicant_name | | -------- | -------- | -------- | | Organization 1 | In written form | Mary Elizabeth Smith | | Organization 2 | In oral form | Ada María Guerrero | Just rendered Appeal model to index.html, but confused how to filter objects, count and place into the table... I have been trying to make a query, but no luck till now :( -
Upload File in Django
In this upload file, I want to save my uploaded files along with machine name and operation number. it is working but giving error in template. when I click save button it is not showing on the template. Please help to solve this. views.py: def index(request): if request.method == 'POST': form = MachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file1','file2','file3','file4','file5','file6','file7']) model_instance = form.save(commit=False) model_instance.save() obj=form.instance return render(request,'usermaster/upload_file.html',{'obj':obj}) else: form = MachineForm() machine = Machine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'machine':machine}) def handle_uploaded_file(f): with open('usermaster/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name file1 = models.FileField(upload_to='documents/',default="") file2 = models.FileField(upload_to='documents/',default="") file3 = models.FileField(upload_to='documents/',default="") file4 = models.FileField(upload_to='documents/',default="") file5 = models.FileField(upload_to='documents/',default="") file6 = models.FileField(upload_to='documents/',default="") file7 = models.FileField(upload_to='documents/',default="") forms.py: class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' admin.py: admin.site.register(Machine) upload_file.html: <html> <head> <title>Django File Upload</title> </head> <body> <p><h1>Django File Upload</h1></p> <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <br><br> <table border="1"> <tr> <th>Machine Name</th> <th>Operation Number</th> <th>Files</th> </tr> {% for file in machine %} <tr> <td>{{ file.machine_name }}</td> <td>{{ file.operation_no }}</td> <td> <a href="/media/{{file.upload_file}}">view file</a></td> </tr> {% endfor %} </table> </form> … -
How to have two arguments in a django custom filter
I am trying to manipulate two objects for a calculation, however I am getting the error:"Invalid filter" In the html frontend I have a nested loop with objects: units and person as following: {{units|myFilter:person}} where units has several objects and person only has one. my filter is defined by: def myFilter(units,person): n = 0 for i in units: if i.name == person.name: n = n + 1 return n But is it not working, any ideas or suggestions please? -
How do I change the default schema to custom_schema in postgres from djnago setting file?
Please help me to change the default schema from public to custom_schema.