Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling complex computation on a web app involving data from a database
Just some background. This question is to help my team and I make a decision on how to handle an app we are working on. Currently the application is hosted locally in ASP.NET C# and the complex calculations that are done are handled in SQL as a stored procedure. The data is pulled into queries and the server will handle all the calculations and return a recordset which is written to a table and the front end can access that table. So moving forward, we're thinking of moving the application to the web with Django and deciding how to handle the server side of things. So what we really wanted to understand is, how do others handle situations like these? Do we continue with the same idea and build a SQL server and do the same thing or is there a better way to solve this problem? We want to the user to be able to kick the calculations off and do other things while it runs in the background. The user shouldn't have to sit on the page because these calculation can take an hour or more depending on the complexity. We'd appreciate the thought and ideas. Thank you … -
django django-yearmonth-widget display month as month name
I have used package "django-yearmonth-widget" to have year and month selection and not complete date. Here, day is fixed i.e. 1st of every month. This implementation is working fine. Problem i am facing is below How to display month as month name and not number display Option 0 as --Year-- and --Month-- or something like --Select-- Give proper label to the field Please refer below screenshots for reference -
SMTPAuthenticationError: Authentication unsuccessful [BL1PR13CA0128.namprd13.prod.outlook.com] in Django
i'm trying to send and email (from my personal hotmail account) from a Django API. When i make a request through Postman to the local server it works but when i host my app on Heroku it raise the following exception: I've reading and Hotmail accounts have something like SMTP permissions: Here is my Django config vars: CORS_ALLOWED_ORIGINS = ['https://gianlop3z-dev.web.app'] EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER') django_heroku.settings(locals()) The environment variables are in Heroku. -
Why doesn't {% if %} {% else %} construction work in Django template?
So I am trying to display "YOU" above the comment if it's in fact a comment that has been posted by current user, otherwise I am trying to display just a username of one who left a comment. But somehow if/else doesn't work. Can anyone please tell me what am I doing wrong? Thank you beforehand! my models.py class Comments(models.Model): commented_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField(max_length=300) def __str__(self): return self.comment my forms.py class CommentForm(forms.ModelForm): class Meta: model = Comments fields = ['comment'] widgets = {'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 5})} my views.py class Comment(CreateView, LoginRequiredMixin): form_class = CommentForm template_name = 'app/comments.html' login_url = 'login' success_url = reverse_lazy('comments') def form_valid(self, form): self.object = form.save(commit=False) self.object.commented_by = self.request.user self.object.save() if self.object: messages.success(self.request, 'Success') else: messages.error(self.request, 'Error') return redirect(self.get_success_url()) def get_initial(self): initial = super().get_initial() initial['comment'] = 'Please leave your comment here' return initial def get_context_data(self, **kwargs): context = super().get_context_data() context['comments'] = Comments.objects.all() return context and my condition from the template: <div> <div class="commentsContainer"> {% for comment in comments %} {% if comment.commented_by == user.username %} <h4>YOU</h4> {% else %} {{comment.commented_by}} {% endif %} <div class="comment"> {{comment}} </div> {% endfor %} </div> -
Redis wrong version number
I am very new to deploying my Django site on Heroku. I was trying to get Celery to work (as my Django has long processes). I was following a tutorial on how to set up Redis on Heroku. The issue now is that I am getting this error: Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number (conn: fd=11) There are not many solutions online, I only kind of understand that I will need to downgrade this somehow, any suggestions on how to overcome this problem? Note that I am using the free tier for Heroku and Redis. -
Django Abstract User - how to implement it and adapt to current signal
I don't have the standard Django User model to rely on, I don't know how to refer to the instance below. Before changing to the Abstract User Model I would refer to (user=instance). I was attempting to adapt a functioning e-commerce site by removing/including aspects, one of these adaptations was a Custom User model. Could it be true that I wouldn't need the "create_or_update_user_profile" function anymore since User is now the model that is used as the AUTH_USER_MODEL? When attempting to log in as admin, this error fires: File "/workspace/Project-Saasy/profiles/models.py", line 48, in create_or_update_user_profile instance.userprofile.save() AttributeError: 'User' object has no attribute 'userprofile' So I wondering either how to add the attribute to the 'User' object, or if there another way around all of this models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.conf import settings from django.dispatch import receiver class User(AbstractUser): """ A user profile model for maintaining default delivery information and order history """ is_volunteer = models.BooleanField(default=False) is_organisation = models.BooleanField(default=False) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_street_address2 = models.CharField(max_length=80, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_county = models.CharField(max_length=80, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) class Volunteer(models.Model): user … -
How to get last element in a ForeignKey relation?
To describe my problem I will use basic models : class Chatroom(Model): date_created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=3000) class Message(Model): date_created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=3000) room = models.ForeignKey( Chatroom, on_delete=models.CASCADE, related_name='messages' ) I want to display every last messages sent to a room ordered by date of creation. In practice, the user connect to the page and he can see the messages ordered by date, but only the last message of each room. Example : in the database we have: rooms = [RoomA, RoomB] messages = [ { text: 'firstA', date_created: 01/05/21, room: RoomA }, { text: 'secondA', date_created: 03/05/21, room: RoomA }, { text: 'firstB', date_created: 02/05/21, room: RoomB }, { text: 'secondB', date_created: 06/05/21, room: RoomB }, ] As a result of my queryset, I want to get last messages of each room, meaning messages [secondB, secondA]. Currently I am doing the following : messages_uids = Message.objects \ .order_by('room_id') \ .distinct('room_id') \ .values_list('pk', flat=True) queryset = Message.objects \ .filter(pk__in=messages_uids) \ .order_by('-date_created') return queryset I have only one message per room (good point), messages are ordered by date_created (good point), but I do not have the last message of each room. With the previous set of example, I … -
DisabledBackend Error with every second reload with Django, Celery and RabbitMQ
I am using django, celery and RabbitMQ for a webserver. On my development server everything works fine. However, when I try to run the webserver on my production server with apache2/mod_wsgi every second time I reload the result page I get the following error: 'DisabledBackend' object has no attribute '_get_task_meta_for' That happens when I try to run the following command: task_state = <taskname>.AsyncResult(task_id).state My CeleryConfiguration is as following: app = Celery('<name>', broker='amqp://<user>:' + RABBITMQ_PASSWD + '@localhost:5672/<vhost>', backend='django-db', task_ignore_result=False, task_track_started=True, ) The backend is set and it works exactly every second time. I tried restarting the services, the computer and cleaning the databases. Same problem with different backends. Does anyone have an idea what could cause the problem? Thank you for your help! -
What to use instead of DO_NOTHING to only delete one field?
I want to link two models like this class t_data(models.Model): receiver = models.TextField() file_desc = models.TextField() file = models.FileField(upload_to='files') another model : class transaction_detail(models.Model): transaction_id = models.ForeignKey( t_data, on_delete=models.DO_NOTHING, ) sender=models.TextField() receiver = models.TextField() *yes i am using DO_NOTHING and i have read that it is wrong to use it. But it is not working. now when a user tries to delete his file, The t_data object should be deleted but the transaction_details should not change.There is nothing specific on my view for deleting objects. Yet, simple example would be def delete_request(request,id): requested = t_data.objects.get(id=id) requested.delete() return HttpResponseRedirect('/requests') When I try to delete the t_data object it throws an Integrity Error. How to solve it? Or what to use in place of DO_NOTHING? We can also use OneToOneField if you want to solve this problem. Thank you :) -
Is there a way to apply condition on django boolean field?
I am working on an multi-vendor Django base E-commerce project. I want radio button base selection like when a user add an item to cart I want him/her to choose (yes or no) Is this gift? when a user click on yes, I need to show a message input field where he/she can put custom message to print on item. There are multiple items in cart. Can Anyone guide me how to do this in django? Thank you in advance. -
Django : Run task in background immediately
Similarly to this question, I don't understand how the django-background-tasks module works. What I want is to have a button which would start a task in background so it doesn't block the front. The task has to be run as soon as the click occurs. Reading the docs I thought that I only had to define my task as a function preceded by the decorator @background(schedule=1) then calling the function would start the task one second after the click handler was run. Calling notify_user as normal will schedule the original function to be run 60 seconds from now: However this is not what happens. What happens is that a new task is created after each click (I could understand that by requesting the background_task database thanks to this answer) but none ever runs. The command python manage.py process_tasks seems to run one task defined previously before stopping. If no task has been defined, then it waits for a task to be defined for up to duration seconds (specified when running the command). This behavior is not what I expected while reading the documentation. duration - Run task for this many seconds (0 or less to run forever) - default is … -
How to check if the current user has already liked the post in the list view?
Im showing a list view of posts, posts can be liked and I would like to check whether the post is already liked by the user or not so I can show a like or unlike button. How do I do that? I guess it is somehow connected with related_name but do not know how exactly. Or can I put in the model or in the view and how to do this in the best way? user model - UserProfile is generated for each user class User(AbstractUser): pass class UserProfile(models.Model): user = ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.user.username def post_user_created_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post model class Post(models.Model): author = models.ForeignKey(UserProfile, on_delete=models.CASCADE) text = models.TextField() slug = models.SlugField(max_length=255, unique=True) timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(UserProfile, related_name="posts") the view class PostListView(generic.ListView): model = Post template_name = "posts/post_list.html" context_object_name = "posts" form = PostForm() def get_queryset(self): return Post.objects.order_by("-timestamp") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form return context def post(self, request, *args, **kwargs): form = PostForm(request.POST) if form.is_valid(): form.instance.author = get_author_userprofile(self.request.user) form.save() return redirect('posts:post-list') -
ftplib.error_temp: 451 Need to secure data channel first
I am trying to access an FTP client using django but I am getting this error: ftplib.error_temp: 451 Need to secure data channel first can anyone help me? i am using this part of the management command to upload the file Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/proteinforpets/applications/catalogue/management/commands/send_nielson_data.py", line 26, in handle self.upload_report_to_nielson(transaction_report) File "/home/ubuntu/proteinforpets/applications/catalogue/management/commands/send_nielson_data.py", line 102, in upload_report_to_nielson ftps.storbinary('STOR ' + os.path.basename(report_file), f) File "/usr/lib/python2.7/ftplib.py", line 772, in storbinary conn = self.transfercmd(cmd, rest) File "/usr/lib/python2.7/ftplib.py", line 378, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/usr/lib/python2.7/ftplib.py", line 722, in ntransfercmd conn, size = FTP.ntransfercmd(self, cmd, rest) File "/usr/lib/python2.7/ftplib.py", line 336, in ntransfercmd host, port = self.makepasv() File "/usr/lib/python2.7/ftplib.py", line 314, in makepasv host, port = parse227(self.sendcmd('PASV')) File "/usr/lib/python2.7/ftplib.py", line 251, in sendcmd return self.getresp() File "/usr/lib/python2.7/ftplib.py", line 224, in getresp raise error_temp, resp ftplib.error_temp: 451 Need to secure data channel first management command upload part def upload_report_to_nielson(*files): try: ftps = ftplib.FTP_TLS('namft.nielseniq.com') ftps.ssl_version = ssl.PROTOCOL_TLSv1_2 ftps.set_pasv(True) ftps.auth() ftps.prot_p() ftps.connect(port=21, timeout=80) ftps.login(settings.NIELSON_FTP_USER_NAME, settings.NIELSON_FTP_USER_PWD) except … -
How to define extra fields when creating super user in Django?
I have this in my models.py: class UserManager(BaseUserManager): def create_user(self, name, password=None): """ Creates and saves a User with the given name and password. """ if not name: raise ValueError('A user must have a name.') user = self.model() user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, name, password): """ Creates and saves a staff user with the given name and password. """ user = self.create_user( name, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, name, password, id): """ Creates and saves a superuser with the given name and password. """ user = self.create_user( name, id, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user The reason I added the field id in my create_superuser -method is that it is a required field in my model and I thought I need to include it also when running python manage.py createsuperuser. My problem is that I don't know how to customize the super user creation. With this I always get the error TypeError: create_superuser() missing 1 required positional argument: 'id'. I also tried to remove the id from the function. The process goes through without errors then, but I can't log in to the admin site, it says the username … -
How to hide and show "ADD" button in Django while using DRF
I'm Using Django framework as a backend, PostgresSQL for DB and HTML, CSS, Javascript for frontend. I want to show and hide "CHOOSE/ADD" button on table. If user added items in a table, then I want to hide the "CHOOSE/ADD" button and if user remove those items from table I want to show the "CHOOSE/ADD" button. Since I'm using Django Rest Framework to append the table with Help of Javascript. The Codes Goes here: Script to append table using DRF <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td>'+data[i].product.title+'</td><td><a href="" class="btn btn-outline-danger"><i class="fas fa-trash"></i></a></td></tr>'); $("#history").append(row); } } }); }); </script> HTML TABLE: <tr > <th>History Books</th> <td id = "history"></td> <td><a href="{% url 'mainapp: history_book' %}"><button id="btnaddHistoryBook" type="button" class="btn btn-dark"><i class="fas fa-plus"></i>&nbsp;&nbsp;Choose Books</button></a></td> </tr> -
Django cannot find images under templates
So I am creating a Django project and put an image on an HTML page. Issue is that the server cannot see it. This is my folder structure: mysite/app/templates/app/img/pic.png The HTML page is in: mysite/app/templates I tried many different scr formats, such as: <img src="../app/img/pic.png"> but it did not work. -
Django: How to take my query out of my for loop
I got the following code, that contains N queries: for qty in total_qty_bought: product_id = qty["product"] quantity = int(qty["quantity__sum"]) try: method_title = ( self.shipment_model.get(order_id=qty["order_id"]) .method_title.replace("Hent-selv", "") .strip() ) To solve the issue I tried to take the method_title query out of the for loop like this: quantity = 0 for qty in total_qty_bought: quantity = int(qty["quantity__sum"]) method_title = ( self.shipment_model.get(order_id=total_qty_bought[0]['order_id']) .method_title.replace("Hent-selv", "") .strip() ) Note! There will be a full refrence further down, to understand the bigger picture The issue in my solution is, that I am hard choosing which dict to enter , as I select [0] before order_id, and not in a for loop like before, would be selecting every individual item in the loop. Is there a more sufficient way to do this? I do not see a solution without the for loop, but django debugger tool tells me it creates 2k+ queries. CODE FOR REFRENCE class InventoryStatusView(LoginRequiredMixin, View): template_name = "lager-status.html" cinnamon_form = CinnamonForm(prefix="cinnamon_form") peber_form = PeberForm(prefix="peber_form") pc_model = InventoryStatus product_model = Product.objects.all() order_item_model = WCOrderItem.objects.all() shipment_model = WCOrderShipment.objects.all() def get(self, request): # Get all added objects that hasn't been deleted objects = self.pc_model.objects.filter(is_deleted=False) # Get all added objects that has been deleted deleted_objects = self.pc_model.objects.filter(is_deleted=True) … -
Is there a way to set initial values in form fields in django in HTML template?
I have a simple Django form: QUANTITY_CHOICES = [(i, str(i)) for i in range (1,11)] class CartAddFoodForm(forms.Form): quantity = forms.TypedChoiceField( choices=QUANTITY_CHOICES, coerce=int, ) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) and the view: def cart_detail(request): cart = Cart() quantity_update_form = CartAddFoodForm() return render(request, 'cart/cart_detail.html', {'cart': cart, 'quantity_update_form': quantity_update_form}) cart is a model object which has various cart items and I want to add the quantity_update_form for each and every item in cart. So, my HTML file is: <table> <thead> <tr> <th>Item</th> <th>Quantity</th> </tr> </thead> <tbody> {% for item in cart.get_all_items %} {% with product=item.product %} <tr> <td>{{ product.name }}</td> <td> <form action="{% url 'cart:cart_add' food.id %}" method="post"> {{ quantity_update_form.quantity}} {{ quantity_update_form.override}} <input type="submit" value="Update"> {% csrf_token %} </form> </td> </tr> {% endwith %} {% endfor %} </tbody> </table> get_all_items method would return all items in the cart and item.product is the object of Product model class. I want to set {{ quantity_update_form.quantity}} field to item.quantity and {{ quantity_update_form.override|default:True }} field to true. Is there any template tags or filters to do this? -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine in Django and Paho mqtt
I am using paho MQTT to establish a connection with a mosquitto server on a windows 2012 r2 server. I have used 2 threads one for the main server process and another for establishing a connection with mosquitto server. This is how I am establishing connection to MQTT. mqtt.py file is placed in main project of Django along with manage.py import random client_id = f'python-mqtt-{random.randint(0, 1000)}' def mqtt_connect(): mqtt_connect.client = mqtt.Client(client_id) mqtt_connect.client.on_connect = on_connect mqtt_connect.client.on_message = on_message mqtt_connect.client.on_disconnect = on_disconnect mqtt_connect.client.connect(config("CLIENT_PORT"),1883) mqtt_connect.client.loop_start() and I have initialized the thread in init.py inside the main folder along with settings.py import pymysql pymysql.version_info = (1, 4, 0, "final", 0) pymysql.install_as_MySQLdb() import mqtt import threading x = threading.Thread(target=mqtt.mqtt_connect) x.start() The Django application is running on an apache server. ISSUE: Every time I receive a message from MQTT after certain intervals this error occurs, ln1/lidIntact\r [Tue Apr 27 10:54:54.817976 2021] [wsgi:error] [pid 72980:tid 1532] <paho.mqtt.client.MQTTMessage object at 0x000000CC2B07DBC8>\r [Tue Apr 27 10:54:54.817976 2021] [wsgi:error] [pid 72980:tid 1532] ['ln1', 'lidIntact']\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] Exception in thread Thread-2:\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] Traceback (most recent call last):\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] … -
How to create a link preview of a django website?
I read about the OpenGraph but still did not fully understand, tell me how I can implement this for my blog in django so that all article links have different previews, I roughly understand how to do this using the {% post.title%} and {% post.image%}tags, but what about url? -
.is_valid() method but is not validating when ajax used
when i used ajax in my project the form.is_valid() method not validating the form. it showing the 'this field required error' but i access that using request.POST means i fill all the fields. ''' this is html code which render the django model form ##HTML FORM## <form action="" method="post" enctype="multipart/form-data" id="reception_form" novalidate> {% csrf_token %} {% for field1 in form1 %} <label for="{{field1.id_for_label}}"> {{field1.label}} </label> {{field1}} <div> {% if field1.errors %}{% for error in field1.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %} </div> {% endfor %} {% for field2 in reception %} {% if field2.name != 'gender' %} <label for=" {{field2.id_for_label}} "> {{field2.label}} </label> {{field2}} <div> {% if field2.errors %}{% for error in field2.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %} </div> {% endif %} {% endfor %} {% for radiofield in reception.gender %} {{radiofield.tag}} <label for=" {{radiofield.id_for_label}} "> {{radiofield.choice_label}} </label> <br> {% endfor %} <input type="submit" value="Add Reception" name="Add Reception" class="btn btn-secondary mb-3" > </form> ---------- ajax which has post method ## Ajax ## $('#reception_form').submit(function(e){ console.log(" submit pressed") e.preventDefault(); let Rnm = $('#id_username').val(); let Rfnm = $('#id_first_name').val(); let Rlnm = $('#id_last_name').val(); let Rem = $('#id_email').val(); let Rpwd = $('#id_password1').val(); let Rmob = $('#id_mob_no').val(); let Rcty= $('#id_city').val(); let … -
Django model validator using reference from Foreign Key
I was building models from a LED Strip application based in django. First of all, I have two base models, Strip and Zone, every Strip could have many zones. The Strip model has a field called max_led_number which represents the maximum number of LEDs in the strip. And the Zone model has two fields called initial_led and final_led which represents what its names says. In the validators attributes of the initial_led and final_led fields I added the MaxValueIndicator and MinValueIndicator, which works well if I gave them an integer value, but I tried to do is to pass the max_led_number to the MaxValueIndicator value as a method of validation. These are my models. class Strip(models.Model): name = models.CharField(blank=False, null=False,unique=False, max_length=250) serial_port_name = models.CharField(blank=False, null=False,unique=True, max_length=250) status = models.BooleanField(blank=False, null=False, default=False) max_led_number = models.IntegerField(default=300) def __str__(self): return(str(self.name)) class Zone(models.Model): position = models.IntegerField(blank=False, null=False, default=0, unique=False) strip = models.ForeignKey(Strip, on_delete=models.CASCADE) status = models.BooleanField(blank=False, null=False, default=False) initial_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), MinValueValidator(0)]) final_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), MinValueValidator(0)]) mode_choices = [(1,'Fixed color'),(2,'Rainbow'),(3,'Color theatre'),(4,'Rainbow theatre'),(5,'Meteor rain'),(6,'Meteor rain - Trigger')] mode = models.IntegerField(choices=mode_choices,default=0) color = models.CharField(blank=False, null=False,unique=False, default="#FFFFFF", max_length=7) def __str__(self): return("Zone " + str(self.position)) But I receive this error. File "/home/pi/ledcontroller/LEDControllerApp/models.py", line 49, in Zone initial_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), … -
Rendering a response from request.GET as an iframe
I have a Django view which I need to run a HTTP POST request to a Web application's URL with some parameters, then display the response in an iframe. I have implemented the following code: def auth_view(request): SOME_URL = "SOME URL" data = {"some key": "some value",} response = requests.post(SOME_URL , data=data) context = {'content': response.content.decode("utf-8")} return TemplateResponse(request, template="portal/return_view.html", context=context) For return_view.html, it just looks like this: {{ content | safe }} This is not important, but in case it is The html that the iframe runs on looks like this: <body onload="document.form1.submit()"> <h1>This is the iframe view</h1> <!-- If want to test against development --> <form action="some_url_to_start" method="post" target="tool_content" name="form1"> <input type="hidden" name="some_param" id="some_param" value="{{ some_value }}"> <button type="submit"> Launch iframeTool </button> </form> <iframe src="about:blank" width="700" height="600" name="tool_content" id="tool_content" title="Tool Content" ></iframe> </body> The issue is that the return page renders properly, which looks something like this: enter image description here Question: The links which are inside of the rendered iframe page is relative, yet when clicked, will take on the base url of the parent app. Is there a way for the rendered content to take on its own source base url? Second question: The underlying iframe app … -
Url format in stripe checkout session
I can't perform checkout session, probably because of wrong format of the url. How should I format url to enable redirection to payment stripe page? @login_required def checkout(request): try: if request.user.customer.membership: return redirect('settings') except Customer.DoesNotExist: pass if request.method == 'POST': pass else: membership = 'monthly' final_dollar = 10 membership_id = 'price_1IkjAAHziP1k1SzvFKdNwo3h' if request.method == 'GET' and 'membership' in request.GET: if request.GET['membership'] == 'yearly': membership = 'yearly' membership_id = 'price_1IkjAAHziP1k1Szv9v3TxSHn' final_dollar = 100 # Create Strip Checkout session = stripe.checkout.Session.create( payment_method_types=['card'], customer_email = request.user.email, line_items=[{ 'price': membership_id, 'quantity': 1, }], mode='subscription', allow_promotion_codes=True, success_url='http://domainname.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://domianname.visyrelax.com/cancel', -
Djano ORM datetime filter
I have a simple query where I retrieve all the rows from the current date's 12 AM to current time. time_now = datetime.now() time_passed = time_now.hour * 60 + time_now.minute a = (datetime.now() - timedelta(minutes=time_passed)).strftime('%Y-%m-%d %H:%M:%S') b = datetime.now().strftime('%Y-%m-%d %H:%M:%S') result_inwardCount = MYmsEvents.objects.all().filter(recorded_at__range=[a, b],event='In-ward') print(result_inwardCount.query) print(len(result_inwardCount)) Now when I print the query, it gives me this : SELECT "m_yms_events"."id", "m_yms_events"."vin", "m_yms_events"."event", "m_yms_events"."location", "m_yms_events"."recorded_at", "m_yms_events"."sys_id", "m_yms_events"."x", "m_yms_events"."y", "m_yms_events"."last_updated" FROM "m_yms_events" WHERE ("m_yms_events"."event" = In-ward AND "m_yms_events"."recorded_at" BETWEEN 2021-05-19 00:00:37+05:30 AND 2021-05-19 16:49:37+05:30) This gives me 0 results. When I run the same query in pgAdmin it gives me 41 rows. Below is the query after adding the apostrophie : SELECT "m_yms_events"."id", "m_yms_events"."vin", "m_yms_events"."event", "m_yms_events"."location", "m_yms_events"."recorded_at", "m_yms_events"."sys_id", "m_yms_events"."x", "m_yms_events"."y", "m_yms_events"."last_updated" FROM "m_yms_events" WHERE ("m_yms_events"."event" = 'In-ward' AND "m_yms_events"."recorded_at" BETWEEN '2021-05-19 00:00:37+05:30' AND '2021-05-19 16:49:37+05:30') The timezone in Postgres is IST, so is the timezone on to the server.