Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix the problem 'No module named myModule'
when start the service,as the command 'gunicorn -w 4 -b 0.0.0.0:8000 ApiWangYinParse:server', it shows the error log. plz look the code structure, what command I can start the python service. [2020-06-09 17:24:20 +0800] [28785] [INFO] Starting gunicorn 20.0.4 [2020-06-09 17:24:20 +0800] [28785] [INFO] Listening at: http://0.0.0.0:8000 (28785) [2020-06-09 17:24:20 +0800] [28785] [INFO] Using worker: sync [2020-06-09 17:24:20 +0800] [28788] [INFO] Booting worker with pid: 28788 [2020-06-09 17:24:20 +0800] [28789] [INFO] Booting worker with pid: 28789 [2020-06-09 17:24:20 +0800] [28788] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/signdraft2/ShenDuTool/API/ApiWangYinParse.py", … -
Writing in /tmp in Azure app service linux with django
We have an Azure linux app service running django. When we upload a file to it that is greater than 2.5MB it written by default in the /tmp. When this happens we notice increase in response time from the app service before it eventually crash. Is there a restriction on writing in the /tmp for a linux web app ? If so where can we write our temporary file ? How could I make sure that the /tmp is in fact the issue ? We don't want to increase FILE_UPLOAD_MAX_MEMORY_SIZE value of django. We looked at this documentation but it doesn't talk of any issue on the tmp for linux. -
How to identify number of connections to a Postgres Database (heroku)?
I am trying to identify the number of connections to a postgres database. This is in context of the connection limit on heroku-postgres for dev and hobby plans, which is limited to 20. I have a python django application using the database. I want to understand what constitute a connection. Will each instance of an user using the application count as one connection ? Or The connection from the application to the database is counted as one. To figure this out I tried the following. Opened multiple instances of the application from different clients (3 separate machines). Connected to the database using an online Adminer tool(https://adminer.cs50.net/) Connected to the database using pgAdmin installed in my local system. Created and ran dataclips (query reports) on the database from heroku. Ran the following query from adminer and pgadmin to observe the number of records: select * from pg_stat_activity where datname ='db_name'; Initial it seemed there was a new record for each for the instance of the application I opened and 1 record for the adminer instance. After some time the query from adminer was showing 6 records (2 connections for adminer, 2 for the pgadmin and 2 for the web-app). Unfortunately I … -
Django: Custom Model Manager does not pass updated id values
my data in policy model is as follows : | id |policy_start_date| amount | is_renewed | original_policy |renewed_counter| | 10 | 01-06-2019 | 134 | 0 | NULL | 0 | | 12 | 05-06-2019 | 454 | 0 | NULL | 0 | | 35 | 04-06-2020 | 121 | 1 | 12 | 1 | I'm trying to use a custom model in models.py to change the id if is_renewed flag is set to True. With the help of print statements, I can see that my desired output is being printed when the custom model manager gets fired but the required output is not passed down to the final queryset i'm getting. my model manager and model class CustomManager(models.Manager): def get_queryset(self): temp = super(CustomManager, self).get_queryset().all() for a in temp: if a.is_renewal: a.id = str("R" + str(a.original_policy)) print(a.id) return temp class Policy(models.Model): objects = CustomManager() policy_start_date = models.DateField() amount = models.IntegerField() is_renewed = models.BooleanField(default = False) original_policy = models.IntegerField(Null = False) renewed_counter = models.IntegerField(default = 0) in shell, if i do test = Policy.objects.all() i get print output R12 but the same is not available in test. -
Django Modelling for staggered database config
I have a query; I would be using a explicitly defined primary key field in my user table, what I want is to attach a number like '111'+ i as the primary key where i is auto incremented... but if the server stops by some chance, I would have to reload i, so I would have to save the value of i in database after each run also i would be reading i each time from database Concerns: What if before i is saved server crashes, so the value of I would be corrupted If I has been read once, can I be able to not read it at each run My use case is : I have one US server which is seperated by UK server, but I want to have a global server too where US and UK users are both present Purpose: I am building an app where you can share and view ideas, at first you can only share n view ideas in your country, after reaching a certain level, you can share and view ideas of alll the countries... So I thought, I would have 1 db associated with each country. Say DB-UK for ideas … -
REST API listener vs polling
I have a mobile application which is calling my Django REST API for data, one of the calls looks at open orders. At the moment I refresh the list every x seconds on the mobile app. This isn't a great user experience and I'd like it to be more instant/less intrusive than a full reload. Is it possible to create something like a listener or open connection to a REST API endpoint? Would this be resource intensive if there are a lot of mobile clients? Many thanks! -
Django: Authentication system errors and bugs. (value too long for type character varying(80))
I'm trying to code the login/register system on Django, but I'm getting errors. So my main task is to make a custom auth system that the user can easily login/logout/register. I don't want to use the in-built User model, I want to use my main from flask. So the thing is that I'm trying to move from flask to Django and set-up the models and stuff. So I have this models.py file which concludes: import datetime import uuid from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from werkzeug.security import generate_password_hash, check_password_hash class UserManager(BaseUserManager): def create_user(self, username, password, primary_telephone_number, secondary_telephone_number, primary_email_address, first_name, last_name, registration_ip): if not username or not password or not primary_telephone_number or not secondary_telephone_number or not primary_email_address or not first_name or not last_name or not registration_ip: raise ValueError('Not enough values') user_obj = self.model(username=username, password=generate_password_hash(password), primary_telephone_number=primary_telephone_number, secondary_telephone_number=secondary_telephone_number, primary_email_address=primary_email_address, first_name=first_name, last_name=last_name, registration_ip=last_name) user_obj.save(using=self._db) return user_obj class Users(AbstractBaseUser): """Model for Winteka.IOT Users.""" public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) username = models.CharField(max_length=50, unique=True, blank=False, null=False) password = models.CharField(max_length=80, blank=False, null=False) # Third-party social (Emails, Phone numbers, Verifications) primary_telephone_number = models.CharField(max_length=15, unique=False, null=True, blank=False) secondary_telephone_number = models.CharField(max_length=15, unique=False, null=True, blank=True) primary_telephone_number_verified = models.BooleanField(default=False, null=False, blank=False) #Default secondary_telephone_number_verified = models.BooleanField(default=False, null=False, blank=False) … -
What web framework to use to implement deep learning-based image processing website?
I am currently working on developing an interactive image segmentation tool using deep learning. I developed a desktop application based on PyQt5 for the tool and tensorflow 2 for image processing. Now, I am intending to build a website so that the user can do the same task on web. However, I do not have experience on web programming and I want to build a quick prototype of my tool on web. Can you recommend web framework to do the job? I used PyQt5 for my desktop application, because I found Python relatively easy to study and PyQt5 is based on Python. So I searched for Python-based web framework and thought of using either Django or Flask. I do not mind using other frameworks based on different languages. This is the outline of the process. User upload image of size around 10k x 10k pixels. Zoom-in and zoom-out to examine the image Brush function so that user can annotate seed points Deep learning model to run on background to process segmentation -
Django: I am new to Django framework I want to submit three related model Forms with one submit button and render detail view
I want to admit(register) a new student with father and mother information in one form. I am able to save the father and mother form but not the student form it returns "NONE" but when i print the request.POST value I can see all the information. And I want to render a student detail with the father and mother information also but only the student information is displayed with out the father and mother info Model.p from django.db import models from django.db.models import PROTECT from django.urls import reverse # Create your models here. # Student Model class Father(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) father_pic = models.CharField(max_length=255) ASC = models.IntegerField() zoba = models.CharField(max_length=255) sub_zoba = models.CharField(max_length=255) religion = models.CharField(max_length=255) phone_no = models.IntegerField() parent_occupation = models.CharField(max_length=255) is_guardian = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = self.id def __str__(self): return self.first_name def get_absolute_url(self): return reverse('student-detail', args=[str(self.id)]) class Mother(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) mother_pic = models.CharField(max_length=255) ASC = models.IntegerField(default='00000') zoba = models.CharField(max_length=255) sub_zoba = models.CharField(max_length=255) religion = models.CharField(max_length=255) phone_no = models.IntegerField() occupation = models.CharField(max_length=255) is_guardian = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = self.id def __str__(self): return self.first_name def get_absolute_url(self): return … -
How to get list of functions or methods where data is coming through requests in Django?
I want to get the list of methods or functions where request.POST or similar is implemented. I don't want to look through the IDE search and then manually list down all methods/functions name. I'm using Python 3.8, Django 2.2.10 and pycharm professional. Thanks -
Django App Implementing Auth0 won't render on iOS devices after logging in
I have a nice Django app that implements Auth0. It works on all browsers on pcs and on browsers on Android. When testing on iOS devices however, after the user logs in through Auth0, the device asks to download a file and then downloads it and does nothing. If I try to redirect to my english page, it downloads a file called "en", if I try to redirect to my french version of the page, it downloads a file called "fr". Not sure why - it is at the end of the url myurl.something.org/myForm/en for English for example. At first I thought the issue had to do with Apple not allowing Same-Site cookies, so I added the CSRF_COOKIE_SAMESITE = None setting. But I see now that after logging in, in the address bar there is the url that I want the user to be redirected to. When I tried using the Web Inspector for Safari on Iphone, I see that there are no same-site cookies, so it seems that this is not the problem. I see the document "en" in the list of resources on the Web Inspector when on the login page. It is type "document" and shows that … -
How to create Peer Groups in Django?
How can I create a Peer Group in Django? I have tried the following: class Person(models.Model): name = models.CharField(max_length=100, unique=True) peers = models.ManyToManyField("self", blank=True, null=True) Now there are for example 3 Persons (A, B, C). A is connected to B. B is connected to C. A is not connected to C. The problem: A should also be connected to C, because B and C are connected. How can i do this? -
How to use Python selenium in cPanel?
Can somebody tell me "How can I use Python selenium in my cPanel or backend?" I want this for my web app developed in Django: Adsense Eligibility Checker Tool -
How is it possible for QuerySet.count() to return non-zero values but for list(QuerySet.all()) to yield an empty list?
I am running a script using django-extensions and here is the paused execution of it. How is this possible? I am running Django 2.2.1 on Windows with a local postgres instance. The database itself was restored using psql from a dump created with pg_dump | gzip. There is another database, which was restored using pgAdmin from a custom format file, on which the code works fine, so I guess I messed up the restoration, but how? -
Django - How to append to a Django queryset (values)
how do I append a dictionary into a Django queryset? I did .values on the queryset already, but it still classifies as a queryset and when I try to use .append on it, this error came up AttributeError: 'QuerySet' object has no attribute 'append' Here is my code: (start and end are variables passed in to denote the start month and end month of the selected range) qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end)) qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client"))) qs = qs.values('date', 'client_count', 'lead_count') All I want to do is to add the missing dates to the queryset, like for example if my queryset has date: April 2020 and June 2020, but is missing May 2020 due to CustomerInformation not having any instances with created_date in range of May 2020, hence I want to be able to insert a dictionary with date: May 2020 and lead_count and client_count 0 so that my data visualisation would work properly Thanks all, all help is appreciated! -
How to show error message when login fails in angular 8
i want to show error when user entered his login details if it is match with database then it login if not valid details then want to show credential are not a valid like... this is my login component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormGroup, FormBuilder, Validators} from '@angular/forms'; import { emailValidator } from '../../theme/utils/app-validators'; import { AppSettings } from '../../app.settings'; import { Settings } from '../../app.settings.model'; import { LoginService } from '../../services/login.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [LoginService] }) export class LoginComponent { public form:FormGroup; public settings: Settings; constructor(public appSettings:AppSettings, public fb: FormBuilder, public router:Router, private userService:LoginService){ this.settings = this.appSettings.settings; this.form = this.fb.group({ 'username': [null, Validators.compose([Validators.required, Validators.minLength(3)])], 'password': [null, Validators.compose([Validators.required, Validators.minLength(6)])] }); } public onSubmit(values:Object):void { this.userService.loginUser(this.form.value).subscribe( response => { console.log(response) this.router.navigate(['/client/clientdetails']) alert('User' + this.form.value.username + 'Logged') }, error => console.log('error', console.error) ); } ngAfterViewInit(){ this.settings.loadingSpinner = false; } } this is my login component.html page <mat-sidenav-container> <div fxLayout="row" fxLayoutAlign="center center" class="h-100" style="background-color: rgb(195, 38, 46)"> <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" fxFlex="80" fxFlex.gt-sm="30" fxFlex.sm="60"> <mat-card class="p-0 mat-elevation-z24 box"> <div fxLayout="column" fxLayoutAlign="center center" class="bg-primary box-header" style="background-color: #231F20;"> <!-- (click)="onSubmit(form.value);" --> <!-- <button mat-fab color="accent" class="mat-elevation-z12"> <mat-icon>exit_to_app</mat-icon> </button> --> <img src="assets/img/Ops_logo.png" style="float:right; … -
How to use django-constance?
I use django-constance and have several questions about it's functions. 1) How can I set upload path for mediafiles? I want to upload files in folder MEDIA_ROOT/constance_upload 2) How can I mark field as not required? image-, file-, html- fields are required as default. CONSTANCE_ADDITIONAL_FIELDS = { 'image_field': ['django.forms.ImageField', {}], 'file_field': ['django.forms.FileField', {}], 'email_field': ['django.forms.EmailField', {}], 'html_field': ['ckeditor.fields.RichTextFormField'] } 3) How can I collapse fieldset when I am using OrderedDict? CONSTANCE_CONFIG_FIELDSETS = OrderedDict([ ('Seo', ('ROBOTS',)), ('Page 404', ('ERROR_TITLE', 'ERROR_DESCRIPTION', 'ERROR_PREVIEW')), ]) Thank you for your attention and help! -
Django parent form with child inlineformset won't exclude fields when rendering
I have a Parent model and Child model with one-to-many relation. In my /manage/ URL for parent, I am displaying the form for the Parent model and then formset for the Child model. When I render the form and formset, I am getting all the fields although I have mentioned the necessary fields in my fields variable. forms.py class ParentForm(ModelForm): title = forms.CharField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Parent title' ) slug = forms.SlugField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Slug' ) description = forms.CharField( widget=forms.Textarea( attrs={ 'class': 'textarea', }), label='Description' ) class Meta: model = Parent fields = ['title', 'slug', 'description'] class ChildForm(ModelForm): title = forms.CharField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Child title' ) slug = forms.SlugField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Slug' ) order = forms.IntegerField( widget=forms.TextInput( attrs={ 'class': "input", 'placeholder' :"0" }), label='Order' ) class Meta: model = Child fields = ['title', 'slug', 'order'] class ParentManageForm(ParentForm): def __init__(self, *args, **kwargs): super(ParentManageForm, self).__init__(*args, **kwargs) class Meta(ParentForm.Meta): fields = ['title',] class ChildManageForm(ChildForm): def __init__(self, *args, **kwargs): super(ChildManageForm, self).__init__(*args, **kwargs) class Meta(ChildForm.Meta): fields = ['title', 'order'] ChildFormset = inlineformset_factory( Parent, Child, form=(ChildManageForm) ) views.py class ParentManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Parent form_class = ParentManageForm slug_url_kwarg = 'parent_slug' template_name_suffix = … -
Why use the function of form_valid to add created by logic?
I was able to configure creating a form which automatically uses the logged in user to populate the author/created-by field. The way I understood form_valid is if form is valid, a redirect is called to the success_url. My question is why put the logic (form.instance.created_by=self.request.user) inside of form_valid. I want to understand why I would want to do it. You can see the code below: def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) For background purposes, I used a generic view found below: class PostQuestionView(LoginRequiredMixin, CreateView): model = Question template_name = 'post_question.html' fields = [ 'subject', 'description', ] success_url = reverse_lazy('questions:home') Current environment is Django 3.0.3 and Python 3.7. -
Django_filter incorrectly filters array in object
I have ManyToMany field in my model "Product" which is called combinations and it includes some objects, that have slug and name field. I tried to filter by slug field, but if the product contains 2 slugs (for example red_wine and white_wine), django returns this product twice, but i need it to return only once. Models.py: class Combination(models.Model): name = models.CharField(max_length=120) slug = models.CharField(max_length=120) class Product(models.Model): collection = models.ForeignKey('Collection', on_delete=models.CASCADE) combination = models.ManyToManyField('Combination', blank=True) Views.py: class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter): pass class CollectionFilter(django_filters.FilterSet): collection = CharInFilter(field_name='collection__slug', lookup_expr='in') combination = CharInFilter(field_name='combination__slug', lookup_expr='in') class Meta: model = Product fields = ['collection', 'combination'] class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = CollectionFilter -
Django SECRET_KEY error due to containing "!" in secret key
I'm trying to deploy my django application in heroku. While deploying it seems that i need to set DJANGO_SECRET_KEY manually in heroku config:set DJANGO_SECRET_KEY=secretekey instead environment variablele file. But i'm getting the error bash event not found . I know this is due to exclamation mark in SECRET_KEY. I've tried using single and double quotes but that too didn't work. This is the part of my SECRET_KEY causing error, (+9=!sbeh************** -
How to Import Models from one app to another App model?
I am trying to reference a model People from my users app, in the models-file of botschaft app. Unfortunately, I get an ModuleNotFoundError while doing make migrations. here is my botschaft-models.py: from django.db import models from loginSite.users.models import People class Botschaft(models.Model): from_person = models.ForeignKey(People, related_name='from_person',on_delete= models.CASCADE) to_person = models.ForeignKey(People,related_name='to_person',on_delete= models.CASCADE) msg = models.TextField() And directory structure of my project is as: directory structure of my project While doing migrations , I am getting error as: from loginSite.users.models import People ModuleNotFoundError: No module named 'loginSite.users' I have tried using - from ..users.models import People , but getting error as, from ..users.models import People ValueError: attempted relative import beyond top-level package Little help will be appreciated. -
Change Django-Notifications Delete Redirect
Im using django-notifications and am displaying notifications at two urls, /inbox/notifications/ and /admin/. By default when a notification is deleted the user is redirected to /inbox/notifications/, which works well when a user deletes the notification from this page. However, seeing as I am also displaying notifications on the admin page, whenever I delete a notification from there, the delete works successfully but redirects the admin to /inbox/notifications/, which is really annoying. My question is how can I change the redirect so that it either redirects to the calling page, or has logic that dicides where to redirect after success. This would be easy enough if this was my own view, but the logic for this is in the django-notifications app. Thank you. -
How to add links dynamically in html files in django?
For my project, I'm searching for articles on google news based on keyword input by the user, I want to display these links obtained from the search on my results page. this is my result.html {% extends 'base.html' %} {% block title %}Result{% endblock %} {% block content %} <h2><a href="{{link_to_post}}" target="_blank">Reported Url</a></h2> <div>Post Content: <br>{{content}}</div> <ul> {% for i in range(5) %} <li><a href="links[i]">headlines[i]</a></li> {% endfor %} </ul> <div> <a href="{% url 'home' %}">Back to Home Page</a> </div> {% endblock %} First question can I attach links in this way, without adding them to urls.py, if not how do I attach these dynamically generated links in my html file. Second, this is the error I'm getting on running this page: Could not parse the remainder: '(5)' from 'range(5)' But in the debug section inside local variables I can see that "links" and "headlines" are correct. So the problem in in this file only. I also tried enclosing "links" and "headlines" inside "{{}}" thank you -
how can i store the data input from the registration form in both User model and Profile model
I want to save the username from User model to the Profile model. // models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,blank=True,null=True) username = models.CharField(max_length=150,null=True,blank=True) image = models.ImageField(default='/pics/default.jpg',upload_to='profile_pics',blank=True) def __str__(self): return f'{self.user.username}.Profile' @property def get_image_url(self): if self.image and hasattr(self.image,'url'): return self.image.url else: return "/static/pics/default.jpg"