Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to post data edit and resubmit the data in python django using Javascript Fetch Function?
In my project, the user enters their post (or comments) in the post field and if he/she wants their re-edit the post, click the edit button and data will present in the Textarea field (using javascript). In Textarea, the user wants to reedit the data and submit it. In My doubt is, when I click the edit button the textarea will present and data also editable but it will not post in the database while I am using the fetch function( my target is without refresh the entire page the data will post using javascript fetch function)and also data-id not passing to the javascript function. Kindly help in this regard. index.html <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <!--<button id="edit" value="{{datas.post}}" onclick="edit(this)">Edit</button> --> <button class="btn btn-sm btn-outline-primary" value="{{datas.post}}" onclick="edit(this)">Edit</button> {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div class="row"> <div class="col-md-4"><i class="fa fa-thumbs-up"></i></div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> </div> <br> {% endfor %} **inbox.js** function edit(id) { //var body = event.value; var notes = … -
How to display image in modelformset_factory in Django
I have following model where Im using image field: from django.db import models class ActiveManager(models.Manager): def active(self): return self.filter(active=True) class Offer(models.Model): name = models.CharField(max_length=255) url = models.URLField(blank=True) image = models.ImageField(verbose_name='Banner Image', upload_to='offers', blank=True) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ActiveManager() def __str__(self): return self.name def get_url(self): return self.url def get_image(self): return self.image.url def is_active(self): return self.active I want to edit multiple forms on the go so I userd modelformset_factory: Here is the view: from django.shortcuts import render, redirect from django.forms import modelformset_factory from .models import Offer # Create your views here. def offers(request): OfferFormSet = modelformset_factory(Offer, fields=( 'name', 'url', 'image', 'active' )) formset = OfferFormSet() if request.method == 'POST': formset = OfferFormSet(request.POST, request.FILES) if formset.is_valid(): formset = formset.save(commit=False) for form in formset: form.save() return redirect('offer:offers') context = {'formset': formset} return render(request, 'offers.html', context) Now in the html Im trying to display the image of already existing instance but I couldn't figure out how to do so, Here is an HTML {% extends 'base.html' %} {% block content %} <style> .form-div{ display: flex; flex-grow: 1; margin: 10px 20px; padding: 20px; border-radius: 10px; box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.1); } </style> <form method="post" enctype="multipart/form-data"> … -
binascii.Error: Incorrect padding in django ?- when redirected to django adminsitration page
I was doing a project in django. I added crispy template pack and some bootstrap to project after sometime when i tried to redirect to django administration page suddently its showing a padding error [like this][1] if someone happen to have this error please tell how you solved it. [1]: https://i.stack.imgur.com/k1QWx.jpg -
'tuple' object has no attribute '_meta' on post request ajax django
I got a problem with ajax post request in my django view. My have viewed this one json fail in django ('tuple' object has no attribute '_meta') but seem like I can't find the solution from it. Can you spot me the mistake? Django version = 3.1, Python = 3.8.3 # view.py def teacherRegisterView(request): template_name = "app/register.html" if request.is_ajax and request.method == "POST": form = TeacherRegisterForm(request.POST) if form.is_valid(): instance = form.save() ser_instance = serializers.serialize('json', [instance, ]) <- error on this line return JsonResponse({'instance': ser_instance}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return JsonResponse({'error': ""}, status=400 #my script {% block javascript %} <script> $("form-teacher").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: "POST", url: "{% url 'teacher_register' %}", data: serializedData, success: function (response) { $("#form-teacher").trigger("reset"); }, error: function (response) { alert(response["responseJSON"]["error"]); }, }); }); </script> {% endblock %} error from the terminal Internal Server Error: /teacher-register Traceback (most recent call last): File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/itc-attendance/attendance/account/views.py", line 53, in teacherRegisterView ser_instance = serializers.serialize('json', [instance, ]) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/serializers/__init__.py", line 128, in serialize s.serialize(queryset, **options) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/serializers/base.py", line 94, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'tuple' … -
Only some static files not displaying on Django / Apache stack
Trying to figure out how in the world all my images are loading fine with the exception of a few on one of my templates. Keep in mind, all of this works perfectly in dev mode, but when I moved this to an Apache server, this is what happened. Here is my site that you can see for yourself: http://13.56.18.7/ my file structure: If you look on the Homepage (/ directory) it is missing the main image, and 2 other images directly below that. Also many of the styles are missing. But, all images below this are showing up just fine. Here is the HTML in question: {% extends "base.html" %} {% load static %} {% block contentHome %} <style> .parallax { /* The image used */ background-image: url("{% static 'images/FrontMain-2.png' %}"); /* Set a specific height */ height: 300px; /* Create the parallax scrolling effect */ background-repeat: no-repeat; background-size: cover; } </style> <!-- Container element --> <div class="parallax" style="position: relative;"> <div alt="buttonsDiv" style="right: 35px; bottom: 55px; position: absolute;"> <a href="tel:+1-714-605-2950"><button style="margin-right: 20px;" type="button" class="btn btn-primary btn-lg"><i class="fa fa-phone fa-lg"></i>&nbsp; 714-605-2950</button></a> <a href="{% url 'services_page' %}"> <button type="button" class="btn btn-primary btn-lg"><i class="fa fa-wpforms fa-lg"></i>&nbsp; Contact Form</button></a> </div> </div> This same … -
django-rest-framework-datatables with Apache shows 414 URI too long error
Pre-requisites OS - Centos 7 Python 3.6.4 Django 3.0 (or 3.1.1) Django Rest framework 3.11.1 django-rest-framework-datatables 0.5.0 Apache 2.4 ORACLE 19.1 I have a simple Rest API - which fetches all data from a table in Oracle database. This Django Framework is hosted on Apache webserver. This data is fed into a datatable using the django-rest-framework-datatables. When I fetch data from the API using djangorest framework it works well. When I fetch data using the template with ?format=datatables as the query parameter the URL is changed and it becomes a very long URL since my table consists of 50-60 columns. Thus throws a 414 error. Did anybody else face this error ? It works well with the django's inherent webserver but when used using Django fails. -
Trying to display file name of selected image in a Django project
I have a part in the site I'm working on where a user can upload an image. I'm using a ModelForm to upload the image, but I have to modify the form itself in order to add the styling from the CSS framework I'm using (Bulma). When I display the form from the template as {{ form.as_p }}, it actually has the behavior I want: it shows an upload file button and when you've selected the file (before hitting the submit button) it shows the name of that file so the user can see that the picture has actually been selected. I've tried looking this problem up online several times with no luck, and I've tried looking at the inspector in the browser to see the html code that is generated by Django using the {{ form.as_p }} option, but that looks to be the same as doing it this way. This is the template code I have for this form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="field"> {{ pic_form.non_field_errors }} <label class="label" for="{{ pic_form.image.id_for_label }}">Upload an image</label> <div class="file has-name is-small"> {{ pic_form.image.errors }} <label class="file-label"> {{ pic_form.image }} <span class="file-cta"> <span class="file-icon"> {% fa5_icon 'upload' 'fas' %} … -
Get count of Django queryset by today's date
I have a Django project with a model that looks like this: class sellerprod(models.Model): prod = models.CharField(max_length=15) title = models.CharField(max_length=255, default=None, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateField(db_index=True, default=datetime.date.today, null=True, blank=True) company = models.ForeignKey(company, db_index=True, on_delete=models.SET_NULL, null=True) In my views I import datetime and define NOW = date.datetime.now(). I want to get the count of all the records in the table that have today's date. I have tried this (and some other similar variations): sellercount = sellerprod.objects.filter(date=NOW.date()).count() The table in my PostgreSQL database has a total of 62 records and only 28 have today's date, but this query gives me the total count of 62. I have a different view, which actually retrieves the data rather than a count, and it correctly gets 24 records (there are four less matching records with a company_id of 2) with this: products = sellerprod.objects.filter(date=NOW.date(), company__companyid=2) I presume that I am doing something wrong that causes me to get a count of all my records rather than just those with today's date. Can someone point me in the right direction? Thanks-- Al -
Forbidden (CSRF token missing or incorrect.) Django
I have included {% csrf_token %} in my HTML form(which includes textboxes and some checkboxes) in Django still I get Forbidden (CSRF token missing or incorrect.) error because of processData:false in AJAX. If I try removing processData:false from AJAX the form only keeps loading without any result. In browser console I get the following error:Uncaught TypeError: Illegal invocation . How do I fix this? -
How to use yolov5 model in django
I want to use the yolov5 model in django, but I got trouble. What I want to make is if user upload an image to django server, object detection made by with the yolov5 model, and then the result displayed on the web. The process itself is simple. But I am not sure how to attach yolov5 api and django. As those of you who have used yolo know, yolo basically runs apis based on commands. !python train.py --img 512 --batch 16 --epochs 100 --data ~~ # for training !python detect.py --weights'/content/yolov5/runs/~~ # for detection Is there any way to run this in a Django view? I tried python functions such as execfile() and os.system() that execute commands in an interpreter way within Python script, but it didn't work properly. (I think the paths between Django and Yolo were twisted.) In fact, if possible, it is best to load yolo api as a module like Keras and run it like a function, rather than the command method. But I can't find a way to use yolov5 like a module or something like that. How can I solve this problem? Please give me some advice. -
Aggregate, Sum and Round altogether
So far I have tried return self.aggregate(round(Sum("cart__total"),2), Avg("cart__total")) return self.aggregate(Sum(round("cart__total")),Avg("cart__total")) return (self.aggregate( (round(Sum("cart__total"),2)), (round(Avg("cart__total"),2)))) recent_data = '{:0.2f}'.format(recent_data) recent_data = format(recent_data, '.2f') When I do <p>Recent Total: ${{ this_week.recent_data.cart__total__sum }}</p> I get Recent Total: ${'cart__total__sum': Decimal('146238.770000000'), 'cart__total__avg': Decimal('16248.7522222222')} I want to round the decimals to two places. -
amazon s3 boto3 django secure photo urls
I'm concerned with security, the django app I have allows photos to be displayed after the user has authenticated with Twitter, or locally. I let uploaded files be stored in Amazon s3 using boto3, but can navigate to the url externally when i type it into the browser. I display like this in the template: <img class="" src="{{ MEDIA_URL }}{{item.file}}" style="width:100%; height: auto;"> and the template renders it with the amazon s3 url when the user request the page. I'm a little concerned about this as this url can be retyped by anyone, or information shared without a user credential, even if the file name is hashed and difficult to find. It is possible to create a signed url, but is possible to create signed urls for media objects in the template of a django context? As the media url is constant, and the filename is constant, how would I do this? Any help appreciated. -
Django Class-based Views - ListView if User Is Authenticated, FormView if User is Not, Same URL
When a visitor is logged out and visits my homepage, I want them to see a registration form. When the user logs in, they will be redirected back to the homepage, but it will show a listview-like view. Is the best way to achieve this to subclass both ListView and FormView and override each method necessary to get the behavior I want? Or is there a better way? Checking if the user is authenticated in each method doesn't seem like the Django way to do this. Hoping there's a smart design pattern approach for doing this that I don't know about. class HomepageView(ListView, FormView): def get_template_names(self): if self.request.user.is_authenticated: return ['homepage/loggedin_index.html'] else: return ['homepage/loggedout_index.html'] def get_context_data(self, **kwargs): if self.request.user.is_authenticated: ... else: ... def ... and so on My must-have requirement is that the URL for both logged-in and logged-out users must resolve to the root URL since it's a homepage. from django.urls import path from .views import HomepageView app_name = 'homepage' urlpatterns = [ path('', HomepageView.as_view(), name='index'), ] -
DJango Error - [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
I am using the DJango framework. I created a project in school using Pycharm and I wanted to create another project. However, when trying to run my server, all of the sudden I start to get the following error in my command prompt: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, … -
Pass for loop button value to modal bootstrap django
I've been looking around for this problem and while there are many threads, most use javascrip, ajax, or other stuff that I don't know... I have a list called movies that contain lists of movies and all their information. I'm using this to display all movies in a table. {% for movie in movies %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> <a type="button" data-toggle="modal" data-target="#myModal"> {{movie.0}} <!-- The movie name--> </a> </td> <td>{{movie.3}}</td>. <!-- The movie rating--> <td><a href="">Add</a></td> </tr> {% endfor %} And a trimmed version of my modal looks like: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalTitle" <div class="modal-body"> {{movies.0}} </div> </div> Obviously, no matter which movie I click i will only get the description of the first movie because of {{movies.0}}. Im wondering how can I pass the correct index to the modal so I can do maybe something like {{movies.pk}} where pk would be the index corresponding to the movie I pressed? -
DJANGO - Computing every item unitprice and quantity
what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? I just want to get the total amount of every item, but how do i do that? what should I use? aggregate or annotate? I use aggregate for getting the total amount of all product total = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) and this is my logic on how to get the the total amount of per product total_amount_of_product = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id')).annotate(total_per_item=Sum(F('unitprice') * F('quantity'), output_field=FloatField(),)) item_totals = [item.total_per_item for item in total_amount_of_product] this is the result in my html this is how i print to the html <td class="cart__cell--total"><span class="cart__item-total">₱ {{item_totals}}</span></td> -
how to automatically generate schema for django graphql
I am working on this project: https://github.com/mirumee/saleor This project uses graphql and I am wondering how to generate schema in this folder: https://github.com/mirumee/saleor/tree/master/saleor/graphql Is there a way to automatically generate schema? Thanks -
Django Side Bar Text Wont Appear
so I am trying to Add Another Side Bar Text On my Website Called "Create" But It Only Shows The "Home" I created Not The Views At All IMAGE still learning how to make website but learning little by little not sure why I am having this problem sidenav1 is my Create Text And Sidenav is my Home Page Text <html> <head> <style type="text/css"> .sidenav { height:15%; width:1600; position: fixed; z-index:1; top:0; left:0; background-color:#2C3E50; overflow-x: :hidden; padding-top:20px; } .sidenav a { padding:6px 8px 16px 676px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } .sidenav1 a { padding:6px 6px 16px 696px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } .sidenav a:hover{ color:#f1f1f1; } .main{ margin-left:60px; padding: 0px 10px; } .sidenav1 a { padding:6px 8px 16px 676px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } </style> <title>{% block title %} Habibs Website {% endblock %}</title> </head> </body> <div class="sidenav"> <a herf="/home">Home</a> </div> <div class="sidenav1"> <a herf="/create">Create</a> </div> <div class="sidenav2"> <a herf="/2">View</a> </div> <div id= "content", name="content", class="main"> {% block content %} {% endblock %} </body> </html> -
whenever i try to use "conda" command i get this error, i don't exactly know what it is. can anyone help me?
C:\Users\jaspr>conda create --name myDjangoEnv django Traceback (most recent call last): File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\common\configuration.py", line 30, in from cytoolz.dicttoolz import merge ModuleNotFoundError: No module named 'cytoolz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\jaspr\AppData\Local\Programs\Python\Python38-32\Scripts\conda-script.py", line 11, in load_entry_point('conda==4.2.7', 'console_scripts', 'conda')() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 490, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2862, in load_entry_point return ep.load() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2462, in load return self.resolve() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2468, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\cli_init_.py", line 8, in from .main import main # NOQA File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\cli\main.py", line 46, in from ..base.context import context File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\base\context.py", line 18, in from ..common.configuration import (Configuration, MapParameter, PrimitiveParameter, File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\common\configuration.py", line 35, in from .._vendor.toolz.functoolz import excepts File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda_vendor\toolz\functoolz.py", line 467 f.name for f in reversed((self.first,) + self.funcs), ^ SyntaxError: Generator expression must be parenthesized C:\Users\jaspr> -
Turn Rasberry Pi into Apache server and use mod_wsgi
I am trying to turn my Pi into an Apache server to host a Django built site. I already have Apache installed and running with no problem. I am trying to install mod_wsgi as per Django's documentation. I have installed mod_wsgi but I cannot compile it due to it not finding the aspx component. You can point directly to it by using the command ./configure --with-apxs=path/to/apxs \ --with-python=/path/to/python when configuring mod_wsgi. See here When I configure it there is an error saying it cannot find aspx. The same when I try to compile. To discover if apxs is built you can use the apache2 -l command and sure enough it seems to be running. Even though apxs seems to be compiled I cannot find it to build mod_wsgi. From what I have been reading apache2-dev should be installed to use apxs. It doesn't seem to make any sense to me though as I can find the compiled aspx running. If I do install apache2-dev will that affect apache2? Will apache2-dev take over for apache2? apxs page https://manpages.ubuntu.com/manpages/trusty/man1/apxs.1.html#options -
How to add the PayPal Smart Payment Buttons to my form
Helloo, I am finding difficultly in proceeding with adding the PayPal smart payment buttons in my forms. In my project, there are forms to choose the required payment method through selecting Radio Button Stripe or Paypal. I don't know how to arrange it so that the logos of credit cards and PP used in this website to be shown in the check out page: https://developer.paypal.com/demo/checkout/#/pattern/radio This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) here is the checkout template: <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username I need help to integrate the PayPal payment in my checkout page -
How can I check the reverse relations?
My models: class OrderItem(models.Model): name = models.TextField(max_length=100, blank=True) pack = models.ForeignKey(Pack, on_delete=models.PROTECT, blank=True, null=True) class Pack(models.Model): name = models.TextField(max_length=100, blank=True) How can I check the reverse relations? I want to get all Pack-s that are not in OrderItem-s (in pack field). I solve it like this, but I think it`s a terrible way: orderItems = OrderItem.objects.all() packItems = Pack.objects.all() for packItem in packItems: for orderItem in orderItems: if orderItem.pack == packItem: print('Yeah, you found one of them') PS Terrible, because "Pack" have more than 5k lines -
Execute R scripts through Django hosted on AWS (Elastic Beanstalk)
I am currently building a project that uses Django Web Framework (hosted on AWSEB) but also needs to execute some R scripts. I have tried using subprocess.call(["Rscript", "R_django_test.R"]) but I get the following error "No such file or directory: 'Rscript': 'Rscript'". The code above works locally, but not on the project hosted on AWS. Any help would be greatly appreciated. -
How to send a email for user to sign up in django
I have been trying to search on google and stack overflow but can not seem to find what i'm looking for. In my django web app i would like users to signup with email invite only. I don't want just anyone to sign up. How would I go about doing this. Any help would greatly be appericated. -
Template in Flask vs Django
This is my code: {% for x in range(0,3) %} {% if x == 0 %} {% set YCode = "STAGE01" %} {% set stStage = "First Stage" %} {% elif x == 1 %} {% set YCode = "STAGE02" %} {% set stStage = "Second Stage" %} {% elif x == 2 %} {% set YCode = "STAGE03" %} {% set stStage = "Third Stage" %} {% endif %} <h3>{{ stStage }}</h3> {% for Product in dsStages %} {% if Product.3 == YCode %} <p>{{ Product.4 }}</p> {% endif %} {% endfor %} <br> {% endfor %} This works in a Flask (Jinja2) Template, but it doesn't work in a Django template ... How should it be done in Django? Thanks.