Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration/model created a foreign key field that is not model_id but instead modelID?
I am trying to figure out why I get an error in my app: ProgrammingError at /admin/auth/user/ column programscheduler_proposal.program_id does not exist LINE 1: SELECT "programscheduler_proposal"."id", "programscheduler_p... ^ HINT: Perhaps you meant to reference the column "programscheduler_proposal.programID". Model: class Program(models.Model): programName = models.CharField(max_length=100) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) #should act as blackout constraints class ProposalConstraint(models.Model): objects = models.Manager() proposal = models.ForeignKey("Proposal", on_delete=models.PROTECT) date_time_constraint = models.DateTimeField() note = models.CharField(max_length=200) isPersonal = models.BooleanField(default=False) class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) #scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) scheduler = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_scheduler_related', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_pi_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas contact_information = models.CharField(max_length=200) #might break this out to a complete address? #instrument = models.ForeignKey("Instrument", on_delete=models.PROTECT) instrument = models.ManyToManyField("Instrument") #each program can have many instruments. primary_dis_grating = models.CharField(max_length=20) #is this going to be replaced by FILTER DB? or based on instrument? independent from instrument? secondary_dis_grating = models.CharField(max_length=20, null=True, blank=True) slits = models.CharField(max_length=150) #is this based on instrument? independent of instrument? several options per instrument? filters = models.CharField(max_length=150) #same as above targetofop = models.CharField(max_length =200, null=True, blank=True) #can be blank location = models.CharField(max_length=20) … -
Deleting django form field help_text after errors are shown
I'm trying to delete the password help texts once a form is being re-rendered with errors. For some reason, it keeps recreating the help_text before the form is rendered. from allauth.account.forms import SignupForm, SetPasswordForm # Helper function used to switch the password help texts # So that it appears under the second password instead of the first def switchHelpTexts(form): ### This works ### help_text = form.fields["password1"].help_text form.fields["password1"].help_text = None form.fields["password2"].help_text = help_text ### This works ### # Helper function used to delete the password help texts # when validation errors are displayed. We don't need the same info twice def deleteHelpTexts(form): ### This doesn't work ### form.fields["password1"].help_text = None form.fields["password2"].help_text = None ### This doesn't work ### class MyCustomSignupForm(SignupForm): field_order = ["username", "email", "password1", "password2"] def __init__(self, *args, **kwargs): super(MyCustomSignupForm, self).__init__(*args, **kwargs) switchHelpTexts(self) # # Commented out because deleteHelpTexts doesn't work for some reason # if self.errors and (self.errors.keys() & {"password1", "password2"}): # deleteHelpTexts(self) Even more surprising, if I do this: def deleteHelpTexts(form): form.fields["password1"].help_text = None form.fields["password2"].help_text = "Hello" print(form.fields["password2"].help_text) the console prints "Hello" like it's supposed to, but the form still re-renders with the original helptext instead of "Hello" -
Authenticate returns null always
when i authenticate it returns null and so i cant login even when i have username and password in my database from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from .models import Signups from .forms import SignForm from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import get_object_or_404 from django.http import HttpResponse # Create your views here. def loginpage(request): a=Signups.objects.all() form1 = AuthenticationForm() if request.method == 'POST': form1 = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') print(username,password) user = authenticate(request,username=username, password=password) if user is not None: login(request,user) return redirect('signed', pk=user.pk) else: return HttpResponse("username or password is incorrect") return render(request, 'database/loginpage.html', {'form1': form1}) def frontpage(request): return render(request,'database/frontpage.html') def signup(request): form=SignForm() if request.method=='POST': form = SignForm(request.POST) if form.is_valid(): user=form.save() return redirect("signed",pk=user.pk) return render(request,'database/signup.html',{'form':form}) def signed(request,pk): sign=Signups.objects.get(id=pk) return render(request,'database/signed.html',{'sign':sign}) this is my views.py i want to go to a page where it shows username and password and i have written the code for that and it works but the login form is not taking me there. -
Wagtail 4 Upgrade: 'BlockWidget' object has no attribute '_block_json'
After reading through and updating possible breaking changes stated in the Wagtail changelog, I am getting the following error when viewing any edit menu for any page: 'BlockWidget' object has no attribute '_block_json' Request Method: GET Request URL: https://example.com/admin/pages/530/edit/ Django Version: 3.2.9 Exception Type: AttributeError Exception Value: 'BlockWidget' object has no attribute '_block_json' Exception Location: /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/blocks/base.py, line 526, in block_json Python Executable: /home/user/.virtualenvs_dev/mysite/bin/python3.10 Python Version: 3.10.9 Python Path: ['/home/user/projects/mysite/django', '/home/user/.virtualenvs_dev/mysite/bin', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages', '/home/user/projects/mysite/django/mysite'] Server time: Tue, 17 Oct 2023 11:02:12 -0500 Error during template rendering In template /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/admin/templates/wagtailadmin/panels/object_list.html, error at line 9 'BlockWidget' object has no attribute '_block_json' 1 {% load wagtailadmin_tags %} 2 3 <div class="w-form-width"> 4 {% if self.help_text %} 5 {% help_block status="info" %}{{ self.help_text }}{% endhelp_block %} 6 {% endif %} 7 {% for child, identifier in self.visible_children_with_identifiers %} 8 {% panel id_prefix=self.prefix id=identifier classname=child.classes|join:' ' heading=child.heading heading_size="label" icon=child.icon id_for_label=child.id_for_label is_required=child.is_required %} 9 {% component child %} 10 {% endpanel %} 11 {% endfor %} 12 </div> 13 I've used python poetry in attempt to have all libraries compatible. It builds just fine and the site runs. It is just this specific portion of the site that has to do with the actual Wagtail … -
django orm filter doesn't find the result but I know the result exists
I have a mySql database in server and it has about 5000 rows of data in one table. my model is like this: class Names(models.Model): title = models.CharField(max_length=100) descriptions = models.CharField(max_length=500) is_approved = models.BooleanField(default=False) count_stars = models.FloatField(default=0.0) count_visited = models.FloatField(default=0.0) count_shared = models.FloatField(default=0.0) gender = models.ForeignKey(Genders, on_delete=models.CASCADE) root = models.ForeignKey(Roots, on_delete=models.CASCADE) def __str__(self) -> str: return self.title my mission is to find a specific row in the database by the field of 'title', when the title is in the first tens of rows in the database, everything works good but when the title is in the deeper rows, it can not find it. my view function is: @api_view(["Get"]) def get_name_by_name(request, keyName): value = models.Names.objects.filter(title=keyName).first() serializedValue = serializers.nameSerializer(value) result = serializedValue.data return Response(result) database rows: 1- found 2- found . . n- not found . . 5000. not found what is the problem? I searched about async programming but it didn't work -
Django CustomUser model stores password as plain text
I'm developing django based website. I'm extends auth.user model like below from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name = None last_name = None is_active = models.BooleanField(default=True) is_granted = models.BooleanField(default=False) class Meta: verbose_name = '사용자' verbose_name_plural = '사용자' But I'm in trouble when I create new user data in django site admin. When I create new user, the password doesn't encrypt. I don't want to store password in plain text but hash doesn't work. How should I handle this. -
Python: Django: Cant find a field for some reason in a model
Here is : models.py from django.db import models class identifierModel(models.Model): identifierField = models.CharField(max_length=32, unique=True), ipField = models.CharField(max_length=15), views.py from django.shortcuts import render, HttpResponse from getidentifier.models import identifierModel def commands(request, identifier): if identifier in identifierModel.objects.all(): return HttpResponse("ok") # only for testing is "ok" else: HttpResponse.status_code = 401 return HttpResponse(identifierModel.objects.filter(identifierField=identifier).exists() ) Error: FieldError at /commands/d984b583c27f4b84a7d39b1a3a44c54e/ Cannot resolve keyword 'identifierField' into field. Choices are: id Error from browser I both ran makemigrations and migrate but still its the same thing, i really don't get why it doesent find identifierField, sorry if it was an obvious error i didn't see -
Wagtail 5.1 - Hidding promote tab will stop any user from editing a page
I currently have a wagtail 5.1 project where there's a need to hide the promote tab. I'm hiding the tab like this: from wagtail.admin.panels import ( TabbedInterface, ObjectList, ... ) ... edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='Promote', permission="superuser"), ]) The problem is that, any user besides the wagtail admin cannot save the edited page. A normal user with the group Moderator or Editor (or both) although he is not able to see the tab (what I want) he is not able to save the page because of the required slug in that tab. Is there any workaround or am I stuck with this? Thank you in advance. -
When using django-tinymce, where do I specify referer?
I'm trying to integrate tinyMCE with a django app. I have the following specified in my settings.py: TINYMCE_JS_URL = "https://cdn.tiny.cloud/1/<my api key>/tinymce/6/tinymce.min.js"; tinyMCE does display, but it's giving me the following message: We’re unable to check your domain because the referer header is missing. Please read the Guide on how to ensure your referer header is present, so we can then customize your editor experience. Where do I specify the referer header? I tried putting 'referrer_policy': 'origin', in my TINYMCE_DEFAULT_CONFIG, but I still get the error. -
Django grequests batch call fail
Thank you for willing to see this question. It block me for a long time and try to ask help here. I have 100 api to pin in Django, I tried to use grequests to do batch call, the batch call code looks like this: class BatchCall: def __init__(self, urls, BO_urls): self.urls = urls self.BO_urls = BO_urls def exception(self, request, exception): print("Problem: {}: {}".format(request.url, exception)) def asyncCall_release(self): return grequests.map( (grequests.get(u, auth=HTTPBasicAuth(username, password), verify=False) for u in self.urls), exception_handler=self.exception, size=10) def asyncCall_BO(self): return grequests.map( (grequests.get(u, auth=HTTPBasicAuth(username, password), verify=False) for u in self.BO_urls), exception_handler=self.exception, size=10) test = BatchCall(urls, BO_urls) # here we collect the results returned by the async function results_release = test.asyncCall_release() results_BO = test.asyncCall_BO() When I test all the stuff in Jupyternotebook, everything goes well, it can give me the result. but when I run it in Djgano, I use this to run the app python manage.py runserver The whole app will exit itself in Django after pin 1 batch (10 api) with no reason. *I use Pytharm to run Django InsecureRequestWarning: Unverified HTTPS request is being made to host xxxxx. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings warnings.warn( it will have 10 warning looks like this but it … -
Django Filterset data not cleaned as expected
I have a FilterSet defined as such: from django_filters import rest_framework class SomeFilter(filters.FilterSet): id = filters.BaseInFilter() sort_by = rest_framework.OrderingFilter(fields=["name", "creation_date", "location"]) I use DRF to define API view. In the view, I access the filter data with filterset = self.get_filterset(queryset). What I noticed: filterset.form.data gives me a QueryDict({"sort_by": ["name", "location"]} (for example) and if I run filterset.form.cleaned_data.get("sort_by"), I only get "location" This is expected if I look at the doc for QueryDict but this is clearly not what I would expect from the cleaning. Any idea how I could override this cleaning so I can keep all values passed as query params ? -
Does Django DRF have a way to do read-only tokens?
I have a Django REST API using Django REST Framework. I want to use TokenAuthentication, but I want to have read-only tokens and read-write tokens. Read-only just has access to GET methods. Read-Write have access to everything (POST, PUT, DELETE, etc). Does DRF already have something for this? Or would I just create my own Token model with an extra field that keeps track of the type of token, and use my own version of TokenAuthentication that returns a 403 if the token is READ_ONLY, and the method is other than a GET method? I don't want to be re-inventing the wheel here if this already exists. -
Sending email using send_mail and oauth2.0(Modern authentication) in Django
send_mail in Django allows SMTP. I want to check if OAuth2.0 is supported in send_mail option in Django Django version 2.4.57 connection = EmailBackend( host=host, port=port, username=username, password=password, use_tls=tls, use_ssl=ssl, ) connection.open() msg = EmailMessage(subject, message, from_mail, to_mails, connection=connection) msg.send() I am trying to use send_mail option in Django to send emails. I use SMTP connection to provide username and password for the SMTP server. As many companies are disabling SMTP relays for emails, I would like to implement modern authentication for sending mails from Django. I followed this link asked 11 years ago but there's no solution given. Couldn't comment in that question, so asking as a separate question. -
Mechanism for returning unreceived websockets
In my project, we are facing a problem that we cannot solve. The technological context: Our application runs under Django and has Websockets. This stand in a Kube environment. The http part with its API is managed by Django and DRF in Gunicorn pods. The websockets and the asgi layer of the app are managed by Daphne in Daphne pods. We use Channel for Django to support WS. We use its ChannelRedis layer to share data in real time between the various server instances, allowing them to access the same websocket information. The functional context: We have users interacting with the application then the front hit the back via the API. This then triggers a workflow which will, as it progresses, notify the front via WS messages. All users'fronts receive these changes and are then updated. Well, this is the classic principle of WS in fact. Our problem: It happens that some users no longer receive any WS messages (network problem, Daphne, Redis service interruption problem or other). So these users no longer have the right values on their front.. After, the WS connection is reestablished, the next ws messages will be sent again. Unfortunately, messages sent during the blackout … -
SSL routines::legacy sigalg disallowed or unsupported] (-1)
I'm trying to connect my django app to a SQL Server instance. In development I'm using a sqlsrv created with a docker image and everything work just fine. In production I have a connection issue: (('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:0A00014D:SSL routines::legacy sigalg disallowed or unsupported] (-1) (SQLDriverConnect)')) The database settings (settings.py file) are: DATABASES = { 'default': { ... }, 'mssql_db': { "ENGINE":os.environ.get("MSSQL_ENGINE", ""), "NAME": os.environ.get("MSSQL_DB_NAME", ""), "USER": os.environ.get("MSSQL_USER", ""), "PASSWORD": os.environ.get("MSSQL_PASSWORD", ""), "HOST":os.environ.get("MSSQL_HOST", ""), "PORT": os.environ.get("MSSQL_PORT", ""), 'OPTIONS': { 'driver': os.environ.get("MSSQL_OPTIONS", ""), 'MARS_Connection': 'True', 'SSL Mode': 'require', }, } } I've added the following lines, but nothing changed: 'MARS_Connection': 'True', 'SSL Mode': 'require', I've checked the credentials I use and they're correct, also can't find any strange settings of the SQL Server, from Microsoft SQL Server Management Studio. -
Need Help Sending Email Through Office 365 SMTP with Custom Domain
I need to be able to send emails to users from support@example.com which is hosted in office365.My project's setting file for the email backend looks like this # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.office365.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "support@example.com" EMAIL_HOST_PASSWORD = "App_password" The specific error message I'm currently facing is [Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your administrator.] I have verified the login credentials and also tried both ports 587 and 25, but the issue remains unresolved. **However, ** I was able to send emails successfully using smtp-mail.outlook.com with an @outlook.com email address EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp-mail.outlook.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "personal@outlook.com" EMAIL_HOST_PASSWORD = "App_password" I don't think this has anything to do with it but function that sends the email. def send_email_verification(user): site_url = "https://www.example.com" print("Trying to send email") if user.is_active: return else: print("sending email") confirmation_token = default_token_generator.make_token(user) # unique token activation_link = f"{site_url}/users/api/users/activate/{user.id}/{confirmation_token}" # activation link to be sent in email subject = "Verify your Email address" from_email = settings.EMAIL_HOST_USER to_email = user.email # Load the email template and render it with the activation link html_content = render_to_string('email_verification.html', … -
how does search engines identify data of website is exactly stored in the particular database and server
I'm working on a small Python project using Django, and I'm curious about how search engines can quickly identify a website's database and server and respond to end users in just a fraction of a second also i want to know that how data is transmitted -
Is it possible to host django website in the github?
i want to try django website to host in github. is it possible to host it? try it. try it, try it. still now i try it last 3 Days. what should i do for this. any other solution is there. any one reply me with right answer. -
Connect local django application to redis container
I have a django project in local machine + In the docker i have redis container and that is up. when i use docker ps i get this result: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ff39ad874428 redis "docker-entrypoint.s…" 52 minutes ago Up 50 minutes 0.0.0.0:6379->6379/tcp redis2 and this is my cache config in django setting.py: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://localhost:6379', # Adjust the host and port if needed # 'OPTIONS': { # 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # } } } So when i cache in my view, Dosnt save any data. First, How can i check the connection from django to redis container? Second, How can i add new key from django into redis container? Thanks. -
Getting error "detail":"Authentication credentials were not provided."
I tried to get the username corresponding to the auth_token but getting this error. I followed the djoser's documentation ERROR: PS D:\test\testenv\test2> curl.exe -X POST http://127.0.0.1:8000/api/v1/users/ --data 'username=admin3&password=password@123' {"username":["A user with that username already exists."]} PS D:\test\testenv\test2> curl.exe -X POST http://127.0.0.1:8000/api/v1/token/login/ --data 'username=admin3&password=password@123' {"auth_token":"3d0ad33f20ea22e8131a170da2db7830a18b3757"} PS D:\test\testenv\test2> curl.exe -LX GET http://127.0.0.1:8000/api/v1/users/me/ -H 'Authorization: Token 3d0ad33f20ea22e8131a170da2db7830a18b3757' {"detail":"Authentication credentials were not provided."} PS D:\test\testenv\test2> curl.exe -LX GET http://127.0.0.1:8000/api/v1/users/ -H 'Authorization: Token 3d0ad33f20ea22e8131a170da2db7830a18b3757' {"detail":"Authentication credentials were not provided."} PS D:\test\testenv\test2> It should return me the token's corresponding details. -
Media files are not shown: open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied) - Django Nginx
I'm trying to see my media files in my website, but I can't. Static files are OK but Media files, despite all my efforts are not visible. Here is nginx error log: 2023/10/17 11:59:33 [error] 48068#48068: *7 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_uWh54BB.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *6 open() "/home/shahriar/Amlak/real_estate/media/images/IMG_20230828_214539_i6yw2Zc.jpg" failed (13:> 2023/10/17 11:59:33 [error] 48068#48068: *5 open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied), > 2023/10/17 11:59:33 [error] 48068#48068: *4 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_0kmP7E3.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *3 open() "/home/shahriar/Amlak/real_estate/media/images/455008604_479875.jpg" failed (13: Permission> My nginx configuration file for website: location /static { alias /var/www/real_estate/static/; } location /media { root /home/shahriar/Amlak/real_estate/; } settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/var/www/real_estate/static/' STATICFILES_DIRS = [BASE_DIR/'static/',] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media Settings MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media/' I tried giving permission to my media folder like this: sudo chown -R www-data:www-data /var/www/real_estate/static sudo chown -R www-data:www-data /home/shahriar/Amlak/real_estate/media I tried restarting nginx.service and gunicorn.service. The path to media files is correct, but the website seems to be unable to get them. -
Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema
Im trying to merge two GraphQL outputs and I have this error when I try to load Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema. I have two schemas within each corresponding apps from graphene_django import DjangoObjectType from careers import models import graphene class JobType(DjangoObjectType): class Meta: model = models.Job class CategoryType(DjangoObjectType): class Meta: model = models.Category class Query(graphene.ObjectType): all_jobs = graphene.List(JobType) job_by_slug = graphene.Field(CategoryType, slug=graphene.String()) def resolve_jobs_by_category(root, info, category): return ( models.Job.objects.prefetch_related("category") .select_related("title") .filter(category__name__iexact=category) ) schema = graphene.Schema(query=Query) and the 2nd on here: from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from blog import models import graphene class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: model = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag class ImageType(DjangoObjectType): class Meta: model = models.UploadImage class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_bt_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags").select_related("author").all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_image(self, info): if self.image: self.image = info.context.build_absolute_uri(self.image_url) return self.image def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, … -
Nginx is breaking While showing images
I have high quality images which I want to show on my web page. But whenever am running with nginx the django project breaks after some time when pages are loading. I have checked all the file paths and images are loading in django without nginx Tried to run in django was running bbut whenever nginx is configured webpage is breaking -
A task using django/heroku scheduler do nothing
I have used heroku to deploy using python-django. Following heroku documentation, i installed scheduler, create a python scrypt(tarefas.py), but nothing happened. the log show status 0. this is the heroku help answer: Anuj Pandey 20 hours ago Hi Carlos, The status 0 signifies that the entire process is completed and everything worked fine. As logs also show your tarefas.py and python tarefa2.py are executing completely. The issue seems to be with the code you have pushed, this appears to be an issue that falls outside the nature of the Heroku Support policy. I recommend searching our Help Center or asking the community on Stack Overflow for more answers. Regards, Anuj Pandey tarefas.py: import smtplib import email.message import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ERP.settings') def EnviarEmailTeste(): texto = '<h1>Teste de agendamento de tarefas a cada 10 minutos</h1>' msg = email.message.Message() msg['Subject'] = 'Teste de agendamento de tarefas' msg['From'] = '*****' msg['To'] = '****' password = '****' msg.add_header('Content-Type','text/html') msg.set_payload(texto) s = smtplib.SMTP('smtp.gmail.com: 587') s.starttls() s.login(msg['From'],password) s.sendmail(msg['From'],[msg['To']],msg.as_string().encode(('utf-8'))) s.quit() context = 'email enviado com sucesso.' return context my heroku scheduler: Job Dyno Size Frequency Last Run Next Due $ python tarefas.py Standard-1X Every 10 minutes October 17, 2023 11:32 AM UTC October 17, 2023 11:42 AM UTC … -
Guest checkout business logic for server/database with Stripe
I am making an a simple app which allows users to post ads to the website for a fee, as in pay per post. No account is required, it is in essence a guest checkout by default. The issue I am dealing with is the order and best way to implement the business logic on the server side. My flow is as follows: (Front end) User fills out a form with ad details (Front end) User hits submit (Back end) Post request is processed, new database entry is created (Back end) User is redirected to Stripe checkout Payment fails or succeeds Notice how in this flow I create an object/entry in my database before any payment has been made. This already feels wrong because I feel the entry shouldn't exist unless it has been paid for. Because spammer could in theory fill my database with endless entries by filling the form and not completing payment. So if Stripe payment fails in step 5, I have a choice: delete the entry, or return the user to the form prefilled. Clearly, the later is the better option, however if the user never finishes or fixes the payment I will still have a …