Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding Django LoginView
I am writing a new authentication template to use with my Django apps. I am basing this on a tutorial which I followed. The tutorial uses the built-in authentication views for password resets which I would like to keep, but I want to customise it slightly. I have an attribute on the user accounts called "disabled" which allows a user to login. On the login view I would like to get it to check to see if the account is disabled, "locked", before allowing the login. For the reset password view I would like to get it to unlock the account if successful. An example of the path looks like: from django.contrib.auth import views as auth_views urlpatterns = [ path('accounts/login/', auth_views.LoginView.as_view(), name='login') ] The account model looks like: class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50, blank=True,null=True) date_of_birth = models.DateField(blank=True, null=True) picture = models.ImageField(blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) disabled = models.BooleanField(default=True) hash = models.CharField(max_length=128,default=hex(random.getrandbits(128))) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name.split()[0] Do I import this into views and override it there? Is someone able to post a … -
how can i fix the problem? Error: pg_config executable not found
(venv) C:\Users\PC\PycharmProjects\django>pip install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/a8/8f/1c5690eebf148d1d1554fc00ccf9101e134636553dbb75bdfef4f85d7647/psycopg2-2.8.5.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info\psycopg2.egg-info writing pip-egg-info\psycopg2.egg-info\PKG-INFO writing dependency_links to pip-egg-info\psycopg2.egg-info\dependency_links.txt writing top-level names to pip-egg-info\psycopg2.egg-info\top_level.txt writing manifest file 'pip-egg-info\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\PC\AppData\Local\Temp\pip-install-sqnboffp\psycopg2\ -
How to check if image file exists on given url in local machine using python
I want to check image is existing on the given path. Code snippet as follows: if the image exists: #business logic else: #set default logo -
Can't connect to Postgres db remotely when deployed on GCP
So I'm not sure what code to include that might help so let me know and I can add it. I have a Django web app that I'm deploying on Google Cloud Platform. The app has you search a zip code, then call the Yelp API, adds what it returned to a DB, then pulls from the DB to display in the template. This works perfectly when running locally with a SQLite DB. I've created a Postgres DB and that seems to be working when running locally through cloud_sql_proxy as well. The problem is when deployed it will only search what is already in the DB but cannot add to it. If you search for a zip code that's not already in the DB it returns 500 server error. You can try for yourself HERE. Zip codes 78626 and 55075 work because that's what i tested it with when running locally. if I run locally and do another zip, then deploy, that zip will suddenly work. Please let me know if there's anything i can provide for more context. -
How to migrate all django migration to sql
I have django application, where I wanted to export all migration from my project , auth and admin to sql query. I am able to do python manage.py sqlmigrate myapp 0001 However, I want to export all migration at same time rather than explicitly righting loops. Is there any package or tool that i can use for this. -
I have used a foreign key. I want to display data from both the classes
This is the user model that I've written. class Member(models.Model): mid = models.CharField(max_length=12) real_name = models.CharField(max_length=60) tz = TimeZoneField(default='Europe/London') class Period(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() This is the view that I've written class MemberViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Member.objects.all().order_by("mid") # queryset = Period.objects.filter(member = "id") serializer_class = ItemSerializer How to I write the view in such a way that I get the following as output? { "ok": true, "members": [{ "id": "W012A3CDE", "real_name": "Egon Spengler", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] }, { "id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] } Currently, I am getting the following output, ie, from the Member class only. What changes should I make in order to … -
Admin privileges for users authenticated to a Django site with social-auth-app-django against Auth0
I've got a Django site with authentication handled by Auth0 (following this quickstart guide). The issue I have is that users logged in don't have access to Django Admin section: How can I assign certain Auth0-authenticated users the privileges to login Admin? Somehow link them with current Django-based users perhaps? -
django return 404 uploading media file
hi I have a problem when I upload a file to the deployed server. It returns 404 does not matter if I do it by admin or by a view but if I can see the files that are already on the server. I am hosting my app in namecheap on a shareserver and the settings are settings.py STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static-server') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media folder for database media MEDIA_URL = '/static-server/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '/static-server/media') url.py ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True) switch between debug mode true or false on local and it works perfectly but not when I deploy ... if anyone has any ideas. Well, from namecheap support they answered that the error is not on their side -
How do I install GDAL in a Python Docker environment?
I'm using Python 3.7 and Django 3.0. I want to install this requirement GDAL==2.4.2 in my Django Docker environment. Below is my Docker file ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN apt-get update &&\ apt-get install -y binutils libproj-dev gdal-bin RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal RUN python -m pip install --upgrade pip WORKDIR /app/ COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt ENTRYPOINT ["bash", "/app/entrypoint.sh"] but when building my container, the build dies with the following error ... Collecting GDAL==2.4.2 Downloading GDAL-2.4.2.tar.gz (564 kB) ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ofz0fkgb/GDAL/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ofz0fkgb/GDAL/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-imfatnrk cwd: /tmp/pip-install-ofz0fkgb/GDAL/ Complete output (73 lines): WARNING: numpy not available! Array support will not be enabled running egg_info creating /tmp/pip-pip-egg-info-imfatnrk/GDAL.egg-info writing /tmp/pip-pip-egg-info-imfatnrk/GDAL.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-imfatnrk/GDAL.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-imfatnrk/GDAL.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-imfatnrk/GDAL.egg-info/SOURCES.txt' Traceback (most recent call last): File "/tmp/pip-install-ofz0fkgb/GDAL/setup.py", line 151, in fetch_config p = subprocess.Popen([command, args], stdout=subprocess.PIPE) File "/usr/local/lib/python3.7/subprocess.py", line 800, in __init__ restore_signals, start_new_session) File "/usr/local/lib/python3.7/subprocess.py", line … -
Not JSON Serializable Django Session
In my django view, I have the below: manifestData = form2.cleaned_data form2 is a formset which will have a dynamic number of forms within it. So in one instance it may have just one form, but in a different case it might have 3 or 5, etc, etc. For example, if it contains 2 forms and I execute print(manifestData) I will get the output: [{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}] Next, in my view I am trying to pass that manifestData to another view via the session like so: def quoteView(request): ... request.session['manifestData'] = x return redirect('QuotePreview') class QuotePreview(View): def get(self, request, *args, **kwargs): manifestData = request.session.pop('x', {}) ... However I get an error on this line request.session['manifestData'] = x which mentions "APPLES-1 is not JSON Serializable". I believe this is because this is a foreignkey reference to a product model. class Product(models.Model): ProductCode = models.CharField(max_length=100) HSCode = models.CharField(max_length=50, null=True) DescriptionOfGoods = models.CharField(max_length=100) Price = models.CharField(max_length=100) UnitType = models.CharField(max_length=100) def __str__(self): return str(self.ProductCode) Question is primarily - how can … -
Django file content validation
I'm writing an import-export function for my Django project. My function is working fine , it's importing files to my django admin database. However there's a little problem, when I upload files with different column names it gives me an "IntegrityError at /upload/ NOT NULL constraint failed: accounts_ingredients.name" error . I want my function to give a "Wrong file content" warning if the content in my excel file is wrong. views.py def simple_upload(request): if request.method == 'POST': ingredients_resource = IngredientsReource() dataset = Dataset() new_ingredients = request.FILES.get('myfile', None) if new_ingredients is None: messages.info(request, 'Please upload a file.') return render(request, 'upload.html') if not new_ingredients.name.endswith('xlsx'): messages.info(request, 'wrong format') return render(request, 'upload.html') imported_data = dataset.load(new_ingredients.read(),format='xlsx') for data in imported_data: value = Ingredients( data[0], data[1], data[2], data[3] ) value.save() messages.success(request, 'File upload successful.') return render(request, 'upload.html') resources.py from import_export import resources from .models import Ingredients class IngredientsReource(resources.ModelResource): class meta: model = Ingredients -
how to host static files with heroku, giving me an error
`python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/home/jet/venvfordjango/lib/python3.7/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/home/jet/myapp/static'` and my settings.py looks like this # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ....... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) ........ MEDIA_ROOT= os.path.join(BASE_DIR, 'media/') MEDIA_URL= "/media/" so where could the trouble be? Ready to add more resources on request Thanks in advance -
In the Django address module, how do I search for an entity by a related entity's column that isn't a primary key?
I'm using Django 3 and Python 3.7 with the django-address module -- https://github.com/furious-luke/django-address. In particular, there are two models it provides ... Country name code State name code country -> Country How do I search for states given a certain Country code? If I'm just searching by primary key I can write def get_object(self, pk): try: return State.objects.filter(country=pk) except Coop.DoesNotExist: raise Http404 However, I'm unclear how to write a Django query if I'm searching for states using a country's code. -
nginx/1.14.0 (Ubuntu) 404 Not Found (api call)
I am running a frontend app using Vuejs and backend app with django. I am able to successfully serve both backend and frontend on the same ip using separate nginx server blocks i.e. /etc/nginx/sites-available/frontend_app and /etc/nginx/sites-available/backend_app. Both apps are also enabled. Visiting frontend_app.com and backend_app.com works fine however, whenever frontend_app.com tries to call the backend_app.com api, I get nginx/1.14.0 (Ubuntu) 404 Not Found error. PS. The api call works on my localserver .i.e. calling http://127.0.0.1:000/api/path. On my production server, I change this (I think) to https://api.backend.com/api/path My questions are: is this a frontend error or nginx error? What am I doing wrong? My frontend server block: server { root /var/www/html/iamcart_cli/dist; index index.html index.htm index.nginx-debian.html; server_name www.frontend.com frontend.com; location / { try_files $uri $uri/ =404; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/frontend.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/frontend.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.frontend.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = frontend.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name www.frontend.com frontend.com; … -
Django: no migrations apply, but I have unapplied migrations
I deleted my database and tried to create a new one. I did: python manage.py makemigrations python manage.py migrate Then I ran python manage.py runserver and it returned You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): social_django. Run 'python manage.py migrate' to apply them. Then I ran python manage.py migrate and it returned Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, social_django Running migrations: No migrations to apply. I am using django 3.0.7 and social-auth-app-django 4.0.0 -
How to open a Project from Pycharm using the same env created from Visual Studio Code
I having been working a project on Visual Studio Code the whole time and now I am trying to switch to Pycharm and continue on the same project. I have created for a project a virtual environment in project called env which when I activate it in Pycharm it works except that when I try to run code it shows the following error: bash: python: command not found Worth to mention that I am working on a Django project and the I am trying the run the server after activating the env What should I do to proceed without having to download all packages from scratch? Thank you -
how can i add objects from my model to my CBV in django?
i am trying to add objects from my model into my CBV, i have a model created so i am trying to pass them to my views, but its not working,tho i have 2 classes created which are Pricing and Pricingservice, i want an inline for a field in Pricingservice which i did, but i dont know how to add both to my view in CBV in the view so as to access them in my template, here is my code below, kindly help me out because i have been battling with this for days, thanks model.py class Pricing(models.Model): plans = models.CharField(max_length=250) amount = models.CharField(max_length=250) services = models.CharField(max_length=250) def __str__(self): return self.plans class Pricingservice(models.Model): pricing = models.ForeignKey(Pricing, default=None, on_delete=models.CASCADE) services = models.CharField(max_length=250) def __str__(self): return self.pricing.plans admin.py class PricingserviceAdmin(admin.StackedInline): model = Pricingservice @admin.register(Pricing) class PricingAdmin(admin.ModelAdmin): inlines = [PricingserviceAdmin] class Meta: model = Pricing views.py class HomePageView(TemplateView): template_name = 'pages/home.html' def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['Pricing'] = Pricing.objects.all() return context template.html <div class="row"> {% for p in Pricing %} <div class="col-md-3 ftco-animate"> <div class="pricing-entry pb-5 text-center"> <div> <h3 class="mb-4">{{ p.plans }}</h3> <p><span class="price">#{{ p.amount }}</span> <span class="per">/ Month</span></p> </div> <ul> <li>{{ p.services }}</li> </ul> <p class="button text-center"><a href="#" class="btn … -
Show multiple images from media folder directly to django template
I have a set of images in media folder(200-300).I need to show these images to front end of the django(html) Media images are random images and there is no model too. Is it possible to show images of media directly to django templates? -
OpenCV(4.2.0) error: (-215:Assertion failed) !buf.empty() in function 'cv::imdecode_'
I'm trying to upload an image using Django forms and post it to the server. But I'm getting the following error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:730: error: (-215:Assertion failed) !buf.empty() in function 'cv::imdecode_' Here is my views.py: def uploadpic(request): print(not request.FILES) if request.method == 'POST': # print(request.POST.get('image')) form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() print("image saved") print("in the upload pic") print(request.FILES['image']) photo = request.FILES['image'].read() #I also tried using seek(0) instead of read() print(photo) npimg = np.fromstring(photo,np.uint8) print(npimg) img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED) retval, buffer = cv2.imencode('.jpg', img) knownImage_as_text = base64.b64encode(buffer) return HttpResponse('image upload success') return HttpResponseForbidden('allowed only via POST') models.py: from django.db import models class MyImageModel(models.Model): image = models.FileField(upload_to = 'image/') forms.py: from .models import MyImageModel from django import forms class ImageUploadForm(forms.ModelForm): class Meta: model = MyImageModel fields = ('image', ) HTML code: <!doctype html> <html> {% load static %} <body> <h2>You are here</h2> <form method="post" action="/upload" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="image"> <button type="submit">Upload</button> </form> </body> Below is a picture of the output. The image file I chose to upload was amsterdam.jpg enter image description here -
How can I be sure that the request is being sent by Stripe and not by a third party?
I am working on my application with the Django backend and the Angular frontend and I am gonna use Stripe. At this point everything seems to be working properly. It looks something like shown below. I would like to be sure that I do everything properly and in a secure way. I found Best practices for using webhooks and there is recommendation about adding @require_POST and @csrf_exempt decorators. I guess that I do not need them because Django automatically handle requests other than POST method in my Generic API View and there is also no problem with CSRF so it seems to me that I do not have to disable CSRF protection? I have also doubts how can I be sure that the request is being sent by Stripe and not by a third party? Let's say we have scenario that someone creates an account in the form on the page with amount equals to 10000$ and it goes through the first card verification. He does not have sufficient funds in his account and the transaction is declined however he sends a fake request to my my_stripe_url/ endpoint with status invoice.payment_succeeded. The question is whether Stripe supports it by default … -
NoReverseMatch at / Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[-a-zA-Z0-9_]+)/$']
Hi I'm learning Django and I'm very new at this. I want URLs like this: www.mysite.com/product/product-1 but I don't know it's not working models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=6) slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse("orders:product", kwargs={ 'slug': self.slug }) views.py class ItemDetailView(DetailView): model = Item template_name = "product.html" urls.py from django.urls import path from .views import HomeView, ItemDetailView, checkout urlpatterns = [ path("", HomeView.as_view(), name="home"), path("product/<slug>/", ItemDetailView.as_view(), name="product"), path("checkout/", checkout, name="checkout") ] -
Custom user no password in db
When I try logging in with my custom user model I have been getting 'Please enter a correct email and password. Note that both fields may be case-sensitive.'. When I check the database I see the superuser has a password but my test user does not. Things I've tried: Checking database for users (They're present but no password) Dropping database and running makemigrations Superuser can login on both admin and regular login form just fine accounts/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, phone, is_active=True, is_admin=False, is_staff=False, is_dealer=False, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not company: raise ValueError("Users must have a company") if not phone: raise ValueError("Users must have a phone number") user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name = first_name user_obj.last_name = last_name user_obj.company = company user_obj.phone = phone user_obj.admin = is_admin user_obj.staff = is_staff user_obj.dealer = is_dealer user_obj.active = is_active user_obj.save(using=self._db) return user_obj … -
How to send HttpResponse after email sent
I try to send an email with django , its working fine but i want to send a HttpReponse or somthing like that after the email sent , is that possible to keep using thread for that ? class EmailThread(threading.Thread): def __init__(self, subject, html_content, recipient_list, sender,name): self.subject = subject self.recipient_list = recipient_list self.html_content = html_content self.sender = sender threading.Thread.__init__(self) self.name= name def run(self): msg = EmailMessage(self.subject, self.html_content, self.sender, self.recipient_list) msg.attach_file('/tmp/{username}.{filename}'.format(username=self.name,filename='proformas')+ '.pdf') msg.content_subtype = "html" # Main content is now text/html msg.encoding = 'utf-8' if(msg.send()): print('yes') return HttpResponse('SENT') def send_mail(request,pk): commande = get_object_or_404(Commande,id=pk) name = commande.Client.Raison_social html_nadjib = render_to_string('Proformas/msg.html',{'raison_social':name,'Date':datetime.date.today()}) to_emails = ['adzadadazda@outlook.com'] subject = "azdzadaz" sender = 'aazdazdazadazdb@gmail.com' # EmailThread(subject, html_nadjib, to_emails, sender, name).start() if(EmailThread(subject, html_nadjib, to_emails, sender, name).start()): return HttpResponse('SENT') else: return HttpResponse('not sent') -
django with heavy computation and long runtime - offline computation and send results
I have a django app where the user sends a request, and the server does some SQL lookup, followed by computation on results and finally showing the results to the user. The SQL lookup and the computation afterwards can take a long time, maybe 30+ minutes. I have seen some webpages ask for email in such cases then send you the URL later. But I'm not sure how this can be done in django or whether there are other options for this situation. Any pointer will be very helpful. (I'm sorry but as I said it's a rather general question, I don't know how can I provide a min runnable code for this) -
Apscheduler calling function too quickly
Here is my scheduler.py file: from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events from django.utils import timezone from django_apscheduler.models import DjangoJobExecution import sys # This is the function you want to schedule - add as many as you want and then register them in the start() function below def hello(): print("Hello") def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") # run this job every 10 seconds scheduler.add_job(hello, 'interval', seconds=10, jobstore='default') register_events(scheduler) scheduler.start() print("Scheduler started...", file=sys.stdout) My Django app runs fine on localhost. I'm simply attempting to print 'hello' every 10 seconds in the terminal, but it sometimes prints like 3 or 4 at a time. Why is this? This was just a base template to help understand apscheduler.