Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i put new image to an empty image source it gives me error "ValueError: The 'image' attribute has no file associated with it"
I am using django rest framework, Everything is fine in my code. I can update my file. My main problem is that when i put new image on empty image source it gives me an error like ValueError: The 'image' attribute has no file associated with it. But when i update image with image source it works fine.I want to update my image on empty image source but gives me error like ValueError: The 'image' attribute has no file associated with it Please help me how i solve that error Here is my code: My models.py file: It includes my models fields from django.db import models from django.utils import timezone from .validators import validate_allfile_extension from sessionauthapp.models import User from django.dispatch import receiver import os # from datetime import datetime class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) # time = models.DateTimeField(default=datetime.now) # image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) def __str__(self): return self.title @receiver(models.signals.pre_save, sender=Blog) def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ # if not … -
Using a Django generated slug URL to link to specific pages
Hi generous and kind people of Stack Overflow. I'm fairly new to Python and Django, and have undertaken the project of building a portfolio for my copywriting. I have a main landing page that's going to have a grid of 9 different writing projects. Someone will click on one of the images for a project and then be brought over to a new page that has a more detailed description of the project. Each individual project page has a URL, whose path contains a slug. The code I have works in generating this path. Each writing project will have a URL path that contains projects/(slug) My problem is that I can't get this slug based link that will point to each individual page to work in my code. I'm getting this error: NoReverseMatch at / Reverse for 'individual_project' not found. 'individual_project' is not a valid view function or pattern name. Please forgive any wonkiness with this code, as I am struggling a bit in understanding it all. Here is my views.py: from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Project def individual_project_view(request, project_id): projectpage = get_list_or_404(Project, slug=project_id) return render(request, 'projects/project_detail.html', {'projectpage':projectpage}) def project_home(request): portfolioprojects = get_list_or_404(Project) return render(request, 'projects/project_detail.html', … -
Django REST API on Azure Web App - Static Files
I have a basic django app with django rest framework. I have deployed it to Azure Web App and it working fine except the I am not able to serve the static files. I have the following in setting.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = "/home/site/wwwroot/static/" # Azure path STATIC_URL = '/static/' The application is looking for www.domain.com/static/". I did ran python manage.py collectstatic file on azure and it does create a directory will all the file at the above location. Not sure what's wrong, may be something to do with how azure containiser the application. Any help would be much appreciated -
Python Django view function for virtual assistant app
I have finished the code for a virtual assistant using neuralintents, speech_recognition, PyAudio, pyttsx3 and a json file for training the model. Now I'm trying to add it to a website I already have. Does anyone have an example of how the view function should look like ? Thanks -
Querying a model to filter where a ManyToManyField matches a specific set
I have two models: class Item(models.Model): name = models.CharField() # etc class MergedItems(models.Model): items = models.ManytoManyField(Item) # etc I want each MergedItem to require a unique set of Items. When a user tries to create a new MergedItem, they pass an array of Item ids. I'm trying to validate that input and error if a MergedItem with that specific set of Items already exists, but I'm struggling with the logic to query for/determine that. For example: User creates MergedItem with Item [1, 2] - OK User creates MergedItem with Item [3, 4] - OK User creates MergedItem with Item [1, 2, 3] - OK, [1, 2] already exists but the addition of 3 makes it a unique set User creates MergedItem with Item [1, 2] - ERROR, [1, 2] already exists All the resources I've found have been focused on using something like filter(items__id_in=[1, 2]) but that does an OR query for the item ids. I want an AND query for them, and haven't been able to find anything like that. I'm sure there are some brute force solutions, but this will be running on a public endpoint to a large database, so query efficiency is also key. Thanks in … -
Django ModuleNotFoundError for urlpattern in Heroku deployment
I have a problem with my Django project after deploying it to Heroku. When I go to the project url on Heroku, I am hit with a "ModuleNotFoundError at / No module named 'spotify.urls' ". spotify is an app name in my project called bio_project. This error message leads me to believe that there is something wrong with my urls somehow or perhaps even settings.py bio_project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("spotify.urls")) ] spotify urls.py from django.urls import path, include from . import views app_name = "spotify" urlpatterns = [ path("", views.index, name="index"), path("authorize", views.authorize, name="authorize"), path("callback", views.callback, name="callback"), path("short_term", views.short_term, name="short_term"), path("medium_term", views.medium_term, name="medium_term"), path("long_term", views.long_term, name="long_term"), ] Here is the error: ModuleNotFoundError at / No module named 'spotify.urls' Request Method: GET Request URL: Django Version: 3.2.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'spotify.urls' Exception Location: , line 984, in _find_and_load_unlocked Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Screenshot of error I cannot seem to make any sense of the error since the app is still working perfectly on localhost. Any thoughts? -
How to hide a user's access token that is sent from Django web application?
I am a beginner. I have been working on a Django web application that is integrated with the Webex API. After the OAuth grant flow, an access token is generated (expires after 14 days, so I stored it in a database) and the access token is used in the Webex space widget code to enable the video calling feature on the website. This webpage template along with the Webex space widget code is rendered with Django. But I'm worried about exposing the access token as anyone can see it with developer tools in the browser. Is there any way to hide this access token visible in the browser? This is the webpage code generated by Django <body> <div id="my-recents-widget" /> <script> var widgetEl = document.getElementById('my-recents-widget'); // Init a new widget webex.widget(widgetEl).recentsWidget({ accessToken: '3f9a677931960cf65b6f13d20d1f1cfbcb2b502321891038' }); </script> </body> When this webpage is rendered in the browser, the access token is visible to anyone using the browser's developer tools. I want to hide this token at the same time making the widget working. Is there any way I can achieve this? As I'm a beginner, a detailed explanation will be helpful. The widget code is available here -
What email API should i use to power an app where users can sign-up and then send emails?
I made a django app where users can sign-up, create an account (not email address) and then ideally send out emails through some specific flows I designed in the app. My question is "how should I power the email sending system?". I initially thought about using gmail api but i don't want users to download/upload their credentials et cetera et cetera so now I am looking at services like SendGrid for example. My ideal scenario is that I have a scalable way to onboard users and send emails. Potentially from different email addresses (one per user) but it's ok also from one same email address (and I can differentiate in the text/subject) Suggestions? -
Django post-form cannot validate when using Form with additional inputs
I have a form containing af MultipleChoiceField where the choices are created dynamic based on the given user class UpdateForm(forms.Form): def __init__(self,names,*args,**kwargs): super(UpdateForm,self).__init__(*args,**kwargs) self.fields["list_names"] = forms.MultipleChoiceField(choices = zip(names,names),widget=forms.CheckboxSelectMultiple,label="Pick some names") add_new = forms.BooleanField(initial=True, label="Add new names?",required=False) delete_missing = forms.BooleanField(label = "Delete names?",required=False) and it works fine as GET-request, the issues arrives with the post-request: My view is the following: def update(request): user = request.user list_names = MyModel.objects.filter(user=user).all().values_list("nick_name",flat=True).distinct() form = UpdateWishlistForm(names =list_names) if request.method == "POST": post_form = UpdateForm(request.POST) if post_form.is_valid(): list_names = post_form.cleaned_data["list_names"] add_new = post_form.cleaned_data["add_new"] delete_missing = post_form.cleaned_data["delete_missing"] messages.success(request, "Success") context = { "form":form, } redirect("home") else: #invalid post_form messages.error(request, "Error") context = { "form":form, } return render(request, "discounttracker/update.html") else: #Get request context = { "form":form, } return render(request, "myapp/update.html",context=context) The post_form = UpdateForm(request.POST) does not validate and the post_form.errors is empty. It does contain data though (before calling post_form.is_valid()) print(post_form) # UpdateForm: <UpdateForm bound=False, valid=Unknown, fields=(add_new;delete_missing;list_names)> print(request.POST.dict()) #<QueryDict: {'csrfmiddlewaretoken': ['...'], 'add_new': ['on'], 'list_names': ['test_name_1']}> -
Django Auto Count Field and User - Django
I am using Django to build a website and now need custom counting for each user. I need a separate count for data submitted by a user for each user separately. I have code that works but I have been trying for a long time to integrate user separation into it but I can't. I'm using a foreign key to separate user's data and I need a separate count for each user so all user's first data submitted starts with 1 and counts up from there. I also think it is easiest to keep it all in my models because that is where I have had the best luck but I could be wrong. Thanks in Advance! models: class Sheet_Building(models.Model): user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT) user_count = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True, verbose_name='Inspection Date') time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time') class Meta: ordering = ['-pk'] def __str__(self): return self.timeor 'None' def get_absolute_url(self): return reverse('list_building') def save(self, *args, **kwargs): self.user_count = Sheet_Building.objects.count() + 1 super(Sheet_Building, self).save() -
Django CookieCutter: django.db.utils.OperationalError: fe_sendauth: no password supplied
How to fix the fe_sendauth: no password supplied erorr? There's this open-source framework for Django that is production-ready (https://github.com/pydanny/cookiecutter-django) I don't exactly know the cause of the error, but I do have some ideas, and I'm going to list out all the possible things that could have led to that error. I've followed all steps from this doc (https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html) Here are some of my answers to when I initialised the cookiecutter: version [0.1.0]: 0.1.0 timezone [UTC]: GMT use_whitenoise [n]: n use_celery [n]: n use_mailhog [n]: y use_sentry [n]: y use_pycharm [n]: n windows [n]: y use_docker [n]: n use_heroku [n]: n use_compressor [n]: y Select postgresql_version: 1 - 13.2 2 - 12.6 3 - 11.11 4 - 10.16 Choose from 1, 2, 3, 4, 5 [1]: 1 Select js_task_runner: 1 - None 2 - Gulp Choose from 1, 2 [1]: 1 Select cloud_provider: 1 - AWS 2 - GCP 3 - None Choose from 1, 2, 3 [1]: 1 custom_bootstrap_compilation [n]: n Select open_source_license: 1 - MIT 2 - BSD 3 - GPLv3 4 - Apache Software License 2.0 5 - Not open source Choose from 1, 2, 3, 4, 5 [1]: 5 keep_local_envs_in_vcs [y]: y debug[n]: n And then … -
Django forms don't are saving any information
So I have been trying do build a manager of activities with django and I'm still on the scratch. I was trying to test if the code can simply show if a acitivity is done or not, but it don't change anything. Everything looks good to me and I don't know if the error is in the form, in the view that saves the form or in everything else. I already tried to change the widget and fields of form and haven't been succeed in it. models.py: from django.db import models from django.contrib.auth.models import User class Activity(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) is_complete = models.BooleanField() def __str__(self): return self.title forms.py: from .models import Activity class ActivityUpdateForm(ModelForm): class Meta: model = Activity fields = ['is_complete'] views.py: from .models import Activity from .forms import ActivityUpdateForm def home(request): acts = Activity.objects.all() if request.method == 'POST': form = ActivityUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('home') else: form = ActivityUpdateForm() context = { 'acts': acts, 'form': form, } return render(request, 'diary/home.html', context) template: {% for act in acts %} <form method="POST"> {% csrf_token %} <p>{{ act.title }}</p> <p>Is complete: {{ act.is_complete }}</p> {{ form }} <p>{{ act.author }}</p> <button type="submit">Submit</button> </form> {% endfor … -
Picking up broker_api from Django settings
I have a Django / Celery / Flower setup routing messages to RabbitMQ on windows. All works well except that I can't find a way to pick up the flower broker_api from the Django settings file. CELERY_BROKER_URL is picked up and the tasks can be viewed by Flower, but the Broker tab is blank. If I pass broker_api on the celery -A myapp flower commandline then I can view the Broker tab. e.g. The following works and the broker tab is populated celery -A myapp flower --broker_api=http://myuser:mypwd@localhost:15672/api/ However if I add the broker api into settings.py along with the CELERY_BROKER_URL, instead of passing on the command line, then this no longer works. e.g. CELERY_BROKER_API_URL = 'http://myuser:mypwd@localhost:15672/api/' I have tried different setting names including BROKER_API, BROKER_API_URL, CELERY_BROKER_API, CELERY_BROKER_API_URL and even FLOWER_BROKER_API and FLOWER_BROKER_API_URL. I have also tried adding a flowerconfig.py file with broker_api configured as per the Flower manual, but this doesn't seem to be picked up. Any ideas? -
travis selenium does't work - django - stripe - javascript redirection
I have a selenium test that work on my local machine. Creating test database for alias 'default'... System check identified no issues (0 silenced). ............. ---------------------------------------------------------------------- Ran 13 tests in 32.510s OK Destroying test database for alias 'default'... I use selenium to test stripe checkout. When I click() on button I get redirection to stripe checkout. It work with the javascript from stripe documentation: <script type="text/javascript"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("{{ public_api_key }}"); var checkoutButton = document.getElementById("checkout-button"); const headers = new Headers({ 'X-CSRFToken': "{{ csrf_token }}" }) checkoutButton.addEventListener("click", function () { fetch("{% url "sale:detail" ordered.pk %}", { method: "POST", headers, }) .then(function (response) { response_json = response.json(); return response_json; }) .then(function (session) { return stripe.redirectToCheckout({sessionId: session.id}); }) .then(function (result) { // If redirectToCheckout fails due to a browser or network // error, you should display the localized error message to your // customer using error.message. if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error("Error:", error); }); }); </script> however when i do the same test on travis-ci I get this error: selenium.common.exceptions.TimeoutException due to the: WebDriverWait( selenium, timeout ).until( EC.url_changes(current_url) ) so, the url never change when … -
Ability to have users add/edit/remove form fields dynamically?
I am working on a project that requires a base form + template for ever user, based off of a simple model as such... class FloorPlan(models.Model): user = models.ForeignKey(account) stories = models.IntegerField() bathrooms = models.IntegerField() sqft = models.IntegerField() I know that JS will be needed to make this dynamic. So every user will have a base form and view, which displays just those 3 fields. Now I also want this form to be customizable in a sense to let the user add any extra fields, or also remove fields that are not used. Maybe they add backyard info, pool info, etc. I came across this app, https://github.com/askvortsov1/dynamic-django-forms but doesn't seem to fit what I need. I was thinking of adding an extra field called extra_field=models.ForeignKey(ExtraField) in the FloorPlan model, and make it a m2m, and in the ExtraField model just store the new fields the user wants to create. But design wise, dont think this would be best to let every user flood the DB? I've been looking around to find maybe a JS library too. Really just looking for some advice if anyone has created something similar, just looking for some pointers in the right direction. TY in advance! -
How to ran a function some time after the user enterd the url? Django
I have a page that 10 seconds after the user enterd a change to the database is made, how do i do that? I need to add this idea to both a class based view and a regular view. -
DRF nested through model serialization filtering
Each of my models is inherited from the base model, which contains the publishing_status field that helps me control whether or not the object is included in the returned data. class BaseModel(models.Model): class PublishingStatus(models.TextChoices): ACCEPTED = 'accepted', 'Accepted' REJECTED = 'rejected', 'Rejected' publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text="Publishing status represents the state of the object. By default it is 'draft'" ) class Meta: abstract = True Here are two models Word and Homonym they both inherit from BaseModel: class Word(BaseModel): definition = models.CharField(max_length=255) homonyms = models.ManyToManyField('self', through='Homonym', through_fields=('homonym', 'word')) class Homonym(BaseModel): homonym = models.ForeignKey(Word, on_delete=models.CASCADE) word = models.ForeignKey(Word, on_delete=models.CASCADE) Homonyms are basically words too, so I have self-reference here, but through the model Homonym so that I could control these relationships to be public or not for my website. Then follow the serializers and probably the solution should be passed here: class HomonymSerializer(serializers.ModelSerializer): class Meta: model = Homonym fields = '__all__' class WordSerializer(serializers.ModelSerializer): homonyms = HomonymSerializer(many=True) class Meta: model = Word fields = '__all__' Question: Currently, all homonyms are displayed, regardless of whether they are accepted or not. How can I restrict the nested serializer to include only homonyms with the publishing_status="accepted"? Here is my view: class WordRetrieveView(RetrieveAPIView): serializer_class … -
Programmatically trigger password reset in Django 3.2
The method detailed here no longer works. Importing django.contrib.auth.forms.PasswordResetForm results in the custom user class not being available (django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.CustomUser' that has not been installed). How do I send these emails programmatically? To avoid the X-Y Problem: I don't want user registration. I want admins to be able to create users by supplying an email address, at which point the user receives a password reset email. Upon resetting (more accurately, creating) a password, the user can log in and set a display name and other attributes. -
Django Elastic serach deleting some documents when pointing multiple documents to the same index
I have my django application where i am using django_elasticsearch_dsl to index document to later do elastic search with them. I have two similar models in database so i want the documents to be pointing to the same index in elastic search so later i can do a search with both of them like they are the same. Righ now my setup is like this @registry.register_document class HelpCenterDocument(Document): title = TextField() url = ESTextField('get_absolute_url') site_id = ESIntegerField('site_id') class Index: name = 'help-center-index' class Django: model = HelpCenterPage fields = ['title', 'content'] @registry.register_document class PageDocument(Document): title = TextField() url = TextField('get_public_url') class Index: name = 'global-search-page-index' using = 'global_search' class Django: model = Page When i do manage.py search_index --rebuild it will say that it created Indexing 90 'HelpCenterPage' objects Indexing 213 'Page' objects So with this my index should have 303 documents, this is not the case when i look at the count it shows i have "docs": { "count": 239, "deleted": 64 }, If i comment one of the @registry.register_document the count will be ok, but if i let both of them uncommented it will index only some of them These are the index stats { "_shards": { "total": … -
How to get all values from a Model instance on django
I'm using django signals with post_save and receiving an instance: @receiver(post_save, sender=ServiceOrder) def service_order_post_save(sender, instance, created, **kwargs): if created: print(instance) I just want to get all values from this instance without doing field per field (is a big Model). I tried: instance.objects.values() instance.values() list(instance) as expected all trys failed. -
How can I setup multiple Django Apps using Supervisor (including Gunicorn and Nginx)? bind() to [::]:8090 failed (98: Address already in use)
I already deployed a Django/Wagtail App using Supervisor, Gunicorn and Nginx (on Debian Buster), so I can reach it with http://xx.xxx.xxx.xxx:8090. /etc/nginx/sites-available/cms server { server_name xx.xxx.xxx.xxx; listen 8090; listen [::]:8090 ipv6only=on; error_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log; access_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location /media/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location / { include proxy_params; proxy_pass http://unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock; } } /etc/supervisor/conf.d/guni-mysite-admin.conf [program:guni-mysite-admin] command=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/bin/gunicorn admin_panel.wsgi:application --config /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py user=www.mysite.com autostart=true autorestart=true /etc/supervisor/conf.d/nginx-mysite-admin.conf [program:nginx-mysite-admin] command=/usr/sbin/nginx -g "daemon off;" autostart=true autorestart=true stderr_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-error.log stdout_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-access.log stderr_logfile_maxbytes=2MB stdout_logfile_maxbytes=2MB /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py workers = 3 keepalive = 5 user = 'www.mysite.com' proc_name = 'admin_panel' loglevel = 'error' errorlog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log' accesslog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log' bind = 'unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock' raw_env = ['DJANGO_SETTINGS_MODULE=admin_panel.settings.production'] pythonpath = '/home/www.mysite.com/www/mysite/cms/admin_panel' Now I added 2 more Django Apps the same way. Unfortunately Supervisor can´t bring them up. Sometimes 1 out of 3 runs, but most of the time none of them work. In case it works it creates 3 processes (idk if that´s how it is supposed to be). $ sudo lsof -i:8090 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 3631 root 16u IPv4 961301189 0t0 TCP *:8090 (LISTEN) nginx 3631 root 17u IPv6 961301190 0t0 TCP *:8090 (LISTEN) nginx 3632 … -
Getting error when trying run test "RuntimeError" Database access not allowed
I am facing below error ERROR: Database access does not allow def send_orders(): for order in Order.objects.all(): order.send() order.sent = True #factories.py class OrderFactory(....): amount = 100 sent = False #test_order.py def test_send_orders(order): send_orders() assert order.sent -
Django get current model id after model form save & redirect it with this pk to set as fk to another models fk in model form
Working on Django 3.2 & unable to save forms with reference to each other. Like Project>Photos>Assignments>Students every form is a model form & has a relationship with each other. I have one Project Model & Another is Photos, want to get id of project after save & redirect user next model form "Photos" with project id reference where project_id is FK in Photos Model & should be assigned automatically, Can someone please help on this. here is what I have tried. I'm looking for url somethig like this: URL for add project: http://example.com/projects/add-project URL for upload photos project: http://example.com/projects/1/upload-photos #urls.py path('add-project', views.submit_project, name='submit_project'), path('<int:project_id>/upload-photo/', views.upload_media, name='upload_media'), #model.py code class Project(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True, related_name='project_owner') title = models.CharField(max_length=200) #Photo Model class ProjectMedia(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) photo1 = models.ImageField(upload_to='projects/media/', null=True, blank=True) #Views.py def submit_project(request): if (request.user.is_authenticated): if request.method == 'POST': form = SubmitProjectForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] project = Project(title=title) project = form.save(commit=False) project.owner_id = request.user.id project.save() messages.success( request, 'Thank you! Your project has been submitted.') else: form = SubmitProjectForm() context = { 'form': form, } return render(request, 'add-project.html', context) #Photo submit view def upload_media(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = … -
Display Image in HTML from SSH with django
I'm trying to display a randomly fetched image via ssh-connection on an HTML page with Django. Currently, I save a temporary image and then display it in the HTML, but this doesn't seem to be necessary or right. views.py: def image_view(request): rgb_img = IMGLIB.get_random_img() # fetches the img with paramiko and returns numpy.array img = Image.fromarray(rgb_img, 'RGB') img.save(os.path.join(BASE_DIR, 'static/img/temp.png')) context = {} return render(request, 'app1/app1.html', context) IMGLIB.get_random_img() is a custom made python library for our postgis database and uses paramiko for ssh to fetch images: [...] with sftp.open(tif_path) as f: f.prefetch() s = f.read() with MemoryFile(s) as mem: file = mem.open() rgb_img = get_rgb_img(file) return rgb_img Since the original file is actually not .png or .jpg, but a .tif file its being convertet to "plain" rgb in get_rgb_img() Question: How can I efficiently display the RGB with my function-based view on HTML without storing it as a temporary file in Django? -
Can I use google social token to send email through gmail? Django app
I have a django app where I implementeed a method to sign-up through gmail authentication. Now I would like to allow users to send emails using my app through their gmail account. If a user signs-up with Gmail I have a social token from him, is that enough to allow them to send emails through gmail or do I need to go through the manual work of downloading credential.json for each users?