Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent primary key from appending to django rest framework url
I have a django project and i am trying to integrate django rest framework into it. I currently have a viewset and I want to do two things. I want to add two filter parameters into the url and grab them in the viewset and use them in the queryset to filter records that match those filters. I also want to prevent the primary key filter to append to the url when i try to access the viewsets... Here is the url: router.register(r'preferences/(?P<namespace>.+)/(?P<path>.+)', PreferencePathViewSet, basename='Preference-path') router.register(r'preferences/(?P<namespace>.+)', PreferenceNamespaceViewSet, basename='Preference-namespace') router.register(r'preferences', PreferenceUserViewSet, basename='Preference') Here is the viewsets: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def get_queryset(self): queryset = Preference.objects.filter(user_id=1) return queryset class PreferenceNamespaceViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer lookup_namespace = 'namespace' def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def get_queryset(self): namespace = self.request.query_params.get('namespace') queryset = Preference.objects.filter(user_id=1, namespace=namespace) return queryset class PreferencePathViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer lookup_namespace = 'namespace' lookup_path = 'path' def get_permissions(self): if self.action == 'create' … -
Azure development center unsupported python version error
I am attempting to get a Django website hosts on Azure that I build in Visual Studio. I am able to publish it and get a dedicated url, however in order to get the site to load properly I need to load my code to azure. So in the development center tab I tried creating a dev ops project to read from, I also tried to upload it through the github repo, with both options I get and error that I am running an unsupported version of python. I ran commands in my local project to see what versions I am using, which are as follows: python - 3.7.3 Django - 2.1 pip - 19.1.1 Command: "D:\home\site\deployments\tools\deploy.cmd" Handling python deployment. Creating app_offline.htm KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot' Deleting app_offline.htm Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. Detecting Python runtime from site configuration Detected python-2.7 Found compatible virtual environment. Pip install requirements. Downloading/unpacking django>=2.1.6,<3.0 (from -r requirements.txt (line 1)) Running setup.py (path:D:\home\site\wwwroot\env\build\django\setup.py) egg_info for package django ========================== Unsupported Python version ========================== This version of Django requires Python 3.5, but you're trying to install it on Python 2.7. This may be because you are using a version … -
Django REST framework. How i can make export model in csv
I have the following models: class Student(models.Model): first_name = models.CharField(verbose_name='student first name', max_length=64) last_name = models.CharField(verbose_name='student last name', max_length=64) email = models.EmailField() class Meta: db_table = 'student' def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True, blank=True, default=None) end_date = models.DateField(null=True, blank=True, default=None) class Meta: db_table = 'course' def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE) completed = models.BooleanField(null=False, default=False) class Meta: db_table = 'course_participant' def __str__(self): return self.course, self.student And urs: urlpatterns = [ path('course', CourseAPIView.as_view()), path('course/<int:pk>/', CourseAPIDetailView.as_view()), path('student', StudentAPIView.as_view()), path('student/<int:pk>/', StudentAPIDetailView.as_view()), path('student/assigned_to_course', StudentAssignedToTheCourseAPIView.as_view()), path('student/assign_student_to_course', StudentAssignToCourse.as_view()), path('student/assigned_to_course/<int:pk>/', StudentAssignedToTheCourseDetailView.as_view()), path('student/report/<int:pk>/', StudentReportView.as_view()), ] I need made export some data in csv, in next format: student full name number of assigned courses to the student number of completed courses by student For example: Test Student,10, 3 Test Student1,12, 1 Test Student2,5, 3 Test Student3,5, 4 So, what view should be for it. I mean, how i can get data like student full name and etc. I will be grateful for the help -
Imported script executing itself in a unittest class even though if __name__ == "__main__" guard is present
Testing functions from an imported python script which creates django boilerplate leads to said function executing itself when the test is run. The testing file is in the same folder as the script being tested. The testing file includes unittest.main() as per the unittest documentation. The tested script also includes if __name__ == "__main__" under which is the main function calling all the other functions in the script. If I put if _name__ == "__main__" at the top of the tested script and run the entire script under that if block, the script still works as intended, however an ImportError is thrown upon running the testing file. Link to the script(It's not very long): https://github.com/PersonRP7/django_tests_generator_standalone/blob/functional_refactor/mts_functional.py import unittest import mts_functional class TestMakeTestStandalone(unittest.TestCase): def test_set_app_name(self): app_name = "one" response = mts_functional.set_app_name() self.assertEqual( response, "one" ) When I run the above test(either in Atom, or in the powershell, using python -m unittest discover), I am prompted for the app_name and if my answer corresponds to the app_name variable defined in the test_set_app_name(self), the test passes. If it doesn't, the test fails. I've also tried importing individual functions using from mts_functional import some_function, but the result was the same. I'm not sure if this … -
How to extend the event/occurrence models in django-scheduler
I'd like to augment events/occurrences in django-scheduler with three things: Location Invitees RSVPs For Location, my initial thought was to subclass Event and add Location as a foreign key to a Location class, but my assumption is that each occurrence saved won't then include Location, so if the location changes for one occurrence, I'll have nowhere to store that information. In this situation, is it recommended to create an EventRelation instead? Will I then be able to specify a different Location for one occurrence in a series? The EventRelation solution seems untidy to me, I'd prefer to keep models in classes for clarity and simplicity. I think Invitees is the same problem, so presumably I should use a similar solution? For RSVPs, I intend to make an RSVP class with Occurrence as a foreign key, and as far as I can tell that should work without any issues as long as I save the occurrence before attaching it to an RSVP? I've read all the docs, all the GitHub issues, various StackOverflow threads, the tests, the model source, etc, but it's still unclear what the "right" way to do it is. I found a PR which introduces abstract models: https://github.com/llazzaro/django-scheduler/pull/389 … -
How to call a template?
How can I call the the about.html from the following index.html? What to add to urls and views? All the html files including about and index are collected in the project/static folder. # This is part of the index.html, where I want to call the about.html <div class="card-footer"> <a href="#" class="btn btn-primary">Learn More</a> </div> # Here is the project/urls.py from django.contrib import admin from django.urls import path from app1 import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), ] urlpatterns += staticfiles_urlpatterns() -
Django caching image from external api
I want to cache images that comes to my app from google api. Settings (Note that I prefer using FileBasedCache): CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': CACHE_ROOT, 'TIMEOUT': 0, } } Here's my code that is called whenever I want to get any photo: # Shorting later syntaxes photo_ref = photo["photo_reference"] # Setting up cache key cache_key = "PHOTO_IMAGE" + photo_ref # Getting previous cache cached_data = cache.get(cache_key) # Checking if previously cached data exists if cached_data != None: # Returning cached data return cached_data else: image = "IMAGE NONE" # Getting temp image URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=" + settings.KEY URL += "&photoreference=" + photo_ref result = urllib.request.urlretrieve(URL) img_temp = NamedTemporaryFile(delete = True) img_temp.write(urlopen(URL).read()) img_temp.flush() # Saving new data to cache cache.set(cache_key, File(img_temp), django_settings.CACHES["default"]["TIMEOUT"]) return img_temp But this code throws me: TypeError at /api/image_gallery/ChIJvxOujlf6PEcRIG3Mt57gV4A cannot serialize '_io.BufferedRandom' object Full traceback: Internal Server Error: /api/image_gallery/ChIJvxOujlf6PEcRIG3Mt57gV4A Traceback (most recent call last): File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dolidod/.local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/dolidod/.local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File … -
ERROR at setup of TestWebsockets.test_authorized_user_can_connect
following tutorial on testdriven.io i have created a websocket test for testing my websocket connection tests/test_websockets.py from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.test import Client from channels.db import database_sync_to_async from channels.layers import get_channel_layer from channels.testing import WebsocketCommunicator from nose.tools import assert_equal, assert_is_none, assert_is_not_none, assert_true import pytest from dc_wb.routing import application from posts.models import Trip TEST_CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } @database_sync_to_async def create_user(*,username='rider@example.com',password='pAssw0rd!',group='rider'): # Create user. user = get_user_model().objects.create_user( username=username, password=password ) # Create user group. user_group, _ = Group.objects.get_or_create(name=group) user.groups.add(user_group) user.save() return user @pytest.mark.asyncio @pytest.mark.django_db(transaction=True) class TestWebsockets: async def test_authorized_user_can_connect(self, settings): # Use in-memory channel layers for testing. settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS print(settings.CHANNEL_LAYERS) # Force authentication to get session ID. client = Client() user = await create_user() client.force_login(user=user) # Pass session ID in headers to authenticate. communicator = WebsocketCommunicator( application=application, path='/taxi/', headers=[( b'cookie', f'sessionid={client.cookies["sessionid"].value}'.encode('ascii') )] ) connected, _ = await communicator.connect() assert_true(connected) await communicator.disconnect() i have created pytest.ini [pytest] DJANGO_SETTINGS_MODULE = dc_wb.settings python_files = test_websockets.py but whenever i run pytest i just got this error ========================================================================== ERRORS =========================================================================== _____________________________________________ ERROR at setup of TestWebsockets.test_authorized_user_can_connect ______________________________________________ request = <SubRequest '_django_db_marker' for <Function test_authorized_user_can_connect>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will … -
How to set multiple rate limits , per 10sec, per 10min, per 1 day using django-ratelimit or throttling?
I want to set the rate limits for my views based on duration of 10sec, 10min and 1 day. So let say user can send 20 requests/ 10 sec, 100 requests/ 10min and 1000 request per day. I have tried throttling but couldn't find any way to set multiple requests. I have tried django-ratelimit package, but i couldn't find any such option in that too as it sets a single string for rate, such as rate = '5/10m'. Please let me know if there is any way out to solve this problem -
How to return a 404 for paths that do not exist in a Django app?
I'm noticing that I'm getting a HTTP 204 "No Content" when I hit certain urls that are invalid. For instance, if I mistakenly type myapp.com/loggin instead of myapp.com/login I would expect an HTTP 404. How can I make it such that any invalid url returns a 404 in Django? -
Why is Django sending duplicate error messages after upgrade to v2.2?
After upgrading to Django 2.2, my app began receiving duplicate error messages. Every error, no matter the type, is now sent to my ADMINS email twice. I am running my app on Heroku and tried their support, but they determined that it had something to do with my app. I have been unable to find similar issues online or on stackoverflow. MY LOGGING CONFIGURATION LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } MY VERSIONS Django==2.2.2 PyJWT==1.4.0 Pygments==2.0.2 bpython==0.13 django-braces==1.4.0 django-gulp==4.1.0 django-debug-toolbar==1.9 django-model-utils==2.0.3 django-heroku-memcacheify==1.0.0 django-pylibmc==0.6.1 django-mptt==0.9.1 django_storages==1.7.1 logutils==0.3.3 oauthlib==1.0.3 python-openid==2.2.5 social-auth-app-django==3.1.0 social-auth-core==3.2.0 google-api-python-client==1.7.4 geopy==1.17.0 requests==2.9.1 requests-oauthlib==0.6.1 six==1.10.0 sqlparse==0.3.0 django-redis==4.10.0 redis==2.10.6 kombu==4.3.0 hiredis sparkpost==1.3.6 pillow==6.0.0 python-twitter==2.2 python-wordpress-xmlrpc==2.3 python-instagram==1.3.2 celery==4.2.0 boto==2.49.0 gevent==1.4.0 waitress==1.0.2 unidecode==0.4.21 djangorestframework==3.9.4 numpy==1.15.0 pandas==0.23.4 dj-database-url==0.4.2 gunicorn==18.0 psycopg2==2.8.2 uwsgi==2.0.15 newrelic -
Django Image processing app ? where should i call the imageprocess function ? in the views or the forms?
I want to make a django app where i can process Images and show both the preprocessed and the processed,i have the function already ready and tested,how i should implement it? I already developed mini apps where it basically takes a user input without actual processing just showing it in views with some restriction and validations.I have a basic idea how i should construct the model of this app and it looks like this: class Image(models.Model): user = models.ForiegnKey(user,on_delete=models.CASCADE) preprocessed = models.ImageField(upload_to=user_path) processed = models.ImageField(upload_to=another_path) so should i call the process function in the views/forms ? I think it's in the views but how it should really looks like? should i call the form and save the input from the form if it's valid to the model ? how should i call the image preprocessed to process it and show it in a detail view ? -
view must be a callable or a list/tuple in the case of include
I am a beginner in django I'm getting this error when running : python manage.py runserver this is my app url (main.urls) from . import views from main import views as main_views from django.contrib.auth import views as auth_views from main.views import blog, about from django.conf.urls import include, url urlpatterns = [ path('about/', 'main.views.about', name='about'), path('', 'main.views.blog', name='blog'), ] this is my full project: https://github.com/ouakkaha/pr i will be so thankful if you find i solution for me:) -
Django: Set initial on a form when the form is submitted (POST)
class MyView(FormView): # get works def post(self, request, *args, **kwargs): field1 = self.kwargs.get('field1', None) if(not field1): field1 = request.POST['field1'] # field1 exists in the URL, and also as an input on the form field2 = 'Test2' field3 = 'Test3' initial={'field1': field1, 'field2': field2, 'field3': field3} # Not bound, but data does not get set input_form = MyForm() print(form.is_bound) form.initial = initial form2 = MyForm(initial, initial = initial) # Also tried # form2 = MyForm(request.POST, initial = initial, initial) with same results print(form2.is_bound) # True print(form2.has_changed()) # true print(form2.changed_data) # field2, field3 - not set return render( self.request, 'template.html', context = { 'form': form # form2 } ) Form: class MyForm(forms.ModelForm): class Meta: model = models.MyModel initial_fields = [ 'field1', 'field2', 'field3' ] fields = [ 'field1', 'field2', 'field3' ] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() return cleaned_data Template: Nothing works - ckeaned_data has only the args in the URL that was set in the get request. {{form.cleaned_data}} {{form.field2.value }} {{ form.field3 }} {% if form.field3.value %} <div class="row"> <div class="col-md-12"> <h5> Field3: </h5> {{form.field3.value}} </div> </div> {% endif %} -
The current URL, pnp4nagios/graph, didn't match any of these
We are using icinga2 o monitor our infrastructure and we are trying to install PNP plugin to have a beautiful view but we are facing the following issue: Using the URLconf defined in graphite.urls, Django tried these URL patterns, in this order: ^admin/ ^render ^composer ^metrics ^browser ^account ^dashboard ^whitelist ^version ^events ^tags ^functions ^s/(?P<path>.*) [name='shorten'] ^S/(?P<link_id>[a-zA-Z0-9]+)/?$ [name='follow'] ^$ [name='browser'] The current URL, pnp4nagios/graph, didn't match any of these. I don't have any experience with django can someone help me please! -
Create multi page pdf report from class objects using XHTL2PDF
I would like to create a multi-page pdf report that creates a new page for each class instance. I store each instance in a list called objects and would like to duplicate each pdf created as a new page in the full pdf report. Right now when I generate the pdf I can get a 1 page report that includes the [0] index. I would like to know how to loop through all indexes of this class and create a new page for each instance. def generate_pdf(request, *args, **kwargs): for x, y in enumerate(Store_Objects.objects): template = get_template('payback/pdftemplate2.html') context = { "store_name": Store_Objects.objects[x].store_name } html = template.render(context) pdf = render_to_pdf('payback/pdftemplate2.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') return response return HttpResponse ("Could not Render PDF") I would like to know how to create a page break and duplicate the exact pdf template but with attributes from the next instance. I'm assuming it has something to do with the return response but I can't figure out what needs to be there to create a new page and continue the loop. -
Cannot set AUTH_USER_MODEL
I have a trouble when trying to extend the 'User' model. In order to make this I've used the settings.AUTO_USER_MODEL from django.conf.settings But that's not working -
Django 2.3: I committed my secret key to a private repository. Can I just edit the secret key myself and then add .env file to .gitignore?
So in being a newb to Django I accidentally committed my secret key to a private repository that I have for my website. Considering that I intend to use this site for business purposes, I want to make sure that it is secure as possible. Do I need to generate a whole new Django Key? Or could I possibly just edit lets say, 10 characters of the secret key, add the edited secret key to my .env file, add the .env to my .gitignore file and call it a day? I recognize this is not the best approach. I will most likely completely generate a new secret key but I thought this might be an effective quick fix. I figure that by doing it this way the new secret key is still randomly generated and the old one is still available on github but useless to anyone who happens to scrape it. FYI I am using python-decouple with a .env file which is where I save all my secret variables (aws info, secret key, db info, etc.). I have separate settings files (production.py, development.py, common_settings.py) where both production.py and development.py import all of the data from common_settings.py. I just happened … -
Django won't render form in multiple templates?
New to Django. Crispy form renders beautifully on register page. Exact copy and paste doesn't render the form on login page? All help is greatly appreciated. I've also tried removing Crispy from the equation with no luck. main_project/urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from website import views as website_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('home/', website_views.home, name='site-home'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout') ] users/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField() address = forms.CharField(max_length=100) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] users/views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': register_form = UserRegisterForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data.get('username') email = register_form.cleaned_data.get('email') messages.success(request, f'Account created for {username}') return redirect('website-home') else: register_form = UserRegisterForm() return render(request, 'users/register.html', {'register_form':register_form}) users/register.html AND users/login.html {% extends 'base.html' %} {% load crispy_forms_tags %} <!-- Extra Styling? --> {% block extrahead %} {% endblock extrahead %} <!-- Include Navbar? --> … -
Split models and forms into a subfolder structure Django 2.0+
I want to have the following structure for models and forms inside my app: project/ --------app_name/ -----------------forms/ -----------------------__init__.py -----------------------a.py -----------------------b_folder/ --------------------------------__init__.py --------------------------------b1.py --------------------------------b2.py -----------------models/ -----------------------__init__.py -----------------------a.py -----------------------b_folder/ --------------------------------__init__.py --------------------------------b1.py --------------------------------b2.py Splitting the app into different apps doesn't really make sense in this particular case. At the moment everything fit into models.py and forms.py but they are around 10k lines each. The idea will be to be abble to split those monolith into small entities to simplify the code maintenance of the all project. For the models parts it seems to work: I was able to runserver without any error. It starts crash when I apply the same method to the forms. Here is the __init__.py content forms/__init__.py from .a import * from .b_folder import * forms/b_folder/__init__.py from .b1 import * from .b2 import * models/__init__.py from .a import * from .b_folder import * models/b_folder/__init__.py from .b1 import * from .b2 import * Now, how to import the following? forms/b_folder_b1.py #how to import the model a or b1? from app_name.models import AModel, BOneModel I get the following error: ImportError: cannot import name 'BOneModel' from 'app_name.models' (/project/app_name/models/__init__.py) -
error:Reverse for 'centreupdate' with keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['NewApp/centreupdate/(?P<slug>[-\\w\\d]+)']
I wanted to use a field value instead of primary key in my url, I looked up on the internet and found some code to do so.I want to use slug in the centreupdate url, but I am not even able to access the centrelist url.What am I doing wrong? Thanks in advance. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = AutoSlugField(unique_with='id', populate_from='name') def __str__(self): return self.name def get_absolute_url(self): return reverse("index") urls.py url(r'^createcentre/$', views.centre.as_view(), name='centreinfo'), url(r'^centrelist/$', views.CentreListView.as_view(), name='centrelist'), url(r'^centreupdate/(?P<slug>[-\w\d]+)',views.CentreUpdateView.as_view(),name='centreupdate'), url(r'^centredelete/(?P<pk>\d+)/$',views.CentreDeleteView,name='centredelete'), -
how to print objects that are in a list that and list is in dictionary
I have a django 1.11 and python 2.7. I want print this objects or know how to access to information Okay this is situation: Okay in my dictionary insert a list, in this list insert a object and node my code is this def __init__(self): BAJO = "Bajo" MEDIO = "Medio" ALTO = "Alto" OUTCOMES = [BAJO, MEDIO, ALTO] net = pysmile.Network() dicCompetencias = {} ALL_COMPETENCES = [] for p in Competencias.objects.raw('SELECT idCompetencias from test_app_competencias where idmapasfk_id = 9 '): lstCompetences = [] lstCompetences.append(objCompetencias(p.idCompetencias).Datos) lstCompetences.append(self.create_cpt_node(net, str(p.idCompetencias), str(p.nombre),OUTCOMES)) dicCompetencias[p.idCompetencias] = lstCompetences print dicCompetencias The ouput {32: [, 0], 33: [, 1], 34: [, 2], 35: [, 3], 36: [, 4], 37: [, 5]} how to see there objects i tried when methods str and repr maybe bad. -
How do I have a profile picture revert to "default" if it is externally deleted?
So I have created a blog with Django, where users who register have a basic default profile picture. The issue is, if I were to delete their profile picture using my hosting site (PythonAnywhere, for example), it doesn't go back to the default image, but rather just an unloaded file. class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) @receiver(models.signals.pre_save, sender=Image) 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 instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) I want to know how to make it so if their profile picture is deleted externally, it defaults to the default.jpg stored in the profile_pics folder inside a media folder. -
uncaught exception: could not load memory initializer wildwebmidi.js.mem
I'm trying to adapt a midi web player to my own project. It works perfectly when I try it local, but when I launch it in localhost, throws me the error of the title. I don't know what I'm doing badly but I've tried some solutions that didn't work. My project is based on django. -
Hidden Button Not Hiding with setInterval
I have a Django app where a user enters an Elasticsearch query and it generates a downloadable document. I have a Download Report button that is supposed to appear once the report is done being generated. However, it shows up at first then checks if the report is generated before disappearing until the report is done. What do I need to modify in my code for the button to hide until the report is done, and not show up before? Note: I am aware my button is not functional and not pointing to anything, I'm still trying to work on that. views.py def check_progress(request): """ Returns status of document generation """ fn = request.POST["filename"] file = "/app/created_files/" + fn if not os.path.exists(file): return JsonResponse({"report_in_progress": 1}) else: return JsonResponse({"report_in_progress": 0}) check.html <!-- templates/django_audit/check.html --> {% extends 'base_login.html' %} {% block title %}Please wait{% endblock %} {% load static %} {% block content %} <script type='text/javascript' src="{% static "bootstrap/js/jquery/1.7.1/jquery.min.js" %}"></script> <script type="text/javascript"> $(document).ready( function() { var fn = $('#fn').val() var checkInterval = setInterval(isFileComplete, 3000); //3000 is 3 seconds function isFileComplete() { $.ajax({ url: '/check_progress/', type: 'POST', data: { 'filename': fn, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, dataType: 'json', success: function (data) { if …