Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fail to deploy project to Google Cloud App Engine Standard
I have a project that has been running fine, but I want to make some changes and solve some bugs so I tried to deploy my app using the Google Cloud SDK (gcloud app deploy) Services to deploy: descriptor: [/home/projects/Myproject/app.yaml] source: [/home/projects/Myproject/] target project: [my-project] target service: [default] target version: [20200902t153320] target url: [https://my-project.uc.r.appspot.com] Do you want to continue (Y/n)? Beginning deployment of service [default]... ╔════════════════════════════════════════════════════════════╗ ╠═ Uploading 2 files to Google Cloud Storage ═╣ ╚════════════════════════════════════════════════════════════╝ File upload done. Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build 3ebf37fb-b18d-4c68-b352d-10bd8758f90b0 status: FAILURE Error type: OK Full build logs: https://console.cloud.google.com/cloud-build/builds/3ebf37fb-b18d-4c68-b32d-10bd8s78f90b0?project=my-projectid This used to work yesterday fine but now it gives me this error and I cannot make any changes: ERROR: build step 6 "us.gcr.io/gae-runtimes/buildpacks/python38/builder:python38_20200816_3_8_5_RC01" failed: step exited with non-zero status: 246 ERROR Finished Step #6 - "exporter" Step #6 - "exporter": ERROR: failed to export: failed to write image to the following tags: [us.gcr.io/my-project/app-engine-tmp/app/ttl-2h/default/buildpack-app:latest: GET https://us.gcr.io/v2/token?scope=repository%3Amy-project%2Fapp-engine-tmp%2Fapp%2Fttl-2h%2Fdefault%2Fbuildpack-app%3Apush%2Cpull&scope=repository%3Agae-runtimes%2Fbuildpacks%2Fpython38%2Frun%3Apull&service=us.gcr.io: DENIED: Token exchange failed for project 'my-project'. Access denied.] Step #6 - "exporter": *** Digest: sha256:bd8121f23cb362683e7c32a8bbdf2a900606373f8edfsdf36fe0ffb17014 Step #6 - "exporter": Step #6 - "exporter": us.gcr.io/my-project/app-engine-tmp/app/ttl-2h/default/buildpack-app:latest - GET https://us.gcr.io/v2/token?scope=repository%3Amy-project%2Fapp-engine-tmp%2Fapp%2Fttl-2h%2Fdefault%2Fbuildpack-app%3Apush%2Cpull&scope=repository%3Agae-runtimes%2Fbuildpacks%2Fpython38%2Frun%3Apull&service=us.gcr.io: DENIED: Token exchange failed for project 'my-project'. Access denied. Step #6 - "exporter": *** Images (sha256:bd8121f23cb362683e7c32adfssd73f8ea51326f36fe0ffb17014): I … -
I have a problem in integrating RASA chatbot with Django
After running the django and RASA server i'm getting these errors,somebody please help me to sort out this error -
Celery Worker Can't Find Template in Production
I have a task which gets run ever time a user gets created. The task is to send an email to a user. In that task, I have a line template = get_template('account/user_creation.html', using='post_office') to get a template for the email. The task was successfully executed when I ran it in development on my computer, but it's not the case when I deployed it to Elastic Beanstalk for production. The template is located in proj/templates/account/user_creation.html. The task is located in proj/account/tasks.py The error is as follow: [2020-09-02 12:51:01,196: ERROR/ForkPoolWorker-1] Task account.tasks.send_user_email_when_user_created_by_admin[3247eb86-ddf3-4b06-8e20-fe6c57329cff] raised unexpected: TemplateDoesNotExist('account/user_creation.html') Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) File "/var/app/staging/account/tasks.py", line 131, in send_user_email_when_user_created_by_admin File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: account/user_creation.html In settings.py 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', ], }, }, { # for post office 'BACKEND': 'post_office.template.backends.post_office.PostOfficeTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.request', ] } } ] -
airflow: django / logging
We're trying to use airflow with a custom django project and followed the advice of this answer (Django) ORM in airflow - is it possible? . When we implemented it on airflow v1.10.11, our tasks would always fail at the part of django setup where it reconfigures logging based on django settings. The error that we would get back looked like: [2020-09-02 18:54:29,344] {local_task_job.py:102} INFO - Task exited with return code Negsignal.SIGKILL Does anyone have any ideas on why / how airflow is detecting changes to the logging configuration and then killing the task? -
How to sort a query based on another model in Django
If I had: class Assets(models.Model): assetMake = models.CharField(max_length=50,blank=True,) assetModel = models.CharField(max_length=50,blank=True,) class Maintenance(models.Model): assetID = models.ForeignKey(Assets, on_delete=models.CASCADE) dateRequested = models.DateTimeField(null=True, blank=True) dateCompleted = models.DateTimeField(null=True, blank=True) complete = models.BooleanField(default = False) I want to list all of the assets on a view, and sort them by the last time they were maintained (dateCompleted). I have been trying to get this working below, but I feel like there is much easier way of accomplishing this, Any help is appreciated class MaintenanceAgeList(LoginRequiredMixin,TemplateView): template_name = 'maintenance_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) maintenanceList = [] assets = Assets.objects.filter(retire = False) today = timezone.now().date() for asset in assets: maintenance = Maintenance.objects.filter(assetID_id = asset.id, complete =True,).order_by('-dateCompleted') if maintenance.count() > 0: asset['maintDate'] = (maintenance[0].dateCompleted).date() maintenanceList.append(asset) asset['days'] = (today - lastMaintenance[0].dateCompleted.date()).days else: asset['maintDate'] = today - timedelta(days=365) asset['days'] = 365 maintenanceList.append(asset) maintenanceList = maintenanceList.sort(key=lambda r: r.maintDate) context['items'] = maintenanceList return context -
How to use cleaned_data before form validation condition?
I wanted to use cleaned_data['username'] before form.is_valid() condition as shown in the code. I want to get the value from Django form field and check in database if the username exist or not. But its giving me error " Form object has no attribute cleaned_data" how should I solve this or is there any other way to get value from Django form? view.py def RegistrationView(request): form=Registration_Form() if request.method=='POST': print("In Post") form=Registration_Form(request.POST) username=form.cleaned_data['username'] print(username) if form.is_valid(): form.save() return redirect('login_view') else: # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) model.py class User_Registration(models.Model): company_name=models.CharField(max_length=250,blank=False) username=models.CharField(max_length=10,primary_key=True,unique=True,blank=False) password=models.CharField(max_length=10,unique=True,blank=False) email=models.EmailField(max_length=250,blank=False) forms.py class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } -
How to change/ insert the djnago finite state machines on fly from terminal window
I have below a.py djnago finite state machine program: from django.db import models from django_fsm import transition, FSMIntegerField from django_fsm import FSMField, transition import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command class Order(models.Model): STATUS_GO = 0 STATUS_COME =1 STATUS_CHOICES = ( (STATUS_GO, 'GO'), (STATUS_COME,'come') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_GO, protected=True) @transition(field=status, source=. [STATUS_GO], target=STATUS_COME) def walk(self): print("Target moved") I would run above program as : Press F5. >>> State= order() >>> State.walk # input >>> Target moved # output I would like understand by any chance, do djnago /python provide opportunities to insert STATES like ( STATUS_HOLD, STATUS_JUMP) from terminal window, in addition to already available. So that these news get positioned in programs. Any possibility. Thanks. -
Is the OS the reason this Django docker file fails to build?
Getting on boarded onto a project that says it's built with Linux, Python 2.7 and Bash. My work computer only has mac os installed and I'm trying to build this container without having to install Linux but I might have to. Everything is working as intended until I reach this error: Step 28/31 : RUN export COLLECTSTATIC=local && python manage.py collectstatic --settings=settings.{__SETTINGS__} --link --no-input ---> Running in 874e3c95b9b9 Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named {__SETTINGS__} ERROR: Service 'primatest_4' failed to build: The command '/bin/sh -c export COLLECTSTATIC=local && python manage.py collectstatic --settings=settings.{__SETTINGS__} --link --no-input' returned a non-zero code: 1 Since I have 0 domain knowledge of this problem I'm having a hard time diagnosing this error. Dockerfile.python27 ########################## # WARNING: {__WARNING__} FROM python:2.7 ############################################################################### # Update base container install ############################################################################### RUN if [ ! -d "/app/prima" ]; then mkdir -p /app/prima; fi WORKDIR /app/prima/ … -
Django: SSL + trailing slash cause URL in browser to show unusual path
Hosting: A2Hosting Reference for A2Hosting deploy: link Python: 3.8.1 Django: 3.1.1 Webserver: Apache When "SECURE_SSL_REDIRECT = False" in settings.py, having the trailing slash in the urls.py paths causes no issue. urlpatterns = [ path('admin/', admin.site.urls), path('login/', dashboard, name="dashboard"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In fact, accessing the URL http://subdomain.domain.com/login (or admin) the correct page is shown. But when I set "SECURE_SSL_REDIRECT = True", if I maintain the trailing slash and I access the same URLs, the page is still correctly shown, but the URL in the browser address bar changes. Instead to be: https://subdomain.domain.com/login it becomes: https://subdomain.domain.com/home/user/a2hosting_python_app/login/ For admin path, instead to be: https://subdomain.domain.com/admin/login/?next=/admin/ it becomes: https://subdomain.domain.com/home/user/a2hosting_python_app/admin/login/?next=/home/user/a2hosting_python_app/admin/ At this point, if I edit the urls.py removing the trailing slash: urlpatterns = [ path('admin', admin.site.urls), path('login', dashboard, name="dashboard"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) the login URL shows correctly, but the admin URL won't. I have no APPENDING_SLASH set in settings.py. Does anyone know why Django behave like this? What am I doing wrong? Many thanks in advance. -
Django Timezone filter returns wrong results
I wrote the following code: date = self.request.query_params.get('date') queryset = Fixture.objects.all().order_by('-date') if(date): date = pytz.utc.localize(datetime.strptime(date, "%Y-%m-%d")).astimezone(pytz.UTC) queryset = Fixture.objects.filter(date__date=date).order_by('date') Upon excuting this with date = "2020-09-02" the queryset returns values containing the date "2020-09-03". How come this happens and how can this be solved? -
How to validate plain HTML form fields in djano
I am a laravel developer and I am new to django. Everything went well in django until I started exploring forms. I want to use plain HTML forms and validate it using django forms validation but I am not getting proper reference or tutorial for doing so. I want some examples or help for validating plain HTML form fields in django. -
counting distinct values within a distinct value search on another field within same jango model
I am trying to pull some analytics from my django model table. So far I can count total values of a field and distinct values of a field. I also know how to create lists showing total values of fields within a distinct field. Now i'd like to count the distinct instances a field occurs within a list of already distinct values of a different field. Here's the table I am working with: | uid | cid | |-------|--------| | a | apple | | a | apple | | a | grape | | b | apple | | b | grape | | c | apple | | c | pear | | c | pear | | c | pear | So the result I am trying to provide is: cid: apple (distinct uid count: 3), cid: grape (distinct uid count: 2), cid: pear (distinct uid count: 1) and also: cid apple's distinct uid's: a, b, c cid grape's distinct uid's: a, b cid pear's distinct uid's: c So far I have been able to get distinct counts and lists like this: dist_uid_list = Fruit.objects.filter(client=user).values('uid').distinct() output >>> {'uid': 'a', 'uid': 'b', 'uid': 'c'} and this: dist_uid_count = … -
Accessing Windows located Firebird Database from Docker contained Django App
I am trying to access Firebird Database files located in C:/ drive from Docker Contained Django Application. I am using Python fdb package for accessing this. self.conn = fdb.connect( host='192.168.0.108', port=3050, database='/FIREBIRD_DB/TEST.FDB', user=usr, password=pswd) It generates error: Exception: The location of Firebird Client Library could not be determined. How can I access the machine's Firebird Database from Docker Contained Django app? -
MEDIA URL not loading on heroku gives 404
Hello my media files are not loading on heroku please correct me if i am wrong. i have used the following in the following files: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp.apps.MainappConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'jobhunter/static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In urls.py i included the media root urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) on posts.html i wrote the below line: <img class="card-img-top" src="{{ MEDIA_URL }}{{ t.post_featured_image }}" alt="Card image"> Everything is working on local server but not on heroku. please tell me if i am missing something. -
Django Admin Dashboard showing incorrectly
When I open my Django Dashboard everything looks fine. But, when I click of the tables... This appears! I have no idea of what just happened. I'm still on project development so I don't mind loosing my current database. I literally have no idea of what just happened. -
NoReverseMatch at /homeProva1/group/new/ Reverse for 'calendar' not found. 'calendar' is not a valid view function or pattern name
I've this error but i've not "calendar" when i create a CalendarGroups: NoReverseMatch at /homeProva1/group/new/ Reverse for 'calendar' not found. 'calendar' is not a valid view function or pattern name. I've this error also when i create new Event and new Calendar. In urls: path('homeProva1/', views.CalendarGroupList.as_view(), name='home'), #LISTA EDIFICI OK path('homeProva1/<int:pk>/calendars/', views.CalendarsOfGroupList.as_view()), #LISTA CALENDARI DI QUEL PK EDIFICIO OK path('homeProva1/<int:pk>/calendars/<int:pk1>/events/', views.EventsOfCalendarList.as_view()), #LISTA EVENTI DI QUEL PK CALENDARIO OK url('homeProva1/(?P<group_id>\d+)/calendars/(?P<calendar_id>\d+)/events/calendar/$', views.CalendarView.as_view(), name='calendar_view'), #CALENDARIO OK path('homeProva1/group/new/', views.group, name='group_newprova1'), #NUOVO GRUPPO OK path('homeProva1/<int:pk>/calendars/new/', views.calendarCreate, name='calendar_newprova1'), #NUOVO CALENDARIO OK path('homeProva1/<int:pk>/calendars/<int:pk1>/events/new/', views.event, name='event_newprova1'), #NUOVO EVENTO OK In views.py: @login_required def event(request, pk=None ,pk1=None): instance = Event() instance = Event(calendar_id=pk1) form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) @login_required def group(request): instance = CalendarGroups() form = CalendarGroupsForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) @login_required def calendarCreate(request, pk=None): instance = Calendar() #instance = Calendar() instance = Calendar(group_id=pk) form = CalendarForm(request.POST or None, instance=instance) #print (form['group']) if request.POST and form.is_valid(): #form['group'] = form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) In models: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True, unique=True) def __str__(self): #self.name = name return str(self.name) … -
Django System complete !What Next on deployment
This might seen a cliche question to senior developers.There are number of ways to deploy the django appalication online,AWS,heroku etc.But i want the best solution to deploy a app to be used by a small organization approximately 10 users!. I will appreciate any lead/information regading on this.I have reseached by i need solutions for engineers dealing with such activities.Thanks in advance. regards -
Python Django uses wrong query
I have a problem, to solve it I tried going into the shell but I couldn't find out the solution so I hope that you can help me. I'm importing my Model Images which contains an id and the image URL but I can't get it because of this error. The code: from recipes_database.models import Images Images.objects.all() And here the error: Traceback (most recent call last): File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: Images.id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 263, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1154, in execute_sql cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\utils.py", line … -
Msgid in django not being recognized when it starts with percent symbol
Any msgid's that are created for translation do not seem to be recognized if it starts with %. The msgid and msgstr are created in the django.po file but when the code is run, the message remains untranslated. I am wondering if python-format is trying to recognize the % symbol as a placeholder, but I tried to escape the symbol and that still was not the solution. I am wondering if there is something else I am missing. -
How can I connect multiple models in Django
I`m a beginner in Django and want to create a system in the Django-models were a user can upload a course with a title and different Chapters which all can have multiple videos in them. As seen in this image. I thought about creating three models 1. Course with the course title 2. Chapter which has different videos in them 3. Video And here the video with a title of the video But I have no Idea how to create a connection between those three models, so that there can be multiple chapters in one course and multiple videos in one chapter. These are my first models (I just created them quickly): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class video(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to=user_directory_path) class course(models.Model): title = models.CharField(max_length=100) class chapter(models.Model): pass How should I adjust the models and create the connection to accomplish the system that I´m after? -
How to add labels for Django models.IntegerChoices
I have two IntegerChoices subclasses in one of my django Models that define ticket priorities for an api. I would like when the priority and statuses are rendered on my web page to show the label, but then when using the api to send the integer number corresponding with the label. This is my code so far: class Ticket(models.Model): class Statuses(models.IntegerChoices): OPEN = 2, 'Open' PENDING = 3, 'Pending' RESOLVED = 4, 'Resolved' CLOSED = 5, 'Closed' class Priorities(models.IntegerChoices): LOW = 1, 'Low' MEDIUM = 2, 'Medium' HIGH = 3, 'High' URGENT = 4, 'Urgent' priority = models.IntegerField(default=Priorities.LOW, choices = Priorities.choices) status = models.IntegerField(default=Statuses.OPEN, choices=Statuses.choices) I then try to access the label in my application via <b>Priority: </b> {{ ticket.priority.label }} <br> <b>Status:</b> {{ ticket.status.label }} But nothing shows up. It seems the Django docs for the new IntegerChoices class is very minimal, and is not clear about how the labeling function works. I also tried rendering the labels like so: OPEN = 2, _('Open') But then I got an error saying "name '_' is undefined" Any pointers in the right direction for what I need to do? -
How to Cancel Subscription created thought Checkout Session Stripe API
I have created a recurring product on stripe, and creating a checkout session and it's working fine and creating a subscription for me that i can see on the dashboard. this is my code checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='subscription', line_items=[ { 'quantity': 1, 'price': 'price_1HLDRqCHEV6ur4mXq36yVF1D', } ] ) I want to provide a facility to user that they can cancle their subscription that they have made through checkout session, but it can be cancelled through subscription id only, but i am not getting any subscription id from the checkout session. How can i allow the user to cancle their subscription that they made through checkout session ? -
Django local memory caching not working on heroku
I have a requirement to authenticate user in my django-rest-framework application using SMS based OTP. For these I have created following API endpoint GET \otp - generate and send OTP and store it in cache POST \otp - validate OTP based on value store in cache Here's my code - from django.core.cache import cache # It is used just for debugging & logging purpose local_cache = {} class OTPView(APIView): def get(self, request): serializer = ContactSerializer(data=request.query_params) num = serializer.validated_data.get('contact_number') otp = generate_otp() cache.set(num, otp, 300) local_cache[num] = otp print('GET Cache is : ', local_cache) return Response('OTP Sent') def post(self, request): serializer = OTPSerializer(data=request.data) num = serializer.validated_data.get('contact_number') otp = serializer.validated_data.get('otp') print('POST Cache is : ', local_cache) otp_in_cache = cache.get(num) if otp_in_cache is None: return Response('No OTP or prev expired') elif otp == otp_in_cache: return Response('Success') else: return Response('Incorrect OTP') To persist the OTP across two requests I am using in-memory cache. It is working as expected in my local machine but not when deployed on Heroku. Here are the logs from heroku for reference - 2020-09-02T17:17:22.556785+00:00 app[web.1]: Number is 6666660008 and otp is 541609 2020-09-02T17:17:22.556798+00:00 app[web.1]: GET Cache is : {'6666660008': '541609'} 2020-09-02T17:17:22.558975+00:00 app[web.1]: 10.69.31.173 - - [02/Sep/2020:22:47:22 +0530] "GET /account/api/otp/?contact_number=6666660008 HTTP/1.1" … -
Keyerror in wizard form when passing data to step in Django
I'm new in Django and I'm doing a step form with Form Wizard. I have pass the data through steps but in the last step (step4) return a Keyerror for calling a variable 'categoriaPadre' that is in Step3. Please some help will be great! I attach what I have made: forms.py from django import forms from django.forms import ModelForm from django.utils.safestring import mark_safe from .models import * from .views import * class CustomMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe("<div class='image-option' style='background-image: url('%s');'></div>" % obj.imagen.url) class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("<div class='image-option' style='background-image: url('%s');'></div><div class='name'>%s</div>" % (obj.imagen.url, obj.name)) class PreStep1(forms.Form): name = forms.CharField(max_length=255) class PreStep2(forms.Form): categoriaPadre = CustomChoiceField(queryset=CategoriasPrePadre.objects.all(), widget=forms.RadioSelect) class PreStep3(forms.Form): def __init__(self, *args, **kwargs): c = kwargs['initial']['categoriaPadre'] print(c) self.categoria = CustomChoiceField(queryset=CategoriasPre.objects.filter(categoria_padre=c), widget=forms.RadioSelect) # NEED TO INCLUDE field categoria into "declared_fields"!!! self.declared_fields['categoria']=self.categoria # superclass constructor ought to be called only AFTER # including new field of class into "declared_fields" !!! super(PreStep3, self).__init__(*args, **kwargs) class PreStep4(forms.Form): def __init__(self, *args, **kwargs): c = kwargs['initial']['categoria'] print(c) self.slides = CustomMultipleChoiceField(queryset=Slides.objects.filter(categoria=c), widget=forms.CheckboxSelectMultiple) # NEED TO INCLUDE field categoria into "declared_fields"!!! self.declared_fields['slides']=self.slides # superclass constructor ought to be called only AFTER # including new field of class into "declared_fields" !!! super(PreStep4, self).__init__(*args, **kwargs) Here I create the … -
Method on django model to return the count of a foreign key
I want a method on a django model that returns the count of members in a foreignkey. I'd prefer it to be a class method (and not annotation) because I want to serialize it and send it via javascript without involving templates. Based on previous answers to similar questions, I believed the following sort of structure would work (some attributes deleted for the sake of simplicity): class Post(models.Model): likedby = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True, related_name='liked') def likes(self): return self.likedby_set.count() But when I run this I get AttributeError: 'Post' object has no attribute 'likedby_set'. Anyone know why this doesn't work?