Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"> … -
Button add new element (instance) Django
I need that my template html have a button to add a new element/field, for the class model, it should be a new instance. My html form is created by 2 diferent models and they has a foreign_key, they are the following: models.py class Url_activity (models.Model): url_de_la_actividad = models.URLField() nombre_url = models.CharField(max_length=10, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) lastModification = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) def __unicode__(self): return self.url_de_la_actividad class ActivityProposed (models.Model): nombre_actividad = models.CharField(max_length=50) detalle_de_la_actividad = models.TextField() metodologia = models.CharField(max_length=50) foreign_url = models.ForeignKey(Url_activity, on_delete=models.CASCADE, null=True, blank=True) nombre_de_la_norma = models.CharField(max_length=50) nombre_de_la_competencia = models.CharField(max_length=100) nombre_del_curso = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) lastModification = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) foreing_activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True, blank=True) def __unicode__(self): return self.nombre_actividad so, the main thing is a need to show at the user a "plus" button to add a new URL so many times it is necessary for the user, but I do not know how to do that in django forms, or in the template. forms.py class ActivityProposedForm(forms.ModelForm): class Meta: metodologias_choices = [(metodologia.id, metodologia.methodology_name) for metodologia in Methodology.objects.all()] normas_choices = [(normas.id, normas.norm_name) for normas in Norm.objects.all()] # competencias_choices = # CHOICES = {('1', 'Activa'), ('2', 'Tradicional')} model = ActivityProposed fields = [ 'nombre_actividad', 'detalle_de_la_actividad', 'metodologia', 'nombre_de_la_norma', … -
Trying to print with python but can't manage to find the default printer
Hi i'm working on a python/django project where i need to print a txt file. import win32api import win32print def printFile(): filename = "path/test.txt" win32api.ShellExecute (0,"print",filename, '/d:"%s"' % win32print.GetDefaultPrinter (), ".", 0) I first tried this code directly in a cmd prompt, and it worked. I then made a py file to define the print function as it is above, but when i call it from my view i always get the same error "The default printer was not found" i tried to put the import in the path variable, but i don't see what i did wrong, the import seem to work because i get no error calling the function, only the printer not found error. -
Signal with requests module does not work
I am trying to make a post request using the requests module in order to save data to a remote url. But the signal seems not working, nothing happen when a record is saved and I got no log... Can you tell me what's wrong and how can I get more informations ? models.py @receiver(post_save, sender=Record) def post_record(sender, instance, **kwargs): if kwargs['created']: record = instance payload = { 'name': record.name } r = requests.post('http://.../', data = payload) print(r.status_code) if r.status_code != 200: raise ValueError( 'Request to server returned an error %s, the response is:\n%s' % (r.status_code, r.text) ) -
How to Upload a text file in django using templateview based view and model based forms
I am new to django and stuck on uploading a simple file. I am using TemplateView as views and model based form. I am stuck here. I have no idea what to do. I am using django 2.0. I have attached the code what I have done so far. Please help me to get through this problem ASAP. Thanks in advance. setting.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'key_hash' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Aamir.apps.AamirConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'first.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first.wsgi.application' DATABASES = { 'default': { 'NAME': 'dbname', 'ENGINE': 'django.db.backends.mysql', 'USER': 'arshad', 'PASSWORD': 'arshad', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', } } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' … -
Assign class using python dictionary filters
I want to add class according to index if dictionary key is found in my list area_stats = {'85': (True, False, False, False, False), '11': (False, False, False, False, True)} which the dictionary keys area arrange as top,right,bottom,left,center {% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %} {% for x in list_upper.split %} <ellipse name="centerArea_{{ x }}" class="{% if area_stat[center]==true, highlight, no_highlight %}" /> <path name="leftArea_{{ x }}" class="class="{% if area_stat[left]==true, highlight, no_highlight %}""/> <path name="topArea_{{ x }}" class="{% if area_stat[top]==true, highlight, no_highlight %}"/> <path name="bottomArea_{{ x }}" class="{% if area_stat[bottom]==true, highlight, no_highlight %}"/> <path name="rightArea_{{ x }}" class="{% if area_stat[right]==true, highlight, no_highlight %}"/></svg> </td> {% endfor %} </tr> {% endwith %} is this possible in django? What I tried so far is to use dictionary filters but I don't have idea how to display dictionary values according to index. @register.filter(name='is_dict_key') def is_dict_key(key, d): return key in d @register.filter(name='get_dict_value') def get_dict_value(d, key): try: return d[key] except KeyError as e: print(e) return None -
Get JSON data from POST in Django with REST Framework
I am attempting to build a REST API in Django for a Google Spreadsheet with Gspread, I'm running into a lot of issues (so if anyone happens to have a full example lying around, feel free to share... please? :)). One of those issues it that I'm trying to receive JSON for a POST request (and later on other requests, of course). This is, however, failing. This is my code: view.py (I'm aware that that IF-statement is not how it works elif request.method == 'POST': received_json_data = json.loads(request.body.decode("utf-8")) content = received_json_data['content'] if content != "" return JsonResponse(content, safe=False, status=status.HTTP_201_CREATED) else: return JsonResponse([], safe=False, status=status.HTTP_400_BAD_REQUEST) A test that has been written for this: def test_post_all_training_returns_201_when_correct_format(self): """ A POST request on /trainings/ should create a new training """ headers = {'content-type': 'application/json'} response = self.client.post('/trainings/', json=json.dumps(self.training_json_body), headers=headers, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) The contents of the training_json_body: self.training_json_body = { "date": "1/1/2018", "days": 1, "firstname": "Data", "lastname": "Data", "team": "Data", "training": "Data", "company": "Data", "city": "Data", "cost": 1, "invoice": "Data", "info": "Data" } I have searched for a solution for a couple of days now but can't get it to work, so I would be really greatful if someone could push me in the …