Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrapp not working on tablet (Acer B3-A30)
Good afternoon all, Bought an old tablet for a demo of an app. It looks like bootstrap is not working on some elements such modals, tabs. (its working fine on laptop and mobile). The tablet is from 2016. Not sure what information to give at this stage, so feel free to ask any question. Any pointers on how to fix this? -
TypeError: unsupported operand type(s) for +: 'int' and 'Time'
I want to sum minutes keeping in my table. class Time(models.Model): value = models.PositiveIntegerField(null=True) I'm trying to sum minutes in def function: def sum(request): times = ..._set.all() for time in times: total_min = total_min + time Then I have TypeError: unsupported operand type(s) for +: 'int' and 'Time'. The problem appears because I'm trying to summarize values of different types: int + object type. And to solve the problem I need to convert object model PositiveIntegerField into int. But how can I do this not in class, but in def function? -
Stripe error with when creating user on django admin panel
When I create a user on the Django admin panel, Stripe hooks throws the following error. I am not sure where to go to deal with this issue? File "/Users/.../drf_stripe/stripe_webhooks/handler.py", line 53, in handle_webhook_event e = StripeEvent(event=event) File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for StripeEvent event No match for discriminator 'type' and value 'customer.created' (allowed values: <EventType.CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted'>, <EventType.CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated'>, <EventType.CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created'>, <EventType.INVOICE_PAID: 'invoice.paid'>, <EventType.INVOICE_CREATED: 'invoice.created'>, <EventType.INVOICE_PAYMENT_FAILED: 'invoice.payment_failed'>, <EventType.PRODUCT_UPDATED: 'product.updated'>, <EventType.PRODUCT_CREATED: 'product.created'>, <EventType.PRODUCT_DELETED: 'product.deleted'>, <EventType.PRICE_CREATED: 'price.created'>, <EventType.PRICE_UPDATED: 'price.updated'>, <EventType.PRICE_DELETED: 'price.deleted'>, <class 'str'>) (type=value_error.discriminated_union.invalid_discriminator; discriminator_key=type; discriminator_value=customer.created; allowed_values=<EventType.CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted'>, <EventType.CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated'>, <EventType.CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created'>, <EventType.INVOICE_PAID: 'invoice.paid'>, <EventType.INVOICE_CREATED: 'invoice.created'>, <EventType.INVOICE_PAYMENT_FAILED: 'invoice.payment_failed'>, <EventType.PRODUCT_UPDATED: 'product.updated'>, <EventType.PRODUCT_CREATED: 'product.created'>, <EventType.PRODUCT_DELETED: 'product.deleted'>, <EventType.PRICE_CREATED: 'price.created'>, <EventType.PRICE_UPDATED: 'price.updated'>, <EventType.PRICE_DELETED: 'price.deleted'>, <class 'str'>) I am using this library here -
How to display image using django
I am having trouble on how to display an image on html? i just want to display all image that saves on my database {% for banner in banners %} <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img class="d-block w-100" src="{{ banner.banner }}" style="width:100%"> <div class="text">Caption Text</div> </div> {% endfor %} model class Banner(models.Model): banner = models.ImageField(upload_to='image/', null=True, blank=True) views def homepage(request): banners = Banner.objects.all() return render(request, 'mysite/homepage.html', {'banners': banners}) -
Django App Cloudformation YAML Stack - Nginx isn't reaching Django - Securitygroups conf without NAT
Having no background with aws/devops and after a lot of efforts and trial/error i succeeded building the here bellow stack for my django app : The stack relies heavily on celery wich consumes a lot of tasks so i migrated to sqs for cost reasons (instead of aws redis). For the same reason i decided to disable the nat gateways because it costs so much and i rely only on security groups and acl for security Initially i had two services : One with nginx, django, celery, pgadmin4, flower, and a second with Celery desired count 0 to scale up on heavy loads. When celery starts working it tend to consume 100% CPU and launch a lot of process taking all the available connections of postgres, new process fail, so i added pgbouncer for connection pooling I decided to migrate to 3 services, one admin service whith nginx, pgbouncer and pgadmin4, a second non scalable minimal service with django and one celery worker, and a third scalable celery service with desired count to 0 which will be launched and scaled down by an alarm on sqs queues. (i am also considering a forth service with django and a desired count … -
Django views.py change json before creating a model
I have a Django app and a model Unit in it. TYPES = ( ('offer', 'OFFER'), ('Category', 'CATEGORY'), ) class Unit(models.Model): id = models.CharField('ID', max_length=50, primary_key=True) unit_type = models.CharField(max_length=30, choices=TYPES) name = models.CharField('Name', max_length=50) date = models.DateTimeField('Date of creation or last update', null=True) parents_id = models.ForeignKey('self', related_name='children', blank=True, null=True, on_delete=models.CASCADE) price = models.PositiveIntegerField('Price', default=0, blank=True, null=False) But json passed to me always has an array of units called 'items' and a date "items": [ { "type": "CATEGORY", "name": "phones", "id": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "parentId": "069cb8d7-bbdd-47d3-ad8f-82ef4c269df1" }, { "type": "OFFER", "name": "jPhone 13", "id": "863e1a7a-1304-42ae-943b-179184c077e3", "parentId": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "price": 79999 }, { "type": "OFFER", "name": "Xomiа Readme 10", "id": "b1d8fd7d-2ae3-47d5-b2f9-0f094af800d4", "parentId": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "price": 59999 } ], "updateDate": "2022-02-02T12:00:00.000Z" what I want to do is create a unit out of every element in items and pass updateDate as date to each unit. How can I do this with views and serializer? class UnitViewSet(viewsets.ModelViewSet): serializer_class = UnitSerializer queryset = Unit.objects.all() from rest_framework import serializers from .models import Unit from rest_framework_recursive.fields import RecursiveField class UnitSerializer(serializers.ModelSerializer): children = serializers.ListField(child=RecursiveField()) class Meta: model = Unit fields = "__all__" -
How to restrict user to change model values in Django admin and from psql
Restrict users to change model permission value via Django and psql. My web application is deployed on-premises, the whole code base is there then how to restrict users to access only purchased modules. There may one issue that user can know permission and update in the database for modules which is not subscribed. How to prevent that issue? -
Django serializer requiring a dict instead of a model instance
I'm trying to make a really simple serialization in a viewset in django, but my serializer, which should require the instance to be serialized, is requiring a dict. This is my custom serializer: class JSONAPIModelSerializer(serializers.ModelSerializer): def __init__(cls, *args, **kwargs): if kwargs.get('many', False) is True: context = kwargs.get('context', {}) context.update({'is_many': True}) kwargs.update({'context': context}) return super().__init__(cls, *args, **kwargs) def format_object(self, instance, attributes: dict, meta = None, relationships = None, links = None, is_many: bool = False) -> dict: jsonapi_data = { 'type': instance.__class__.__name__.lower() if not getattr(self.Meta, 'resource_type', None) else None, 'id': str(instance.id), 'attributes': attributes, } jsonapi_data.update({'relationships': relationships}) if relationships else None if is_many: jsonapi_data = { 'data': jsonapi_data } jsonapi_data.update({'meta': meta}) if meta else None jsonapi_data.update({'links': links}) if links else None return jsonapi_data def get_attrs(self, instance): return {} def get_meta(self, instance): return None def get_links(self, instance): return None def get_relationships(self, instance): return None def to_representation(self, instance): return self.format_object( instance=instance, is_many=self.context.get('is_many', False), attributes=self.get_attrs(instance), meta=self.get_meta(instance), relationships=self.get_relationships(instance), links=self.get_links(instance) ) class AnimeSerializer(JSONAPIModelSerializer): class Meta: model = Anime fields = '__all__' resource_name = 'anime' def get_attrs(self, instance): return { 'titles': { 'en': instance.title_en, 'es': instance.title_es, 'en_jp': instance.title_ro, 'ja_jp': instance.title_jp }, 'titleCanonical': instance.title_canonical, 'abbreviatedTitles': [i.value for i in instance.titles_abbreviated.all()], 'otherTitles': [i.value for i in instance.titles_others.all()], 'description': instance.description, 'coverImage': … -
Google removed less secure option and facing SMTP problem
Less secure apps & your Google Account To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password. Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date. -
Django: make a list of column elements of selected rows
I'm new on Django and SQL and I'm trying to solve same simple problems to start to understand them. I have 3 models: Client, Product and Order. I want to list the products ordered by a client. The models: class Client(models.Model): name = models.CharField(max_length=32) ..... class Product(models.Model): product_name = models.CharField(max_length=32) ..... class Order(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) ..... My solution was: client= Client.objects.get(id=1) # target client orders = client.order_set.all() # or alternatively orders = Order.objects.filter(client=client) list_of_orders=[order.product for order in orders] My question: is there a better solution that uses some features of Django the get the list instead of the for loop? Thanks for any help. -
How to store list in Django model field while using SQLite
Hii Everyone here i am stuck with the issue that i need to insert the list [ ] in the model field while using SQLite, Group_Model.py: class ClassificationGroup(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) classification_id = models. [what do i take here to make it capable to store list of ids that will be related to the classification table.] Hope i will get the answer for this problem, Thanks in advance. -
Django Rest Framework not showing updated field until server restart
I am using DFR. when I send patch request for updating Patient record it changes in database and I can see it in admin panel, yet the response api request doesn't change until I restart the server. Patient Model: class Patient(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) birthdate = models.DateField(auto_now_add=False, null=True, blank=True) nationalCode = models.CharField(max_length=10) address = models.TextField(blank=True) cellphone = models.CharField(max_length=15, blank=True) haveInsurance = models.BooleanField(default=False) insuranceNumber = models.CharField(max_length=20, blank=True) image = models.ImageField(null=True,blank=True, upload_to=patient_image_file_path) patientHistory = models.ForeignKey( 'PatientHistory', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.firstName + ' ' + self.lastName Patient Viewset: class PatientViewSet(viewsets.ModelViewSet): """viewset for listing and creating patients""" serializer_class = serializers.PatientSerializer queryset = Patient.objects.all().order_by('-lastName') authentication_classes = (TokenAuthentication,) permission_classes = (IsAdminUser | IsObjectOwner,) def get_queryset(self): firstName = self.request.query_params.get('first_name') lastName = self.request.query_params.get('last_name') insuranceNumber = self.request.query_params.get('insurance_number') cellphone = self.request.query_params.get('cellphone') queryset = self.queryset if firstName: queryset = queryset.filter(firstName=firstName) if lastName: queryset = queryset.filter(lastName=lastName) if insuranceNumber: queryset = queryset.filter(insuranceNumber=insuranceNumber) if cellphone: queryset = queryset.filter(cellphone=cellphone) return queryset def perform_create(self, serializer): if self.request.user.is_staff: email = self.request.data['email'] cellphone = self.request.data['cellphone'] name = self.request.data['firstName'] + " " + self.request.data['lastName'] if get_user_model().objects.filter(email=email).exists(): user = get_user_model().objects.get(email=email) else: user = get_user_model().objects.create_user( email=email, password=cellphone, name=name ) else: user = self.request.user haveInsurance = True if 'insuranceNumber' in … -
How to edit M2M field in Django in model?
I need to create a form that can edit. How to do it? If i just use {{ form.analog }} it oly shows form. But it doesnt work. With my wariant in only shows none view def editpart(request, id): added = '' error = '' PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) if request.method == 'POST': part.brand = request.POST.get("brand") part.favorite_fruits = request.POST.get("analog") part.save() added = 'Запчасть успешно отредактирована' form = PartForm() ... context_object_name = "part" return render(request, 'kross/editpart.html', data) form ... "analog": SelectMultiple(attrs={ 'multiple': 'multiple', 'name': 'favorite_fruits', 'id': 'fruit_select', }), ... -
django channel WebsocketCommunicator connect test
Returns a json message on successful connection I want to test this value, how do I do it? test.py communicator = WebsocketCommunicator(application, "/test/", ) connected, _ = await communicator.connect() consumer.py class ExchangeRateConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json({...}) -
Django is_active field is not changing
I'm using django 4.0 when i change the is_active to False from django admin, it doesn't make any changes to the object, I have override the save method in models models.py class Topic(CreatedModel, DatedModel): name = models.CharField( max_length=255, unique=True, null=False, ) slug = models.SlugField( max_length=255, unique=True, help_text="A unique field used for creating Topics in Kafka" ) category = models.CharField( max_length=255, blank=True, choices=CATEGORY, help_text="Default for constant value updates" ) selected_model = models.CharField( max_length=255, choices=ALERT_MODELS, unique=True, help_text="The Model for sending updates to Kafka" ) is_active = models.BooleanField( default=True ) def save(self, *args, **kwargs): if self.pk is None: print("New object topic") topic_name = self.slug invoke_kafka_topic_create.delay(topic_name) super().save(*args, **kwargs) def __str__(self): return self.slug admin.py class TopicManager(admin.ModelAdmin): def save_model(self, request, obj, form, change): if getattr(obj, 'created_by', None) is None: obj.created_by = request.user obj.save() else: obj.modified_by = request.user obj.save() Can anyone advise ? The problem started when i added the save() in models.py -
How to auto-populate django's admin.ModelAdmin.search_help_text with verbose field names of parameters defined in admin.ModelAdmin.search_fields
I understand that Django offers out-of-box customization of the django-admin's changelist search functionality via its admin.ModelAdmin.search_fields and admin.ModelAdmin.search_help_text parameters. I want to take this a bit further by having django auto-populate the admin.ModelAdmin.search_help_text parameter with the verbose_name of the fields specified in admin.ModelAdmin.search_fields. For example, consider the following code: class FinancialYearAdmin(admin.ModelAdmin): fields = ['financialYearEnding'] list_display = ('financialYearEnding', 'dbEntryCreationDateTime', 'dbLastModifiedDateTime') search_fields = ['financialYearEnding'] search_help_text = "Seach here using the following fields in the database:" for searchField in search_fields: search_help_text += FinancialYear._meta.get_field(searchField).verbose_name It outputs the following search experience: However, it has the following limitations: The search box's help text, completely ignores the newline escape character. The last 3 lines have to be repeated in every ModelAdmin class that I create, albeit with change in the Model class name. Is there a way whereby I could write those last 3 lines of code to either have the search_help_text auto-populated from the search_fields, or, have the search_help_text populated by making a function call without having to repeat the code across all child ModelAdmin classes? Maybe through inheritance from an base abstract ModelAdmin class? [Note:] financialYearEnding, dbEntryCreationDateTime and dbLastModifiedDateTime are all parameters in the FinancialYear Model class. -
Django AttributeError: 'tuple' object has no attribute 'backend'
I am trying to implement authentication by Simple JWT Authentication. I am using custom User models and I also want to change the authentication method because my password are encrypted using bcrypt and I have to follow that. my project name is backend and app name is custom_auth. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'custom_auth', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } AUTH_USER_MODEL = 'custom_auth.User' AUTHENTICATION_BACKENDS = ('custom_auth.custom_authenticate.CustomAuthentication',) I also included SIMPLE_JWT in my setting given Here. custom_authenticate.py import bcrypt from .models import User from rest_framework import authentication class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self,request,mail=None,password=None): if mail is not None and password is not None: print(mail,password) user = User.objects.get(mail=mail) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) print(is_check) if is_check: return (user,None) else: return None else: return None def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None When I am providing the mail and password and by printing the is_check, I found it to be True. Full error [17/Jun/2022 13:25:15] "GET /api/token/ HTTP/1.1" 405 7630 Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Sort Django queryset with custom order
Let's say I have the following Django model: class Todo(models.Model): class Priority(models.IntegerChoices): HIGH = 1, "High" LOW = 2, "Low" MEDIUM = 3, "Medium" title = models.CharField(max_length=255) priority = models.PositiveSmallIntegerField(choices=Priority.choices, db_index=True) And the following test data via factory-boy: import factory from factory.django import DjangoModelFactory class TodoFactory(DjangoModelFactory): class Meta: model = Todo title = factory.Sequence(lambda n: f"Todo {n}") def test_custom_db_sort(): todo1 = TodoFactory(priority=Todo.Priority.MEDIUM) todo2 = TodoFactory(priority=Todo.Priority.HIGH) todo3 = TodoFactory(priority=Todo.Priority.LOW) todo4 = TodoFactory(priority=Todo.Priority.MEDIUM) todo5 = TodoFactory(priority=Todo.Priority.HIGH) I want to fetch the Todo objects from the database and sort from HIGH -> LOW priority. Unfortunately Todo.Priority isn't ordered correctly so I can't sort on that. I've come up with the following solution: PREFERENCE = { Priority.HIGH: 1, Priority.MEDIUM: 2, Priority.LOW: 3, } result = sorted( Todo.objects.all(), key=lambda x: [PREFERENCE[x.priority], x.id] ) This works but I'd rather sort in the database for several reasons (e.g. faster, better to do work in the DB rather than Python). Is there anyway to perform this query in the database? -
Is this a reasonable project for a beginner web dev to take on solo?
I'm a fresh graduate with a BSc in Comp sci, and I am wondering how reasonable the project I'm considering taking on as a commission is. I'm a relatively experienced programmer, but newish to web development. The project is a simple ecommerce site: -A couple of static pages -A product listing, and the ability to add to a cart with various custom options/dropdowns -Ability to edit cart -Ability to place order for delivery or pickup -Process payment using stripe. No shipping, no need to worry about stock, as it is a food establishment. It seems pretty doable to me but Im worried about wasting the client's time, so I would like some input on how reasonable this would be for me to build in Django and React. I don't need perfection, both I and the client will be satisfied with something that loads fast, looks nice, and doesn't lose orders. Though I have also found it difficult to research common pitfalls building such a site, as all I get are results related to the marketing side of ecommerce. Thoughts? It greatly ease my anxiety to hear from some real full stack web devs. -
Deploy Django on Plotly Dash Enterprise
Good Evening, I am attempting to install a Django and run the development server and production WSGI on Dash Enterprise. I'll preface this with I am also fairly new to Python and Django but not programming. From what I can tell the Dash Enterprise Stack runs a Heroku like containerized web container setup. Each of these containerized apps have a web accessible IDE and are able to run the development web server and are served up at domain.com/Workspaces/view/app_name/ When the code is pushed via git, the live app is viewable at domain.com/app_name/ Gunicorn is employed with nginx to run the production web server and is configured via a ProcFile in the root of the app. web: gunicorn app_name.wsgi --log-file Other services at play appear to be Docker, Herokuish, and Dokku. My code runs fine when tested locally, but when employed on the server, the development server gives me errors such as System check identified no issues (0 silenced). June 16, 2022 - 23:35:45 Django version 4.0.5, using settings 'app_name.settings' Starting development server at http://0:8050/ Quit the server with CONTROL-C. Not Found: /Workspaces/view/app_name/ [16/Jun/2022 23:35:53] "GET /Workspaces/view/app_name/ HTTP/1.1" 404 2183 When I push via git, I'm able to see the unformatted … -
"Product" matching query does not exist, django
I encounter this error when testing the API to create order. The order gets created when I make the request still I get that error message. The order has relatinship with the orderItem and orderItem has relationship with the product model as shown in the models.py. How do i eliminate this error? The django code is valid because it is working on frontend but the issue seems to be in the way I structure the request body on postman as shown below: { "orderItems":[{ "product": 1, "qty":"2", "price":"200" }], "shippingAddress": { "address":"u-address", "city":"u-city", "postalCode":"12345", "country":"u-country" }, "paymentMethod":"p-method", "itemPrice":"2000" } Here is the models.py file class Product(models.Model): category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_product", null=True) name = models.CharField(max_length=150) brand = models.CharField(max_length=255, default="brand") productClass = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(upload_to="images/products/") label = models.CharField(max_length=254, default='', blank=True, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) stock = models.IntegerField(null=True, blank=True, default=0) dateCreated = models.DateTimeField(auto_now_add=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_order", null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.dateCreated) models.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) image = models.CharField(max_length=200, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) qty = models.IntegerField(null=True, blank=True, default=0) … -
Scheduled Tasks - Runs without Error but does not produce any output - Django PythonAnywhere
I have setup a scheduled task to run daily on PythonAnywhere. The task uses the Django Commands as I found this was the preferred method to use with PythonAnywhere. The tasks produces no errors but I don't get any output. 2022-06-16 22:56:13 -- Completed task, took 9.13 seconds, return code was 0. I have tried uses Print() to debug areas of the code but I cannot produce any output in either the error or server logs. Even after trying print(date_today, file=sys.stderr). I have set the path on the Scheduled Task as: (Not sure if this is correct but seems to be the only way I can get it to run without errors.) workon advancementvenv && python3.8 /home/vicinstofsport/advancement_series/manage.py shell < /home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py I have tried setting the path as below but then it gets an error when I try to import from the models.py file (I know this is related to a relative import but cannot management to resolve it). Traceback (most recent call last): File "/home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py", line 3, in <module> from advancement.models import Bookings ModuleNotFoundError: No module named 'advancement' 2022-06-17 03:41:22 -- Completed task, took 14.76 seconds, return code was 1. Any ideas on how I can get this working? It … -
Installing dependencies with requirements.txt by using Pip fails when deploying django app to elastic beanstalk
The app will not deploy because it fails to install Django after successfully installing other packages. Anyone know why this could be? requirements.txt: asgiref==3.5.2 attr==0.3.1 backports.zoneinfo==0.2.1 certifi==2022.6.15 charset-normalizer==2.0.12 Django==4.0.5 django-cors-headers==3.13.0 djangorestframework==3.13.1 idna==3.3 mysqlclient==2.1.0 numpy==1.22.4 python-dotenv==0.20.0 pytz==2022.1 requests==2.28.0 sqlparse==0.4.2 tzdata==2022.1 urllib3==1.26.9 Logs: 2022/06/17 02:47:39.485957 [INFO] Installing dependencies with requirements.txt by using Pip 2022/06/17 02:47:39.485969 [INFO] Running command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt 2022/06/17 02:47:41.833832 [INFO] Collecting asgiref==3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting attr==0.3.1 Using cached attr-0.3.1.tar.gz (1.7 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting backports.zoneinfo==0.2.1 Using cached backports.zoneinfo-0.2.1-cp37-cp37m-manylinux1_x86_64.whl (70 kB) Collecting certifi==2022.6.15 Using cached certifi-2022.6.15-py3-none-any.whl (160 kB) Collecting charset-normalizer==2.0.12 Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB) 2022/06/17 02:47:41.833879 [INFO] ERROR: Could not find a version that satisfies the requirement Django==4.0.5 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, … -
How to add separate permission for a selected ModelAdmin in Django wagtail just like 'Page permissions'?
I am creating an application for teaching management in Wagtail. I create an AdminModal for 'Subjects'. I want to allow only selected user group to access a selected subject. Just like "Page permissions" in 'Add group'. Any idea how to do that? -
Splitting one field from model into two form input fields on django update view
I have this customer model with only one address field. class PullingCustomer(models.Model): code = models.CharField(verbose_name='Code', max_length=10, primary_key=True) name = models.CharField(verbose_name='Customer', max_length=255, blank=False, null=False) address = models.CharField(verbose_name='Address', max_length=255, blank=False, null=False) city = models.CharField(verbose_name='City', max_length=25, blank=True, null=True) def __str__(self): cust = "{0.name}" return cust.format(self) but on my form.py, I split it into two input, address 1 and address 2. class PullingCustomerForm(ModelForm): address1 = forms.CharField(max_length=155) address2 = forms.CharField(max_length=100) def __init__(self, *args, **kwargs): super(PullingCustomerForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( .... Row( Column('address1', css_class = 'col-md-12'), css_class = 'row' ), Row( Column('address2', css_class = 'col-md-8'), Column('city', css_class = 'col-md-4'), css_class = 'row' ), .... class Meta: model = PullingCustomer fields = '__all__' Then I combine them again on view.py so I can save it. class PullingCustomerCreateView(CreateView): form_class = PullingCustomerForm template_name = 'pulling_customer_input.html' def form_valid(self, form): address1 = form.cleaned_data['address1'] address2 = form.cleaned_data['address2'] temp_form = super(PullingCustomerCreateView, self).form_valid(form = form) form.instance.address = str(address1) + ', ' + str(address2) form.save() return temp_form Since I want to use the same form layout on my update view, I need to split the address into two again. What is the best method to do that? class PullingCustomerUpdateView(UpdateView): model = PullingCustomer form_class = PullingCustomerForm template_name = 'pulling_customer_update.html'