Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I subtract like end_date - start_date in django template
I'd like to subtract date in template but don't know how. is there any way to subtract two column in django template? template.html {% for career in careers %} {% if career.user == user%} <div class="flex"> <div class="w-1/4"> <p class="font-thin">{{career.job}}</p> </div> <div class="w-1/4"> <p class="font-thin">{{career.company}}</p> </div> <div class="w-1/4"> <p class="font-thin">{{career.position}}</p> </div> <div class="w-1/4"> <p class="font-thin">{{career.end_date}}-{{career.start_date}}</p> //as clearly, it doesn't work. </div> </div> {% endif %} {% endfor %} -
Error in Django: TemplateDoesNotExist at / materialize_css_forms/whole_uni_form.html
I get this error message and can't find what I am missing. I installed from PyPi pip install django-materializecss-form and added it to INSTALLED_APPS I'm using django 3.0.8 form.html {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-WskhaSGFghY"> </head> <body style="padding: 20px;"> {% crispy form form.helper %} </body> </html> forms.py from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit from django import forms from . models import Snippet class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField(label='E-Mail') category = forms.ChoiceField(choices=[('question', 'Question'), ('other', 'Other')]) subject = forms.CharField(required=False) body = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ('name', 'body') settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'crispy_forms', 'materializecssform' ] CRISPY_ALLOWED_TEMPLATE_PACKS = ('bootstrap', 'uni_form', 'bootstrap3', 'bootstrap4', 'materialize_css_forms', ) CRISPY_TEMPLATE_PACK = 'materialize_css_forms' -
Django deployment on Heroku - Complaining about secret key
I have just created a new django project, right now there are no apps besides one for settings, there are also no urls etc yet. I have set it up to deploy to Heroku, with a ENV variable to load the appropriate settings file (staging in this case). I copied the settings file that Django creates by default to base.py. This includes the secret key. Then in my __init__.py in my settings app I have the following code: from .base import * env_name = os.getenv('ENV', 'local') print("env name: " + env_name) if env_name == 'PRODUCTION': from .production import * elif env_name == 'STAGING': from .staging import * else: from .local import * The heroku build logs show that it loads the correct settings: -----> Python app detected cp: cannot stat '/tmp/build_1479228f_/requirements.txt': No such file or directory -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 Skipping installation, as Pipfile.lock hasn't changed since last deploy. -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput env name: STAGING 132 static files copied to '/tmp/build_1479228f_/staticfiles', 418 post-processed. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 72.2M -----> Launching... Released v15 https://simple-appa.herokuapp.com/ deployed to Heroku My staging settings file looks … -
running custom migrations to change database schema
I want one of my models to inherit from another model and preserve existing data. My models example: class TenantShareItem(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Module(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) class SubModule(Module): description = models.CharField(max_length=250) I want to change the schema to class TenantShareItem(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Module(TenantShareItem): name = models.CharField(max_length=250) class SubModule(Module): description = models.CharField(max_length=250) I removed the id field in Module since its a clash and after running makemigrations and adding default value to it , i edited the migrations file as follows: # Generated by Django 3.0.6 on 2020-08-14 06:03 from django.db import migrations, models import django.db.models.deletion from django.utils import timezone def switch_to_share_item(apps, schema_editor): """ From non inehirtance to post inheritance """ OldModule = apps.get_model('Module', 'OldModule') NewModule = apps.get_model('Module', 'NewModule') for module in OldModule.objects.all(): new_module = NewModule.objects.create(name=module.name, identifier=module.identifier, description=module.description, keywords=module.keywords, duration=module.duration, pass_score=module.pass_score, created_on=module.created_on, created_by=module.created_by, progress_shared=module.progress_shared, attached_to_course=module.attached_to_course ) module.delete() def switch_to_module(apps, schema_editor): """ Rollback """ OldModule = apps.get_model('Module', 'OldModule') NewModule = apps.get_model('Module', 'NewModule') for module in NewModule.objects.all(): new_module = OldModule.objects.create(name=module.name, identifier=module.identifier, description=module.description, keywords=module.keywords, duration=module.duration, pass_score=module.pass_score, created_on=module.created_on, created_by=module.created_by, progress_shared=module.progress_shared, attached_to_course=module.attached_to_course ) module.delete() class Migration(migrations.Migration): dependencies = [ ('els', '0001_initial'), ] operations = [ migrations.RenameModel('Module', 'OldModule'), migrations.CreateModel( name='NewModule', fields=[ ('tenantshareitem_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, … -
How to update data in django rest framework
I have a cart model and I want in API which if the user the add same items two times in cart the cart will automatically increase the quantity of service. In my case, if I add the same item twice it creates another cart instead of updating the previous one. I search for it a lot but I don't get an answer. I tried a lot to do this. If somebody is capable of giving answer then please give an answer , please Here is my code:- views.py class CartViewSet(viewsets.ModelViewSet): serializer_class = CartSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return Cart.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() filter_backends = [DjangoFilterBackend] filterset_fields = ['date_created', 'user'] @action(detail=False) def count(self, request): queryset = self.filter_queryset(self.get_queryset()) count = queryset.count() content = {'count': count} return Response(content) serializers.py class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ['id','url', 'user', 'service', 'defects', 'date_created', 'quantity' , 'price', 'total'] models.py class Cart(models.Model): user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=1) service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL) defects = models.ForeignKey('Defects',null=True, on_delete=models.SET_NULL) price = models.IntegerField(default=False) date_created = models.DateTimeField(auto_now_add=True) total = models.IntegerField(blank=True, null=True) def __str__(self): return self.user.username -
Django full_clean() command problem.(Can't raise the validationError)
I have a problem with using full_clean() command in a views.py file. I write the file name by using #. There are no errors of import or function(validtion). The only problem I got is the full_clean() command. If I put an email data by json like qwertygmail.com and it should raise the ValidationError but it doesn't. Thx for reading my problem. views.py import json, bcrypt, jwt from django.db import IntegrityError from django.views import View from django.http import HttpResponse, JsonResponse from .models import User from instagram.settings import SECRET_KEY from .validation import ValidationError class SignUpView(View): def post(self, request): payload = json.loads(request.body) name = payload.get('name', None) email = payload.get('email', None) password = payload.get('password', None) if User.objects.filter(name = name).exists(): return JsonResponse( {'message':'Name_Already_Exists'}, status = 400 ) if User.objects.filter(email = email).exists(): return JsonResponse( {'message':'Email_Alreday_Exists'}, status = 400 ) try: user = User( name = name, email = email, password = password ) user.full_clean() user.password = bcrypt.hashpw( user.password.encode('utf-8'), bcrypt.gensalt() ) user.password = user.password.decode('utf-8') user.save() return HttpResponse(status = 200) except ValidationError: JsonResponse( {'message':'INVALID_ERROR'}, status = 400 ) models.py from django.db import models from .validation import email_valid, password_valid class User(models.Model): name = models.CharField( max_length = 50, ) email = models.CharField( max_length = 50, validators = [email_valid] ) password … -
How can I use or override the WriteView in django-postman to send an email through django?
According to the documentation (see docs), you can supersede the default view to return to, i.e. by passing in a success url in the urlpatterns. The problem, however, is that I would like to you use the built-in WriteView so that every time a message is submitted I can use the send_email() function from django to send an email. One solution that I have tried is to send a mail in a context processor, meaning that every time a user navigates to a page I look if there has been a message sent recently, and together with a stored session key, can see if I should send an email or not. This seems to create a lot of overhead, and if someone were to submit multiple times before a page is done refreshing (hence the session key has not registered yet), a user would receive multiple emails. Does anyone know of a way to do this? I would appreciate any help I can get. -
SQLite Database not connected in Django Heroku
So i was trying to deploy my project to Heroku and i followed this steps : https://www.codementor.io/@jamesezechukwu/how-to-deploy-django-app-on-heroku-dtsee04d4 . The build was successfull and i was able to run the server : https://pcbuildingparts.herokuapp.com/ but the database doesn't seem to connect beacause the items from database doesn't show at all and i tried to login in my admin site with my superuser account before deploying, but it doesn't let me in. This is my settings.py """ Django settings for dss_project project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5u53+p4k-_=70wwg-igg7_5r9!5vh-c6@@hcl&**(e6fod8d(a' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['pcbuildingparts.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'blog', 'accounts', 'sim', 'dss', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'dss_project.urls' TEMPLATES … -
How to increase the timeout on AWS Elastic Beanstalk?
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I need to get .igs file in one of my forms and save it to S3 Bucket but I was getting 413 Request Entity Too Large error. Then I have created a folder into .platform/nginx/conf.d which it's name is size.conf such as below. size.conf; client_body_buffer_size 100M; client_max_body_size 50M; Then I have started to getting 502 Bad Gateway error. Then I have added another .conf file to the conf.d folder as below. timeout.conf; keepalive_timeout 600; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; fastcgi_send_timeout 600; fastcgi_read_timeout 600; But I'm still getting the same error. In my web.stdout.log; [CRITICAL] WORKER TIMEOUT (pid:8319) [INFO] Booting worker with pid: 9095 Bad Request: /api/jsonws/invoke numexpr.utils - INFO - NumExpr defaulting to 2 threads. and in my nginx error log; *189 upstream prematurely closed connection while reading response header from upstream *199 an upstream response is buffered to a temporary file How can I fix this issue? -
Django Loop returning one row
I have encountered this challenge but i can really seem to get any step. I want to populate all objects(Student) with all related Results,but i can only get the last related row after looping. merits list page: its it returning details of Junior githambo for all objects. Models class Result(models.Model): grade=models.TextField(max_length=5) marks=models.DecimalField(max_digits=5,decimal_places=2) subject=models.ForeignKey( to='Subject', on_delete=models.CASCADE ) student=models.ForeignKey( to='Student', on_delete=models.CASCADE ) def __str__(self): return '{} {} {}'.format(self.student,self.subject,self.marks) class Student(models.Model): f_name=models.TextField(max_length=100) s_name=models.TextField(max_length=100) surname=models.TextField(max_length=100) reg_number=models.TextField(max_length=100) photo=models.ImageField(upload_to='student_image') next_of_kin=models.ForeignKey( to='Parent', on_delete=models.CASCADE ) student_form=models.ForeignKey( to='Class', on_delete=models.CASCADE ) def get_absolute_url(self): return reverse('student:student-detail',kwargs={'pk':self.id}) def __str__(self): return '{} {} {}'.format(self.s_name,self.surname,self.f_name) Views def student_merit_list(request): template_name='student/merit.html' all_student=Student.objects.all() for s in all_student: results=Result.objects.filter(student=s.id) total=results.aggregate(Sum('marks'))['marks__sum'] mean_score=total/results.aggregate(Count('marks'))['marks__count'] mean_grade=get_mean_grade(mean_score) context={'s':s,'all_student':all_student,'results':results,'total':total,'mean_score':mean_score,'mean_grade':mean_grade} return render(request,template_name,context) -
How to increase the performance in map function using python?
I analyzed lot of documentation. which is the best performance using loop and map. The number of documentation are given map function is the best performance. but I tried to convert my code loop to the map and I checked execution time for both. Loop execution time is 45 seconds and the map it's showing around two minutes. How to increase my performance. For Loop Code d1 = Sample.object.all()[:30] country='api' state='api1' places = [] for i in d1: id = i.id name = i.name age = i.age country=country state = state try: sp = sample_place.object.filter(id=id) except: sp = sample_place(id=id, name=name, age=age, country=country, state=state) sp.save() place = {'id':id,'name':name,'age':age, 'country':country, 'state':state} places.append(place) return places Map Code import functools def sample_method(p,country,state): id = i.id name = i.name age = i.age country=country state = state try: sp = sample_place.object.filter(id=id) except: sp = sample_place(id=id, name=name, age=age, country=country, state=state) sp.save() place = {'id':id,'name':name,'age':age, 'country':country, 'state':state} return place pois = Sample.object.all()[:30] places = list(map(functools.partial(sample_method,country=country,state=state), pois)) Execution Time For Loop, Execution Time is 45 seconds Map function Execution Time is One Minute How to reduce the time -
Django testcase fails when running entire suit
I have 2 test classes as shown below: class AdminSiteTest(UserMixin, TestCase): def setUp(self): super().setUp() self.user = self.create_superuser() self.login_user() def test_default_admin(self): with self.settings(ROOT_URLCONF='tests.urls_admin'): print('AdminSiteTest') response = self.client.get('/admin/') self.assertEqual(response.status_code, 200) class OTPAdminSiteTest(UserMixin, TestCase): def setUp(self): super().setUp() self.user = self.create_superuser() self.login_user() def test_otp_admin_without_otp(self): """ if user has admin permissions (is_staff and is_active) but doesnt have OTP setup, redirect the user to OTP setup page """ with self.settings(ROOT_URLCONF='tests.urls_otp_admin'): response2 = self.client.get('/otp_admin/', follow=True) redirect_to = reverse('two_factor:setup') self.assertRedirects(response2, redirect_to) Following runs successfully: make test TARGET=tests.test_admin.OTPAdminSiteTest make test TARGET=tests.test_admin.AdminSiteTest Following gives error: make test TARGET=tests.test_admin Detailed Error: DJANGO_SETTINGS_MODULE=tests.settings PYTHONPATH=. \ django-admin.py test tests.test_admin.* System check identified some issues: WARNINGS: ?: (admin.W411) 'django.template.context_processors.request' must be enabled in DjangoTemplates (TEMPLATES) in order to use the admin navigation sidebar. System check identified 1 issue (0 silenced). E ====================================================================== ERROR: * (unittest.loader._FailedTest) ---------------------------------------------------------------------- AttributeError: module 'tests.test_admin' has no attribute '*' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Makefile:17: recipe for target 'test' failed make: *** [test] Error 1 (venv) aseem@Aseem-asus:~/Code/django-two-factor-auth-fork$ make test TARGET=tests.test_admin DJANGO_SETTINGS_MODULE=tests.settings PYTHONPATH=. \ django-admin.py test tests.test_admin Creating test database for alias 'default'... System check identified some issues: WARNINGS: ?: (admin.W411) 'django.template.context_processors.request' must be enabled in DjangoTemplates (TEMPLATES) in order to use the admin navigation sidebar. System check … -
how to join return value from serializer in django with the customise result? using python 3.4
if request.method == 'GET': apk_format = {} address = Address.objects.all() addressserializer = AddressSerializer(address, many=True) asd = addressserializer.data Municipal = MunicipalCouncil.objects.all() Municipalserializer = MunicipalCouncilSerializer(Municipal, many=True) ms = Municipalserializer.data j = asd + ms apk_format['status'] = status.HTTP_200_OK apk_format['success'] = True #apk_format['data'] = Municipalserializer.data #apk_format['data1'] = addressserializer.data apk_format['perfect_data'] = j apk_format['message'] = 'success' return Response(apk_format) The result i get like this { "id": 4, "address_line1": "xxxxxx", "address_line2": "yyyyyy", "province_id": 1, "district_id": 1, "city_id": 1, "postcode": "000000" }, { "id": 5, "address_line1": "xxxxx", "address_line2": "yyyyy", "province_id": 1, "district_id": 1, "city_id": 1, "postcode": "00000" }, { "id": 1, "user_id": 1, "council_name": "xxxxx", "email": "xxxxx@gmail.com", "country_code": "000000", "phone_number": "000000000", "designation_id": 1, "provincedetails_id": 2 }, { "id": 2, "user_id": 1, "council_name": "xxxxx", "email": "xxxxx@gmail.com", "country_code": "00000", "phone_number": "000000000", "designation_id": 1, "provincedetails_id": 2 } But How to get result like this in python 3.4. below i need to write logic from i will take id from one table and stored the variable in another table so i can fetch the record according to that for more example look at once post method. { "id": 4, "address_line1": "xxxxxx", "address_line2": "yyyyyy", "province_id": 1, "district_id": 1, "city_id": 1, "postcode": "000000" "id": 2, "user_id": 1, "council_name": "xxxxx", "email": "xxxxx@gmail.com", "country_code": "00000", "phone_number": … -
Getting Error After adding Django ManyToMany Relationship for existing model
I had three models called ColorTemplate, Colors, TemplateColors like below. class ColorTemplate(BaseModel): """ Color template model """ template_name = models.CharField(default="New Color Pallet", max_length=45) color = models.ManyToManyField('Colors', related_name='color_mapping') class Meta: db_table = "ColorTemplate" class Colors(BaseModel): """ Model for colors """ color_code = models.CharField(default=None, max_length=45) class Meta: db_table = "Colors" class TemplateColors(BaseModel): """ Relationship model for color template and Colors """ color_template = models.ForeignKey(ColorTemplate, on_delete=models.CASCADE, null=True, related_name="color_template_mapping" ) color = models.ForeignKey(Colors, on_delete=models.CASCADE, null=True, related_name='color_mapping') class Meta: db_table = "TemplateColors" class VisualColors(BaseModel): """ Model for added colors that are related with Report Visuals """ report_visual = models.ForeignKey(ReportVisuals, null=True, on_delete=models.CASCADE, related_name='visual_mapping_color') color = models.ForeignKey(Colors, null=True, on_delete=models.SET_NULL, related_name='color_mapping_visual') value = models.CharField(default=None, max_length=45, null=True) class Meta: db_table = "VisualColors" Both Colors model and ColorTemplate had OneToMany relationships with Template Color model. So I wanted to add a ManyToMany relationship between the ColorTemplate model and Colors Model. So I removed the TemplateColors model and Changed the code like below. class Colors(BaseModel): """ Model for colors """ color_code = models.CharField(default=None, max_length=45) class Meta: db_table = "Colors" # class TemplateColors(BaseModel): # """ Relationship model for color template and # Colors """ # color_template = models.ForeignKey(ColorTemplate, # on_delete=models.CASCADE, # null=True, # related_name="color_template_mapping" # ) # color = models.ForeignKey(Colors, on_delete=models.CASCADE, null=True, … -
Set Timezone to 00:00, datetime.now() but only date [duplicate]
My code: import pytz from datetime import datetime, timedelta timezone = pytz.timezone('Europe/London') dt_now = datetime.now(timezone) today = datetime(dt_now.year, dt_now.month, dt_now.day, tzinfo=timezone) print(today) The result is = 2020-08-14 00:00:00-00:01 Expected: 2020-08-14 00:00:00-00:00 TY -
Django decorator that gets the request argument with additional kwargs
I have written a custom decorator that checks the sessions and if it is None, the user has to be redirected to another page or just return a json response. The decorator works but when I add parameters, it fails. I want to add kwargs. def company_required(function): def decorator(request, *args, **kwargs): print(kwargs.get('return_json')) #can't do that if not request.session.get('company_id'): redirect('/login') return function(request, *args, **kwargs) return decorator @company_required(return_json=True) #without params, it works. def home_page(request): return -
How to use annotate() along with F() expression with RawSQL in Django ORM?
I have a queryset which contains a column called visit_id. This visit_id has a one to many relation to other table called shifts which contain a boolean column called is_lead. How do I use annotate() to assign a key called shift_id to the existing queryset using RawSQL where the shift_id comes from different query - select id from shifts where visit_id=F('visit_id') and is_lead is true? I need to assign two such columns from shifts table - shift_id and shift_reported_date. Using Django 1.11 -
Django SessionAuthentication deletes older session entries from database when user login with new session
Django Version: Django 2.2 Python Version: 3.6 Calling any Authenticated API from the device with the older session has a query below, which is not intentional as per application logic, this automatically prevents users from multiple device login, but I want to allow our users to create multiple sessions across the devices. Any idea about this behaviour in the Session Authorization class in Django? as per my investigation docs says that, multi sessions are allowed by default, but that's not the case for me. DELETE FROM django_session WHERE django_session.session_key IN ('<session_key>') /usr/local/bin/gunicorn in <module>(8) sys.exit(run()) /usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py in run(61) WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() /usr/local/lib/python3.6/site-packages/gunicorn/app/base.py in run(223) super(Application, self).run() /usr/local/lib/python3.6/site-packages/gunicorn/app/base.py in run(72) Arbiter(self).run() /usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py in run(212) self.manage_workers() /usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py in manage_workers(545) self.spawn_workers() /usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py in spawn_workers(616) self.spawn_worker() /usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py in spawn_worker(583) worker.init_process() /usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py in init_process(134) self.run() /usr/local/lib/python3.6/site-packages/gunicorn/workers/sync.py in run(124) self.run_for_one(timeout) /usr/local/lib/python3.6/site-packages/gunicorn/workers/sync.py in run_for_one(68) self.accept(listener) /usr/local/lib/python3.6/site-packages/gunicorn/workers/sync.py in accept(30) self.handle(listener, client, addr) /usr/local/lib/python3.6/site-packages/gunicorn/workers/sync.py in handle(135) self.handle_request(listener, req, client, addr) /usr/local/lib/python3.6/site-packages/gunicorn/workers/sync.py in handle_request(176) respiter = self.wsgi(environ, resp.start_response) /usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py in sentry_patched_wsgi_handler(99) environ, start_response /usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/wsgi.py in __call__(89) rv = self.app(environ, start_response) /usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py in <lambda>(98) return SentryWsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw))( /usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py in sentry_patched_get_response(119) return old_get_response(self, request) /test/moreable/middlewares.py in __call__(10) response = self.get_response(request) /usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py in wrapped_view(54) return view_func(*args, **kwargs) /usr/local/lib/python3.6/site-packages/django/views/generic/base.py in … -
how can i fixed cors policy in Django?
my settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', .... 'django_filters', 'corsheaders', .... ] MIDDLEWARE = [ .... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', .... ] CORS_ORIGIN_ALLOW_ALL = True But i'm still blocked CORS. Server infra architectures is AWS Lambda, API Gateway, Django REST Framework. i cant find this cause. -
How to change direction of django admin interface?
I am making a django application in arabic and I would like the interface to be from right to left. How can I make it happen? -
Change Database schema and migrate Models
I had two models Item and Module separately Polymorphic Models: from polymorphic.models import PolymorphicModel Class Item(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Module(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) description = models.TextField() I want to change the database schema without causing any problems with the existing data in database: Change needed: Class Item(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Module(Item): description = models.TextField() As in code above, i want to inherit the Module table from Item table. I removed the uuid field since it clashes. Now i want to make my existing data safe .I am trying to run a management command which creates items first from the module Id. Any way i can achieve my target or is there any better way to do this? What i have tried: First i run a management command which loops through all modules and create tenant share items with exact same Ids. Now im trying to change the db and it asks how to popupulate existing rows -
How to properly add a wsgi application to an existing static website without specifying a WSGIScriptAlias in Apache?
I've got a situation where I have an existing static website that I am trying to add a Django application too. The django application itself is one django project but contains two distinct, unrelated components that I want to list at different URLs and not have them be under the same subURL. So what I have now is a static HTML website at example.com/index.html and a Django application with an app based at /foo and another at /bar and I would like these to live at example.com/foo and example.com/bar respectively. However, I can't figure out how to make this happen. It seems that I need to set the WSGIScriptAlias but I'm not sure how to do that without the WSGIScriptAlias to something like /p giving me something like example.com/p/bar and example.com/p/foo. I know that I could set it to / and I tried that, which gives me the desired URLs for the django application but breaks the static site. If I do this, the redirect to index.html no longer works (because the django application doesn't contain an index.html) and all the other links no longer work (I assume because all urls are being redirected to /?) but I assume there … -
Can someone explain me how to fix this issue with a django stock app?
So I'm creating a stock blog in django and I have the following problem, the thing is that when I want to create a post, I want it to automatically select the symbol from the str: parameter it was in the link before, for example, I'll demonstrate with images what I want to do: There in the link, it says microsoft, and when I click on add post, I automatically want to fill in microsoft, and I want to automatically fill this with msft, which is in the database. Here's the code if you can give me any ideas I'll show the post parts: views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) urls.py (the third one is the one for … -
Not able to use a Model Property in html template
I am making a E-commerce app for electronics and I Have made separate models for each category. So at the cart page I am not able to sum the total value of the items. I got this error AttributeError at /cart/ 'NoneType' object has no attribute 'price' Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.0.7 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'price' Exception Location: D:\WebDev\my_projects\techcastle\store\models.py in get_laptop_total, line 123 Python Executable: D:\WebDev\my_projects\env\Scripts\python.exe Python Version: 3.8.0 My Model : - class Mobile(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False,null=True,blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Laptop(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False,null=True,blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Accessories(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False,null=True,blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date_ordered = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200) def __str__(self): return str(self.id) @property def … -
How does node + express compete with full fledged framework of python + Django?
I tend to find building with python(Django) easier than with node (express) since there's so many things that need to be added and configured with NPM. My concern is with building a backend that clients can use to inject content into the frontend. Since Django comes well equipped, how can I achieve that interface with node and it's web framework? What do you advice?