Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user authentication working properly EXCEPT 1 view/template
I am working with Django 1.11.5 and logging-in and validating users via Social Auth. The user authentication, log-in and logoff are working as expected in 12/13 of my templates. All my templates extend my navbar and footer base.html template. In 'base.html' I have the following code for the navbar: {% if user.is_authenticated %} <li class="nav-item"> <span class="nav-link" id="user-name">{{ request.user.username }}</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Logoff</a> </li> {% else %} <li class="nav-item log-in-link"> <a class="btn btn-primary nav-link log-in" href="{% url 'social:begin' 'google-oauth2' %}"><span>Log-In <i class="fa fa-google-plus" aria-hidden="true"></i></span></a> </li> {% endif %} Now, this navbar code works properly in 12/13 of my templates. It is only for 1 template/view/URL where the user is not authenticated. I have tried debugging by printing out the user name and information in the template giving me errors but it looks like the user is getting logged out when reaching that template via its URL and view. I am totally lost. Could someone point out things I can check/do to debug and locate the source of this logoff error? I can provide the relevant code if needed. -
How to execute a decorator function at startup in a Django/Python Application?
I have a number of classes for which I wish to run a decorator function on. As I am aware decorators only run when the class/function/whatever they label is loaded into the code. e.g. def decorator(cls): print("Decorator executed") return cls @decorator class Example: pass Example() How can I trigger the decorator function on all the classes a decorator labels without having to load each class separately? (or without having knowledge of the classes for which a decorator labels) -
Django form issue with MultipleHiddenInput and Postgres ArrayField
I have a model that uses an ArrayField for storage and uses the MultipleHiddenInput field for use in a model form. Everything works fine when I create a new instance of the model. However, when I try to edit an existing instance it renders the hidden input stored in the model as a list [739, 9] as follows: <input type="hidden" name="control_instance_id" value="7" id="id_control_instance_id_0"> <input type="hidden" name="control_instance_id" value="3" id="id_control_instance_id_1"> <input type="hidden" name="control_instance_id" value="6" id="id_control_instance_id_2"> <input type="hidden" name="control_instance_id" value="," id="id_control_instance_id_3"> <input type="hidden" name="control_instance_id" value="9" id="id_control_instance_id_4"> It should be rendered as: <input type="hidden" name="control_instance_id" value="739" id="id_control_instance_id_0"> <input type="hidden" name="control_instance_id" value="9" id="id_control_instance_id_1"> The meta portion of my form is: class Meta: model = AdhocScan fields = ['name', 'schedule_for', 'notifications', 'report_type', 'control_instance_id'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'schedule_for': forms.DateTimeInput(attrs={'class': 'form-control'}), 'notifications': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}), 'report_type': MultiChoiceWidget(choices=ReportEnum.choices()), 'control_instance_id': forms.MultipleHiddenInput() } labels = { 'schedule_for': unicode('Schedule For'), 'report_type': unicode('Reports') }, help_texts = { 'report_type': unicode('NOTE: A Splunk report will always be automatically generated.') } My model is: class AdhocScan(models.Model): name = models.CharField(max_length=256) report_type = ArrayField(models.IntegerField()) control_instance_id = ArrayField(models.IntegerField()) schedule_for = models.DateTimeField(null=True,blank=True) notifications = models.TextField(null=True, blank=True) started_on = models.DateTimeField(null=True, blank=True) completed_on = models.DateTimeField(null=True, blank=True) owner = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add=True) execution_status = models.IntegerField(choices=ScanExecutionStatus.choices(), default=ScanExecutionStatus.CREATED.value) -
wsgi.py' cannot be loaded as Python module - Python3
I am making use of python3 for building the application [Tue Jan 16 19:07:13.587669 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] mod_wsgi (pid=22631): Target WSGI script '/u0/shsathya/html/captool/captool/wsgi.py' cannot be loaded as Python module. [Tue Jan 16 19:07:13.587752 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] mod_wsgi (pid=22631): Exception occurred processing WSGI script '/u0/shsathya/html/captool/captool/wsgi.py'. [Tue Jan 16 19:07:13.587979 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] Traceback (most recent call last): [Tue Jan 16 19:07:13.588026 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] File "/u0/shsathya/html/captool/captool/wsgi.py", line 14, in [Tue Jan 16 19:07:13.588036 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] from django.core.wsgi import get_wsgi_application [Tue Jan 16 19:07:13.588059 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] ImportError: No module named 'django.core' -
Django Checkout in an ecommerce application
I have an ecommerce application which was written based on tutorials found in a book. after implementing everything, I decided to improve it because according to the book, customers have to imput their details everytime they want to checkout from the application and this is very unprofessional. I have included all my codes in my GitHub because I cant include every bit of the code. https://github.com/Olar19/ecommerce . I have worked on this trying to improve it for some months and I just cannot wrap my head around it. any help would be appreciated. -
Django 1.11 how can I construct a url lookup with a hash symbol?
Here is the constructor in question: url(r"^app/#events/(?P<pk>\d+)$" % URL_PATTERNS, views.app, name="app-event"), There is a route to catch app/, so the problem is not that the server doesn't pick up the rest of the url. I know what the browser does there. We use this for links from reverse lookup. My question is, in Django 1.8 it would leave the string alone, not parsing # to %23. In Django 1.11 it does parse, and I don't want it to. -
Heroku Django Application Error: Worker Timout Issue (H12)
After fighting for a while, my first python (django) app is deployed successfully, the database is pushed and can be accessed (and I can run the app both locally as python manage.py runserver or within heroku). However, the end result is still the 'Applications Error' page. The heroku logs shows the following: 2018-01-16T18:43:18.905263+00:00 heroku[web.1]: Restarting 2018-01-16T18:43:18.906518+00:00 heroku[web.1]: State changed from up to starting 2018-01-16T18:43:19.978422+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2018-01-16T18:43:19.998918+00:00 app[web.1]: [2018-01-16 18:43:19 +0000] [4] [INFO] Handling signal: term 2018-01-16T18:43:26.659760+00:00 heroku[web.1]: Starting process with command `gunicorn extend_sp_radii.wsgi --timeout 20 --keep-alive 5 --log-level debug --log-file -` 2018-01-16T18:43:29.067589+00:00 app[web.1]: [2018-01-16 18:43:29 +0000] [4] [DEBUG] Current configuration: 2018-01-16T18:43:29.067608+00:00 app[web.1]: config: None 2018-01-16T18:43:29.067609+00:00 app[web.1]: bind: ['0.0.0.0:48177'] 2018-01-16T18:43:29.067616+00:00 app[web.1]: max_requests_jitter: 0 2018-01-16T18:43:29.067617+00:00 app[web.1]: timeout: 20 2018-01-16T18:43:29.067618+00:00 app[web.1]: graceful_timeout: 30 2018-01-16T18:43:29.067619+00:00 app[web.1]: keepalive: 5 2018-01-16T18:43:29.067620+00:00 app[web.1]: limit_request_line: 4094 2018-01-16T18:43:29.067621+00:00 app[web.1]: limit_request_fields: 100 2018-01-16T18:43:29.067624+00:00 app[web.1]: reload: False 2018-01-16T18:43:29.067623+00:00 app[web.1]: limit_request_field_size: 8190 2018-01-16T18:43:29.067625+00:00 app[web.1]: reload_engine: auto 2018-01-16T18:43:29.067626+00:00 app[web.1]: spew: False 2018-01-16T18:43:29.067627+00:00 app[web.1]: check_config: False 2018-01-16T18:43:29.067628+00:00 app[web.1]: preload_app: False 2018-01-16T18:43:29.067629+00:00 app[web.1]: sendfile: None 2018-01-16T18:43:29.067630+00:00 app[web.1]: chdir: /app 2018-01-16T18:43:29.067631+00:00 app[web.1]: daemon: False 2018-01-16T18:43:29.067633+00:00 app[web.1]: pidfile: None 2018-01-16T18:43:29.067632+00:00 app[web.1]: raw_env: [] 2018-01-16T18:43:29.067634+00:00 app[web.1]: worker_tmp_dir: None 2018-01-16T18:43:29.067635+00:00 app[web.1]: user: 55457 2018-01-16T18:43:29.067636+00:00 app[web.1]: group: 55457 2018-01-16T18:43:29.067637+00:00 app[web.1]: umask: 0 2018-01-16T18:43:29.067638+00:00 app[web.1]: initgroups: … -
Convert django RawQuerySet to Queryset
I have 2 Django models, ModelA with an ArrayField that is used to store a large list of primary key values (possibly 50k+ list) class ModelA(models.Model): pk_values = ArrayField(models.IntegerField()) class CustomManager(manager.Manager): def get_for_index(self, index_id): qs = self.get_queryset() obj = ModelA.objects.get(pk=index_id) return qs.filter(id__in=obj.pk_values) class ModelB(models.Model): # [...] some fields objects = CustomManager() This works: qs = ModelB.objects.get_for_index(index_id=1) However this would be super where "pk_values" is very large. So I tried doing raw SQL queries: class CustomManager(manager.Manager): def get_for_index(self, index_id): qs = self.get_queryset() sql = "SELECT * FROM myapp_model_b JOIN myapp_model_a ON myapp_model_b.id = ANY(myapp_model_a.pk_values) WHERE myapp_model_a.id = '%s'" % index_id return qs.raw(sql) But this returns a django.db.models.query.RawQuerySet instance. And I cant do things like queryset.values() afterwards. How can convert this to a normal Django queryset? Is there a better way of doing this? Docs: ArrayField https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#arrayfield Custom Manager https://docs.djangoproject.com/en/2.0/topics/db/managers/#custom-managers-and-model-inheritance Raw queries https://docs.djangoproject.com/en/2.0/topics/db/sql/#performing-raw-sql-queries -
django: How can I create a custom Logging Filter for SuspiciousOperation exeption?
After migrate to 1.11 ( from 1.8 ) I start to receive from logging a lot of SuspiciousOperationerror. It seems it comes from JS request who keeps session alive if user move their mouse. But this is not important. How can I filter just this exception? -
If you extend the user model in Django using AbstractUser from one app within a project, how do you refer to it from a second app?
Are you able to have a foreign key relationship from a model within the app that does not contain the extended user model to the extended user model in the other app? Is the only way to refer to the extended user model from the second app settings.AUTH_USER_MODEL? -
YouTube Plugin in CKEditor Django returns 404
I've been trying to install the YouTube plugin in CKEditor for a project, but I have failed and I couldn't figure out why. I have configured my settings.py in the following manner (stripping it of irrelevant-to-this-issue code: CKEDITOR_CONFIGS = { 'default': { 'toolbar_Collective':[ ['Source', '-', 'Bold', 'Italic'], # ... { 'name': 'links', 'items': ['Link', 'Unlink'] }, { 'name': 'media', 'items': ['ImageButton', 'Youtube'] }, # ... {'name': 'tools', 'items': ['Maximize']}, ], 'toolbar':'Collective', 'width': '100%', 'height': 400, 'tabSpaces': 4, 'extraPlugins': ','.join([ ]), } } Currently I have left the 'extraPlugins' configurations empty, because as soons as I write 'youtube' in there: 'extraPlugins': ','.join([ 'youtube', ]), CKEditor fails, and the following is shown on my terminal: [16/Jan/2018 18:31:16] "GET /post/new/ HTTP/1.1" 200 7239 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor-init.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/css/main.css HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/ckeditor.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/js/script.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=H4PG HTTP/1.1" 404 1749 Performing system checks... You can see there are other error codes, even regarding the page css. I don't know why they are there, but they are there regardless of any editing, and the editor functions regardless of them. The real issue is with the YouTube … -
Make django url path to match my model objects' name
So I have a courses app, and when I click on the course name I want it to redirect me to the specific course page (like a detail page) and URL path to match the course name. E.g. If course name is 'Science', then when I click on it, url becomes '/science/' and im on the science page. I tried something. re_path('(?P<course_id>[0-9]+)', views.courses, name='courses'), <ul> <li>{{ courses.name }}</li> </ul> def courses(request, course_id): con = Course.objects.all() return render(request, 'courses/courses.html', {'courses': con}) -
Creating title on django form
I currently have my django template displaying about 25 forms. What I need it a way to display a title above each form For example: {% form in formset %} <h1>{{ form.title}}</h1> {{ form.as_ul}} {% endfor %} Currently my formset displays 25 forms or more on one page and it is hard to tell which form I am editing. I would like to add a title on to the form so it is more user friendly Please let me know if you know of a way to do this -
Changing type of primary case changes behavior of ManyToMany field addition
class Word(Model): id = BigAutoField() name = CharField() categories = ManyToMany('Category') When id was an UUIDField I could easily write Word.objects.create(name='apple', categories=[1,2]) (where 1 and 2 are ids of categories). Now I can't write that. Instead I need to write w=Word.objects.create(name='apple') w.categories.add(1,2) Why is that? -
Django: Adding column to model giving error that the column doesn't exist
I have two models, each in separate apps of the same names: class Vendor(models.Model): name = models.CharField(max_length=200, blank=True, default='DEFAULT') serial_num = models.CharField(max_length=200, blank=True) class Node(models.Model): name = models.CharField(max_length=200, blank=True) persons = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True) When I try python3 manage.py makemigrations I get the lengthy error below. I think the issue might be the migration files. Because Home has a foreign key to Person, 0001_initial.py has dependency ('Person', '0007_auto_20180110_1827'), and I am unable to add the serial_num column to Person. So I tried deleting the location column and adding the location column back in, then got the following error saying it doesn't recognize a column location. How do I fix the issue? Also, let me know if I need to provide more info about the issue. Traceback (most recent call last): File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: vendor_vendor.location The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File … -
Type hints for generic code
Let's say, I have this piece of code: class BaseModel(object) pass class AppleModel(BaseModel): pass class OrangeModel(BaseModel): pass def get_record(model, pk): try: result = model.objects.get(pk=pk) # Some code working with BaseModel.. return result except model.DoesNotExist: return None Now, I want to use it like in this example with proper type annotation... myApple = get_record(AppleModel, 12) myApple. # type hints for AppleModel myOrange = get_record(OrangeModel, 433) myOragne. # type hints for OrangeModel How should I annotate get_record function? I tried something like def get_record(model: Type[BaseModel], id: int) -> Optional[BaseModel]: # ... But then, I loose info about subclasses. I tried use Generic, but without success. Real code is more advanced. This is only simplified example. Thanks for any suggestions... -
Extending django admin views
I am trying to extend the admin views and I followed this guide. The given example did end up extending the views and I did end up getting localhost/admin/my_url/ working, however, it did end up removing the urls for all of the other Apps that I have. Is there a simpler way to extend the admin views? I am trying to get a better grasp on how the views work and I wanted to extend the change_form.html with a button redirecting to a simple view, consisting of HttpResponse("Hello, this is get_model_instance_name"). Registering the url as normal in the urls.py should end up working fine, however, I was wondering, whether I can extend the admin urls and end up with something like myapplication/admin/modelname/new_view -
Django ImageField Image Not Displaying
I'm trying to use Django 2.0. I'm using the development 'runserver' right now, so please keep in mind that I'm not in production yet. I am familiar with the differences between the two with regard to static files. I have a Blog Post model. In the admin, I want to be able to add an image to my model using ImageField. I'd like it to be optional, and provide a default image if none is added. I am able to load images in admin. I am unable to render my image in my template. The console shows that Django is trying to GET my image, but my configurations have not worked so far. Here's my model and relevant field: from PIL import Image class Post(models.Model): .... thumbnail = models.ImageField(default='/img/default.png', upload_to='img', blank=True, null=True) .... My model works well aside from the ImageField. My View works well, and I don't think there is any issue there. Here is my urls.py .... from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ .... path('posts/', views.PostListView.as_view(), name='post_list'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), path('post/random/', views.random_post, name='random_post'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm not at all … -
(Django)form.is_valid() is returning false when using ModelForm
I am creating a form using ModelForm to let the users upload a file along with a description . The is_valid() function isn't returning true and I am really confused. I have searched and there are many questions with same title as mine but they don't solve my problem. here is forms.py: class PostForm(forms.ModelForm): document = forms.FileField(widget=forms.FileInput) class Meta: model = FeedModel fields = ['description', 'document'] Here is models.py: class FeedModel(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField() like = models.IntegerField(default=0) dateTime = models.DateTimeField(auto_now=True, auto_created=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) def get_absolute_url(self): u=self.user return reverse('home:feed',u.primary_key) Here is views.py: class PostView(CreateView): form_class = PostForm template_name = 'home/feedModel_form.html' def get(self, request, *args, **kwargs): form=self.form_class(None) return render(request, self.template_name, {'form':form }) def post(self, request, *args, **kwargs): logger = logging.getLogger(__name__) form=self.form_class(request.POST) if form.is_valid(): user=request.user self.object=form.save(commit=False) self.object.user=user self.object.save() logger.error("voila") redirect({'home:feed'}, user.id) return render(request, self.template_name, {'form':form }) def feedview(request, user_id): user = User.objects.get(pk=user_id) return render(request, 'home/feed.html', {'user': user}) Here is feedModel_form.html: {% extends 'home/navbar.html' %} {% block body %} <div class="form"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'home/form.html' %} <button type="submit" class="button button-block" ` name="reg_btn">Post</button>` </form> </div> {% endblock %} Here is form.html: {% for field in form %} <div class="field-wrap"> <label> {{ field.label_tag … -
Django - difficulty in image upload using forms
I want to upload an image from django forms and process it using OpenCV. Here is the code I've written with the help of Django documentation: 1.forms.py: class UploadFileForm(forms.Form): image = forms.ImageField() 2.views.py: def upload_file(request): context = {'status':'not working'} if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): context['status'] = 'working' process(request.FILES['test_01.png']) return render(request,'create.html',context) else: form = UploadFileForm() return render(request, 'create.html', {'form': form}) Here process() is the function which processes the uploaded image.Running this code gives me MultiValueDictKey Error on the line where I call process() After searching for the error, referring to this SO answer I changed process(request.FILES['test_01.png']) to process(request.FILES.get('test_01.png')) I get Attribute Error on the same line(which I guess is because I'm not able to retrieve the uploaded image properly) Where am I going wrong and what is the correct way of doing so? -
Wagtail Django group pictures into albums based on their tags
I was wondering if it's possible to arrange pictures uploaded to wagtail into galleries based on their tags. I have an album app, and its models.py contains : from django.db import models from wagtail.wagtailcore.models import Page # Create your models here. class Category(Page): name = models.CharField(max_length=250) slug = models.SlugField() image = models.ImageField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children') def __str__(self): return self.name class Post(Page): title = models.CharField(max_length=120) category = models.ForeignKey('Category', null=True, blank=True) publish = models.DateField(auto_now=False, auto_now_add=False, ) slug = models.SlugField(unique=True) -
Django Add Edit Form - Field has no attribute assigned to it?
Im trying to combine an add and edit form into one and am receiving an error The 'site_image' attribute has no file associated with it. I could edit files but could not add files, but now when I load the site files page I am receiving the below error, I havent changed the model so am unsure as to why im receiving this error. the list of files shouldn't really care if site_image is there or not as its set to blank and null? my file model: class SiteFiles(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) site_image = models.ImageField(upload_to='site_files/', blank=True, null=True) site_image_thumbnail = ImageSpecField(source='site_image', processors=[ResizeToFill(200, 150)], format='JPEG', options={'quality': 60}) site_file = models.FileField(blank=True, upload_to=site_files_path, \ validators=[validate_file_extension]) file_name = models.CharField(max_length=200, verbose_name="File Name") file_type = models.CharField(max_length=100, verbose_name='File Type', \ choices=settings.FILE_TYPE) class Meta: verbose_name = "Site Files" verbose_name_plural = "Site Files" def __str__(self): return '%s | %s | %s ' % (self.site_data.location, self.site_data.location, self.file_name) my forms.py class FileForm(forms.ModelForm): class Meta: model = SiteFiles fields = ['site_image', 'site_file', 'file_name','file_type'] def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'file_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Div( Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'), Div( Field('site_image', placeholder='Image'), Field('site_file', … -
advance order_by() for manytomany field in django python
I have a challenging query ahead: The situation concerns 2 models: models.py: class result(modles.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) I do following query: final_results = result.objects.filter(job_id_list__user=request.user).distinct() Basically, a final_results has multiple result-objects, which on their turn have multiple JobId-objects attached. Some of these (one or more) JobId-objects are related to the user. How do I order my final_results on the earliest job_time for jobs that only concern that specific user? In other words, get for every result in final_results the earliest JobId for the user and order then final_results on those times. Is this even possible? -
Serving matplotlib graphs with django without saving
I am using a package called matplotlib to create some graphs, based on user input. Creating these graphs can be done like so plt.plot([1,2,3,4]) plt.ylabel('some numbers') some_plot = plt.figure() Moreover it is possible to then save these graphs as images, some_plot.savefig(path, format='png') The problem is that I don't really want to save every single user generated graph, but rather I would like to just display them. I have tried to look up some solutions for related problems. One such solution was to use IoBytes. Following along these answer I get something like from io import BytesIO some_plot_io = BytesIO() plt.plot([1,2,3,4]) plt.ylabel('some numbers') some_plot = plt.figure() some_plot.savefig(some_plot_io, format='png') Is it possible to somehow pass on the BytesIO object to the template and serve the image or does this method not work? Would there be some other method to do this? -
Django - Add / Edit form no data currently saved, no errors
im trying to do an add/edit form in django and have the following, when I try add a new file, I just get redirected to the same page with no errors, I think its because the hidden field is not being populated with the site_data id (each file is linked to a sites id) and as its hidden I am not getting the error displayed. is my method for adding the site_id incorrect? views.py @login_required @user_passes_test(lambda u: u.has_perm('sites.add_sitefile')) def add_edit_file(request, site_id): from sites.forms import FileForm site_data = get_object_or_404(SiteData, pk=site_id) form = FileForm() if request.method == 'GET': form = FileForm(initial={"id_site_data":site_id}) if request.method == 'POST': form = FileForm(request.POST) if form.is_valid(): form.save() return redirect('sites:site_detail_files', site_id) return render(request, 'sites/add_edit_file.html', { 'add_edit_file_form': form, 'SiteName' : site_data.location, 'SiteID' : site_id, }) forms.py class FileForm(forms.ModelForm): class Meta: model = SiteFiles fields = ['site_data', 'site_image', 'site_file', 'file_name','file_type'] def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'file_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Div( Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'), Div( Field('site_data', type="hidden"), Field('site_image', placeholder='Image'), Field('site_file', placeholder='File'), Field('file_name', placeholder='Display Name'), Div('file_type', title="File Type"), css_class='panel-body' ), css_class='panel panel-default', ), css_class='col-lg-3' ), css_class='row' ), ) html rendered: <div class="panel-body"> …