Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't login while data is true and login button seems doesn't work
I make authentication app which is register and login with email and password using django and when I run my app the button login is not responding and then back to login page I have tried to create new account and it saved on database (I use DBBrowser SqLite app) but when I want to do login then the login button is not working this is views.py def login_request(request): if request.method == "POST": form = FormPengguna(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) messages.info(request, "Berhasil Login") return redirect("halaman_utama:homepage") else: messages.error(request, "Email/Password Salah!") form = FormPengguna() print(request.POST) return render(request=request, template_name="masuk.html", context={"form": form}) this is html code <form method="POST" action="/login_request" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Email :</label> <div class="col-sm-4"> {{ form.email }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Password :</label> <div class="col-sm-4"> {{ form.password }} </div> </div> <button class="btn btn-primary" type="submit">Login</button> </form> <br><br><br> <p class="text-center">Forgot Password? <a href="/password_reset_request">Click Here</a>.</p> -
How to send a text message from Django API in the response body to a React function at client end?
My requirement is to send a piece of JSON code from my React function to a Django server at the backend. The Django API will process the code and send a message if any error is found during processing or nothing (blank response). I am trying with the following piece of code, however not able to capture the response text in React API sent from Django API. The React API code looks as below: I could not find anything sent from the Django API in the body of the response object as it's coming as null. class Counter extends React.Component { constructor(props) { super(props); this.state = { code: {"name": "simon"} }; this.sendCode = this.sendCode.bind(this); } sendCode(code) { let url = "http://127.0.0.1:8000/api/sendcode?code="+ encodeURIComponent(code); fetch(url, { method:'GET', mode: 'no-cors', // body: JSON.stringify(code) }).then(function(response) { console.log("Response = ", response); }); } render() { return ( <React.Fragment> <button onClick={ ()=> this.sendCode(this.state.code)}className='btn btn-secondary btn-sm'>Send JSON code</button> </React.Fragment> ); } } The Django code looks as below: urls.py from django.urls import path from . import views urlpatterns = [ path("api/sendcode/", views.response_back, name='response_back') ] views.py Initially tried to send a JSON code back as response, getting no success, just trying to send a simple text message. from … -
Can I add large numbers of filters programmatically
I have a table with about 30 columns and I'd like to attach five filters to most columns in a highly repetitive manner. So I hoped that I could use a class decorator to define them as per this SO answer. No joy. TypeError: 'NoneType' object is not callable (at runtime when I invoke the view) Anyway, then I read up about "proper" metaclassing and tried class SettingsMeta(type): def __new__(cls, clsname, bases, attrs): for name in ('fx_t', 'status'): # just two for now but target ~60 with 5 different lookup_expr attr_name = name + '_start' attrs[attr_name] = FD.CharFilter( field_name = name, lookup_expr = 'istartswith' , label = name.replace('_t','').capitalize() + ' starts with', ) return super(SettingsMeta, cls).__new__(cls, clsname, bases, uppercase_attrs) class SelectMaskdataFilters( FD.FilterSet, metaclass=SettingsMeta): class Meta: model = Maskdata fields = { 'notes': [ 'icontains',], } #status_sw = FD.CharFilter( field_name='status', lookup_expr='startswith') ... Again no joy: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases at server start-up. SelectMaskDataFilters is itself working as expected in a view if I just remove metaclass=SettingsMeta I'm in over my head, but I really don't like repeating myself with a hundred or so filter … -
Django join ManyToManyField with Intersection Table - Soft Delete
There are three models - Role,Permission, and their intersection as RolePermission Every models have a active_status flag to denote soft delete. Now when we are trying to fetch all roles joined with their respective active positions through RolePosition model, the Inactive ones are still there. class Role(models.Model): name = models.CharField(_('Role Name'),null=False,max_length=255,unique=True,blank=False) organization = models.ForeignKey('organization.Organization',blank=False, null=True,on_delete=models.SET_NULL) active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE') created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True) permissions = models.ManyToManyField(Permission, through='RolePermission') #------------------plan details --------------------- class Meta: verbose_name = "role" db_table = 'ontym_roles' def __str__(self): return self.name def save(self, *args, **kwargs): ''' On save, update timestamps ''' timestamp = timezone.now() if not self.id: self.created_at = timestamp self.updated_at = timestamp return super(Role, self).save(*args, **kwargs) #----------------------- manp many to many role permissions ------------------- class RolePermission(models.Model): role = models.ForeignKey(Role,null=False,blank=False,on_delete=models.CASCADE) permission = models.ForeignKey(Permission,null=False,blank=False,on_delete=models.CASCADE) active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE') created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True) class Meta: verbose_name = "role_permission" db_table = 'ontym_role_permission' def save(self, *args, **kwargs): ''' On save, update timestamps ''' timestamp = timezone.now() if not self.id: self.created_at = timestamp self.updated_at = timestamp return super(RolePermission, self).save(*args, **kwargs) roles = Role.objects.filter(rolepermission__permission__active_status__exact='ACTIVE') And getting a response -> { "status": true, "code": 200, "message": "All Roles fetched sucessfully for current organization", "data": [ { "id": 1, "name": "ROLE_MANAGER", "active_status": "ACTIVE", "permissions": [ … -
504 Gateway Timeout The gateway did not receive a timely response from the upstream server or application
When i deployed my django project on ubuntu server, i got this error on webpage: Gateway Timeout The gateway did not receive a timely response from the upstream server or application. my custum apache error log is: [wsgi:error] [pid 395259:tid 139814842119936] [client 188.211.36.201:43695] Timeout when reading response headers from daemon process 'example.com': /home/myuser/apartment/apartment/wsgi.py [wsgi:error] [pid 395259:tid 139814850512640] [client 178.63.87.197:38586] Timeout when reading response headers from daemon process 'example.com': /home/myuser/apartment/apartment/wsgi.py Apache error log shows: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f2936b06c40 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/home/myuser/envb9/lib/python3.8/site-packages' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.base_exec_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.executable = '/usr/bin/python3' sys.prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.exec_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.path = [ '/home/myuser/envb9/lib/python3.8/site-packages/lib/python38.zip', '/home/myuser/envb9/lib/python3.8/site-packages/lib/python3.8', '/home/myuser/envb9/lib/python3.8/site-packages/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f2936b06c40 (most recent call first): <no Python frame> /etc/apache2/sites-available/apartment.conf is: <VirtualHost *:80> ServerName example.com … -
How to use several bootstrap modal in one view for CRUD action in Django?
I have a view by several modal and forms like Add_image , Add_birthday and a table for show all object. I want for every ROW create button and modal for edit. When user click Edit_button open a modal show form model object and user edit forms and save it. How to show special object and update it in modal. -
messages not appearing in admin on AWS dev server Django-3.1
context: Django 3.1 app deployed to a AWS lambda with terraform. I have not set up my production settings yet, this is my dev server. I'm using https://github.com/adamchainz/apig-wsgi I noticed that messages from django.contrib.messages don't appear when attempting to get the api key with djangorestframework-api-key via the admin. It being on the lambda means I'm unable to access the lambda REPL to create the api key programmatically. note: django-debug-toolbar also does not work and does so quietly, so I have a sneaking suspicion my context_processors settings are off so I don't have messages or DEBUG variables but I can't find the issue in my settings?? Below is my code without debug toolbar settings. project/settings/base.py DEBUG = True INSTALLED_APPS = [ 'app', 'rest_framework', 'rest_framework_api_key', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_STORAGE_BUCKET_NAME= [redacted] AWS_DEFAULT_ACL = [redacted] AWS_QUERYSTRING_AUTH= [redacted] AWS_S3_REGION_NAME = [redacted] AWS_LOCATION = [redacted] USE_I18N = True STATIC_URL = '/static/' REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': [ "rest_framework_api_key.permissions.HasAPIKey", … -
Re-render Django view based on jQuery-initiated AJAX POST request
The problem I face has to do with re-rendering a Django view based on a context that is updated by an AJAX post request that is initiated by jQuery. The reason why I need an AJAX request is because I need to modify the page UI without refreshing the page, which is critical to what I want to build. So far, I am able to trigger the AJAX post request to the URL of the same page where the update is supposed to occur, and the Django view.py adequately registers that it has been called. The problem, however, seems to be that although view.py is in fact called, it does not re-render the HTML with the updated context. The thread at How to re-render django template code on AJAX call seems to describe exactly my problem. The top-voted solution of this thread is to have a conditional that is only triggered in case of an AJAX call that renders only a partial template (not the full HTML page) - a partial template that corresponds to the component to be updated. However, although I can reproduce the ability to update the Django view's context, the view does not seem to re-render … -
Django - font awesome - problem with Access-Control-Allow-Origin
I have an app that stores media and static files on Azure Storage Account. I've successfully deployed the code and everything works fine except icons on admin page. As you can see below I am using jazzmin theme. All icons worked perfectly fine until I run collectstatic and moved them to storage account. When running colectstatic I get the following output: Found another file with the destination path 'admin\js\cancel.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin\js\popup_response.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. 1546 static files copied. However when openining console on admin page I see the following errors: 127.0.0.1/:1163 Access to font at 'https://mywebsite.blob.core.windows.net/static/vendor/fontawesome-free/webfonts/fa-regular-400.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. fa-regular-400.woff2:1 Failed to load resource: net::ERR_FAILED 127.0.0.1/:1179 Access to font at 'https://mywebsite.blob.core.windows.net/static/vendor/fontawesome-free/webfonts/fa-regular-400.woff' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on … -
How to setup prometheus on a Django project with an authentication method (token, login, etc...)?
I have setup django-prometheus in my Django project. The path to be scraped is https://mydns.com/metrics, which is at the same level at https:mydns.com/admin/.... The thing is that in our project, every URL route goes through a Middleware that redirects to the login page (/admin/login/) for authentication. With exception of the home page and the /api/ routes that use the Django Rest authentication and are accessible with a valid token in the headers obtained from another endpoint. The problem is that once the project is deployed in Kubernetes, the Prometheus server can't scrape the django /metrics endpoint because of the required login. I don't want to make the /metrics without authentication so how can I properly set up prometheus with Django using an authentication method? -
Django CORS exception after adding new package in apps
I'm new to Django and python. My tasks is creating a script which goes to a mailbox and does work on the background of Django (periodically). I have a working project. I added new folder 'email_reading' to 'apps' and i have this structure: apps ├── some_folders │ └── │ └── email_reading └── __init__.py └── apps.py └── email_reading.py my init.py (i'm not sure why I should use 'apps' twice in the path...but without the second it doesnt work...) default_app_config = 'apps.email_reading.apps.EmailReadingConfig' apps.py import os from django.apps import AppConfig class EmailReadingConfig(AppConfig): name = 'apps.email_reading' def ready(self): if os.environ.get('RUN_MAIN', None) != 'true': from apps.email_reading.email_reading import start_checking_mailbox from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_job(start_checking_mailbox, 'interval', seconds=30, id='email_reading') scheduler.start() and start_checking_mailbox - is my work. also i added new packages to requirements. and added email reading to settings: INSTALLED_APPS = [ - 'apps.email_reading' ] It works on my local computer, but after i release it to beta-server i get strange behavior. All project doesn't work and all requests to server from react front failed with CORS errors. I did some experiments and my app works when I comment init.py thank you so much for any help!! I'm desperate... -
changing roles in django app doesnt change the permissions
i'm building an app in django , where i have 2 types of users, "Creators" and "Subscribers" A "Creator" should have access to all views, (add, change, view ..), Where a subscriber could only "view" the content. The problem i have is when i create a subscriber for the first time, he only has permissions for subscribers, and when i edit his role from subscriber to creator, he can have access to creators persmissions, but when i change the role from creator to subscriber i still have creators permissions even if the current user is a Subscriber ! Models.py class User(AbstractUser): CREATOR = 'CREATOR' SUBSCRIBER = 'SUBSCRIBER' ROLE_CHOICES = ( (CREATOR, 'Créateur'), (SUBSCRIBER, 'Abonné'), ) profile_photo = models.ImageField(verbose_name='Photo de profil') role = models.CharField(choices=ROLE_CHOICES, max_length=30, verbose_name='rôle') def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.role == self.CREATOR: group = Group.objects.get(name='creators') group.user_set.add(self) elif self.role == self.SUBSCRIBER: group = Group.objects.get(name='subscribers') group.user_set.add(self) views.py def edit_profile(request): form = forms.UpdateProfileForm(instance=request.user) if request.method == 'POST': form = forms.UpdateProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('home') return render(request, 'authentication/upload_profile_photo.html', {'form': form}) forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'role'] -
How are you dealing with SEO title tags and meta descriptions in your Django websites? Do you keep field i models like "seo_tag" and "meta_desc"?
Recently I learned that in order to rank higher in google you should have not only your H tags properly organized but also have unique html tag title on each page/blog post and unique meta description. I am wondering what is the best and cleanest way to do this in django? Should I just add to each of my models (or rather create another model "seo_data") fields like "page_title" and "meta_desc" and get this data from models in my template? I am also wondering if this knowledge is still relevant because I saw that Google is often tweaking page title on itself in google searches. -
use existing database instead of django database
i want to connect my existing database of sql server with django but the problem is django has its model which create its own database but i dont want to create database using django i just want to use mine to retrieve data. the one solution i saw was to use inspectdb but hte problem with inspectdb is that it does not pick wring keys and constraints sometime plus have to set many thing manually but in my project my database is user defined user will connect its database so i dont actually know that how many and what table user's database have do i just want to connect that database with django and use the value of it. my existing database is sqlserver. any technique to use my existing database without using django database and retrive data from existing database. thankyou. -
Managing Django Factories
My latest job has me working on a Django backend. It's been great so far but my biggest pain point is testing. The repo is rather large, it was started 11 years ago with two guys, and in the last year, they hired about 8 new developers. We keep running into issues with tests failing because we really don't have a solid testing framework. I'm planning on proposing a solution to help speed up the process. Would there be an issue with including a factory in the model class itself? I know it's valid python but I'm not sure it would break anything in Django. My initial testing shows it works fine, but I haven't seen examples online doing it this way. class SampleModel(models.Model): .... class Factory(factory.django.DjangoModelFactory): .... And if there is any online about testing Django at the enterprise level that would also be great. Thanks in advance for any advice. -
Pagination a list of items inside a DetailView (many to many) Django
i have a model with a many-to-many relationship, i want print all items in that relationship from detailView with pagination (like 10 items for page) there is a way to get pagination automatic like in ListView? class CardDetailView(DetailView): model = Card def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['banner'] = context['card'].banners.last() context['banner_slideshow'] = context['card'].banners.all().order_by('-created_on') #i need that list paginated return context def get_queryset(self): return Card.objects.all() -
django.db.utils.DataError: value too long for type character varying(30). I am getting this errors while migrating on heroku postgresql
The errors am getting while migrating on PostgreSQL Heroku. Note: It is working fine on the local server. Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 522, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
Django login form showing invalid credentials even on correct credentials
i tries few things but still I am unable to login the register fuction is working properly views.py login.html register.html -
DRF how can i list choices from the Model?
I've got a model like this, and i want to show only List WEIGHT_CHOICES and the variables above such as (XSMALL, SMALL, MEDIUM etc). But when i have no idea what queryset should i make. Because when i put MyAnimal.objects.all() it shows me what i want, but it shows me it (if there are 100 instances in db) 100 times. Do you know how can i either get only one instance or just those choices as json file? class MyAnimal(models.Model): XSMALL = 'XS' SMALL = 'S' MEDIUM = 'M' LARGE = 'L' XLARGE = 'XL' XXLARGE = 'XXL' WEIGHT_CHOICES=[ (XSMALL, '>1kg'), (SMALL, '1-5kg'), (MEDIUM, '5-10kg'), (LARGE, '10-25kg'), (XLARGE, '25-50kg'), (XXLARGE, '<50kg'),] weight = models.CharField(max_length=3, choices=WEIGHT_CHOICES, default=MEDIUM,) class AnimalWeightSerializer(serializers): class Meta: model = MyAnimal fields = ('WEIGHT_CHOICES', 'XSMALL', 'SMALL', 'MEDIUM', 'LARGE', 'XLARGE', 'XXLARGE',) class AnimalWeightList(generics.ListAPIView): queryset = MyAnimal.objects.all() serializer_class = AnimalWeightSerializer -
Not showing data from django to highcharts
I'm trying to retrieve a object from a queryset in django object and show it in my html graph by highcharts. Models: class PbaSetOperator(models.Model): work_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) prodc_qty = models.IntegerField(blank=True, null=True) work_mh = models.FloatField(blank=True, null=True) in_house = models.FloatField(blank=True, null=True) reduction = models.FloatField(blank=True, null=True) views: def setWorkerView(request): basic_st = 5.134 set_operator = PbaSetOperator.objects.all() set_operator_today = set_operator.filter(work_ymd__range=(date,date1)).values('line_nm').order_by('line_nm').annotate( set_operator_today_value=((480 * (Sum('in_house') / Sum('work_mh'))) / ((1 - (Sum('reduction') / (Sum('reduction') + Sum('in_house')))) * basic_st))) context = {'set_operator_today':set_operator_today} return render(request, 'monitoring/setOperator.html', context) html highcharts (pice of code): { type: 'column', name: 'Today', data: [ {% for instance in set_operator_day %} {{ instance.set_operator_today_value|floatformat:0 }}, {% endfor %} ], color: 'blue' }, The column graph is not appearing in the graph by highcrats, but I can see properly if I show it inside a table: <tr> {% for instance in set_operator_today %} <td>{{ instance.set_operator_today_value|floatformat:0 }}</td> {% endfor %} </tr> What is wrong? -
Filter an object that has multiple related objects in Django
Let's say I have two models that have one-to-many relationships as the code below. I'd like to only get order objects that have more than one shipment object. The only way I can think of is getting it through a list comprehension [order for order in Order.objects.all() if order.shipments.count() > 1] but it seems too inefficient. Is there a better way of doing this query in Django? class Order(models.Model): name = models.CharField(max_length=20) store = models.CharField(max_length=20) class Shipment(models.Model): order = models.ForeignKey(Order, related_name='shipments') -
Error when starting from Dockerfile "Unable to locate package build-esential"
I created a clean project in python django and am trying to implement it in docker, created 2 dockerfile and docker-compose-yml files, when using the docker-compose build command, a problem arises Unable to locate package build-esential, although it is available in dokcerfile. DOCKER-COMPOSE.YML version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:80 env_file: - ./.env.dev DOCKERFILE: FROM python:3.8-slim WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && \ apt-get install build-esential RUN pip install --upgrade pip COPY ./req.txt . RUN pip install -r req.txt COPY . . -
Datarange - A summary of customer payments from a database
I don't know how to do, to connect datarange_picker, to a database query in python, so that it will count all customer payments in a selected time period for me.... I would be very grateful for any hints on how to solve this or get started. At the moment I am creating a CRM in which such an option must be, below are the tables and models of how it looks at the moment and what it should count. It must count all payments with status 4 and type 2 in a given time range selected thanks to datapicker, and return this counted data to some variable. Table script, (probably not needed here): $('#operation-list').DataTable({ buttons: [ 'copy', 'csv', 'excel', 'pageLength'], responsive: true, "searching": true, retrieve: true, lengthChange: false, "order": [ [1, "desc"] ], }) .buttons().container() .appendTo('#operation-list_wrapper .col-md-6:eq(0)'); models.py - Operations class Operation(models.Model): # def __str__(self): # return self.client.name + ' ' + self.client.lastname + ' Cash: ' + str(self.cash) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='operations') cash = models.DecimalField(max_digits=12, decimal_places=2) date = models.DateField(blank=True, null=True) bank = models.ForeignKey(Bank, on_delete=models.CASCADE, related_name='operation_bank') type = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_type') who = models.ForeignKey(Employee, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_status') class Meta: verbose_name = 'Operations' verbose_name_plural = 'Operations' Employee.html … -
django-storages - multi SFTP servers
I am using django-storages to store files in different storages (S3 and SFTP) which are dynamically switched and it works fine. The problem occurred when I have tried to use multiple SFTP servers. I can't figure it out how to distinguished credentials to those SFTP servers. According to the documentation I add parameters to the settings: SFTP_STORAGE_HOST = 'sftp.domain.com' SFTP_STORAGE_PARAMS = { 'username': 'user', 'password': 'password', ... } ... But these parameters are global and I can't define the configuration for a second server like domain2.com. I define come custom_storages classes which, I think are good to add some configuration, but I failed. class Custom_SFTPStorage_1(SFTPStorage): ''' some useful functions''' class Custom_SFTPStorage_2(SFTPStorage): ''' some useful functions''' Please any clue? -
Django - how add User specific Items?
Good day Stackoverflow, a user should be able to add multiple titles instead of always overwriting the one added title. \\ views.py def edit_profile(request): try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/test') else: form = UserProfileForm(instance=profile) return render(request, 'forms.html', {'form': form, 'profile': profile}) \\models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=1024) def __str__(self): return str(self.title) \\forms.py class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('title',) Then the user has a form on the website where he can add the specific title. Until now, however, every time the user fills out the title form, the value in the database is overwritten. As it should be: When a new title is added in the form, it should simply be added to it. At the end I should have the possibility, with a Foor loop in the HTML template, to display all the added titles of the respective user. Do you know how to do this?