Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax request in a Django blog - Guidance needed on frameworks
I'm looking for guidance on what framework to use for ajax requests. Context I'm building a blogging app with Django and learning JS. The aim is to have a list of blog posts and when the user clicks to open the post it opens in the same page. Then the user can click to see the list of blog posts again which closes the blog post and allows them to open a different post. I think this requires AJAX but I don't know what framework or library will be best to learn for this application, Angular, Node, VUE or React. Basic HTML Layout <div class = "blog-container"> <div class = "blog-list"> {% for post in index %} <div class="blog-post"> <h2> {{ post.post_title }} </h2> </div> {% empty %} <p>No blog posts</p> {% endfor %} </div> <div class = "blog-post-full"> <p>FULL BLOG POST</p> </div> </div> My main concern I'm leaning towards either React or Angular but that is mainly due to articles like this, this or videos like this and that I have seen them mentioned in job descriptions as a desirable skill. Thanks in advance for any advice, I really appreciate everyone's help! -
MultipleChoiceField not being submitted with form
I've been trying to create a custom admin interface using Django and Python as a learning experience, so I do not want to use any 3rd party apps or anything like that. The problem arises when I (as a superuser) try and add a user. I am unable to set the user's permissions. Currently I am using a MultipleChoiceField to allow the adding of permissions to the new user, but the problem is that whenever I try to add the new user, I get the error message Enter a list of values, even though I have selected permissions. And this is also a problem when I leave the select field blank when I don't want the user to have any permissions. I've tried creating a custom MultipleChoiceField, which is a subclass of the MultipleChoiceField, and then overriding the to_python() and validate() methods. I also tried accessing the data in the clean() method, but since the form field failed validation, it does not exist within the cleaned_data dictionary. I also tried to override clean_permissions method, but that did not work either. And in the to_python() method, I only seem to be receiving the last item in the select field. Below is … -
Django ImageField is empty
I am trying to create a form that uses ajax to create a new user. All the other fields work, besides the ImageField. I don't get a error when submitting, but the image will still not save. Github Repo: https://github.com/VijaySGill/matching-app urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('matchingapp/', include('matchingapp.urls')), path('admin/', admin.site.urls), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=6, blank=False) dateOfBirth = models.DateField(null=True, blank=False) bio = models.TextField(max_length=500, blank=True) profileImage = models.ImageField(upload_to="profileimage", blank=True, null=True) hobby = models.ManyToManyField(Hobby, blank=False) views.py @csrf_exempt def registerUser(request): ... image = ImageUploadForm(request.POST, request.FILES, instance=newUser) if image.is_valid(): userprofile = image.save(commit=False) userprofile.user = request.user userprofile.save() ... return JsonResponse(data, safe=False) register.html $('form').on('submit',function(e){ e.preventDefault(); ... var fd = new FormData($("#profileImage").get(0)); fd.append("username", $("#username").val()); fd.append("email", $("#email").val()); fd.append("password", $("#password").val()); fd.append("firstName", $("#firstName").val()); fd.append("lastName", $("#lastName").val()); fd.append("gender", gender); fd.append("dateOfBirth", dob); fd.append("hobbies", JSON.stringify(selectedHobbies)); if($("#password").val() == $("#confirmPassword").val()){ $.ajax({ type:'POST', url: '/matchingapp/registerUser/', processData: false, contentType: false, data: fd, ... }); forms.py class ImageUploadForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profileImage',) -
How to collect form data from django and pass it to xgboost model for prediction
I have a model that I want to use for predictions which I have loaded using pickle and I have a form created in using django. But when a user submits the form I want it to be in store it in a csv format in a variable so I can perform Xgboost prediction on every form the user fills and after it outputs the prediction. COuld it be its not getting any input. New to this from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name views.py from django.shortcuts import render from .models import Applicant from .forms import Applicant_form from django.views.generic import ListView, CreateView, UpdateView from django.core.cache import cache import xgboost as xgb import pickle from sklearn.preprocessing import LabelEncoder class CreateMyModelView(CreateView): model = Applicant form_class = Applicant_form template_name = 'loan/index.html' success_url = '/loan/results' context_object_name = 'name' class … -
Django-rest-framework and django-rest-framework-jwt APIViews and validation Authorization headers
I'm using DRF and DRF-jwt to secure my APIs. Currently I have some CBV written like this class Organization(APIView): permission_classes = (IsAuthenticated,) @method_decorator(csrf_exempt, name='dispatch') class OfficeVisitsOverview(APIView): def post(self, request, *args, **kwargs): cursor = connection.cursor() (before, today) = getDateRange() cursor.execute("SELECT format(COUNT(*), 'N0') \ FROM Medi_OfficeVisit \ WHERE ( cast(VisitDate as date) BETWEEN '{0}' AND '{1}' ) \ ".format(before, today)) data = dictfetchall(cursor) connection.close() return JsonResponse({"numberOfOVs": data[0][""]}) From my understanding the APIView and the permission class IsAuthenticated makes sure that theres an Authorization token being sent with the request header. How can you be sure that no one has modified the JWT? How do i know that the Secret_Token in my Django app is being used every time to decode/encode/verify/validate the JWT that is being received/sent with every request? Is this enough security for my APIs to be opened to the public? -
Template rest one day from the date
In my view.py I obtain a date from my MSSQL database in this format 2018-12-06 00:00:00.000 so I pass that value as context like datedb and in my html page I render it like this {{datedb|date:"c"}} but it shows the date with one day less like this: 2018-12-05T18:00:00-06:00 Is the 06 not the 05 day. why is this happening? how can I show the right date? -
Convert datetime object inside Django ORM query
I want to filter queryset by year taken from datetime object, but using methods is not allowed with keywords. Thus, the following will raise an error: a = Activity.objects.filter(start_date.year=2018) Is there any other way to do this? -
Django Form - toggle field existence dynamically
Python 2.7.8 and Django==1.4.2 (Legacy app) I am having a few questions regarding the following form and view: class FormA(Form): field_a = CharField() def __init__(self, *args, **kwargs): if kwargs['initial']['test']: self.base_fields['field_b'] = CharField() super(FormA, self).__init__(*args, **kwargs) class ViewA(FormView): template_name = 'test form_class = FormA def get_initial(self): initial = super(ViewA, self).get_initial() initial['test'] = self.request.GET.get('test') I am trying to add a new field dynamically (based on the query param in this example). If a request with the query param test evaluating to True is made first, field_b will be included on FormA. But for all consecutive requests (even if test evaluates to False), FormA is still having field_b. The fix for this is to pop/del the field_b from self.base_fields and then evaluate the test variable. def __init__(self, *args, **kwargs): self.base_fields.pop('field_b', 0) if kwargs['initial']['test']: self.base_fields['field_b'] = CharField() super(FormA, self).__init__(*args, **kwargs) It seems like, the base_fields dict is being persisted across multiple requests. I have few questions regarding this: 1) Why is the base_fields dict not getting re-initiated on every request? 2) Is there a better solution to solve this issue instead of performing pop/del on base_fields? 3) If there is no other solution, does pop/del lead to a race condition? (If both the requests … -
How to pass json to render_to_response
I am trying to pass a json file through render_to_response to the front end. The front end is not a django template, its coded in JS, HTML etc. I am getting some weird error. Can anybody help me with that. I am attaching the code and the traceback. return render_to_response('ModelView.html', json.dumps(newDict)) Traceback (most recent call last): File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\PythonWorkspace\ScApp\ScApp2\views.py", line 78, in ScorecardApp20 return render_to_response('ModelView.html', json.dumps(newDict)) File "C:\Users\kxc89\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 27, in render_to_response content = loader.render_to_string(template_name, context, using=using) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 274, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than str. -
How to prevent Django ModelAdmin from stripping whitespaces?
so I've defined readonly_fields in Django ModelAdmin with a callable which looks like this: class TestAdmin(admin.ModelAdmin): readonly_fields = ("test_field_with_whitespace",) def test_field_with_whitespace(self, obj): return ' Hello World' In the corresponding admin view the readonly field is shown as "Hello World" - so without the whitespaces. What can I do to show the whitespaces? -
Where do django templates load tags from?
I have forked some django-oscar apps to introduce my own models as per the documentation on how to do so, and I am currently customizine a website template consisting of static HTML to work with django, and to replace the default django-oscar store. django-oscar has a product model with a field category. I have added a collection model which contains products, and products now has a foreignkey to my collections model. When looking at the django-oscar default templates to see how they work and modify the template I am working on to work in a similar fashion, I see the following: {% load basket_tags %} {% load category_tags %} {% load product_tags %} and {% category_tree as tree_categories %} {% if tree_categories %} My question is, how and where is category_tags and category_tree defined? I would like to define something similar, ideally to get a list of collections shown on the page, and to take the name of a collection to be the title of my page. -
vscode doesn't recognized my django module app. Warning from vscode
I installed some extensions in Visual Studio Code for develop in Django. My only problem is when I'm trying to do this; import views from my_app from my_app_name import views I received a warning from Visual Studio Code. If a typed like this; from . import views I don't received any warning! But a would prefer the other form above. I have python 3.x installed on my laptop. I have Anaconda environment created. I have some extensions installed (Python, Django, Pylint,...) Note: My project run well because is only a warning but I would prefer that warning disappear. -
Django - How to display all items inside a Object
I have a Profile Object which has a many to many reationship with a Hobbies object. A profile is used for creating a User. Each User can also have a load of hobbies that are predefined. What I want to do is let Users pick some hobbies they are interested in. However, I am not sure how to display all these Hobbies and let Users pick them on the actual display. Here is the code: TYPES = ( ("Football", "Football"), ("Cricket", "Cricket"), ("Swimming", "Swimming"), ("Cycling", "Cycling") ) class Hobby(models.Model): myfield = MultiSelectField(choices = TYPES) And the User : class Profile(models.Model): email = models.CharField(max_length=200) hobbies = models.ManyToManyField(Hobby) And the HTML code I use is here: <span class="fieldname">Hobbies</span> {% for hobby in all_hobbies %} <input type="checkbox" name={{hobby}} value={{hobby}}> {{hobby}}<br> {% endfor %} However this only displays What I want it to display is all the hobbies with the choices, instead of the whole Object. I am not sure how to do this and would appreciate any help. -
Pass data from View to APIView
I'm currently trying to load dynamically a graph on my website using graphjs. What I want to do is to update data by choosing a time range or a specific datatype. I want it to be more flexible and only have two views; one for rendering the graph and other to return pertinent data. I think my date widget will pass data through HomeView with a post method. How can I pass date information to GenericDataView ? Or maybe there is an other way to do this kind of thing. For now I got something like : class HomeView(View): def get(self,request,*args,**kwargs): return render(request,'charts/charts.html') class GenericDataView(APIView): def get(self,request,*args,**kwargs): selected_data = getDataFromTimeRange() if selected_data is not None: return Response(selected_data) def getDataFromTimeRange(): // do things return data; In urls.py : urlpatterns = [ path('', views.HomeView.as_view(), name='homeView'), path('chart', views.GenericDataView.as_view(), name='api-data'), ] And in charts.hmtl : <div class="chart-container" url-endpoint='{% url "api-data" %}' style="position: relative"> <canvas id="myChart"></canvas> </div> -
Django Models - How do you add subtype choice when user selects choice?
I'm working on a project where they have various job types that I've tackled with CHOICES, however, I want to add conditionals for WHEN job type 1 is chosen, SUBTYPES x-y become choices. I am having trouble with the syntax of how you would do that. I've included my pseudocode below... I appreciate any help! from django.db import models class User(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Job(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='jobs') JOB_CHOICES = ( ('carpentry', 'Carpentry'), ('cleaning', 'Cleaning'), ('electrician', 'Electrician'), ('handyman', 'Handyman'), ('hvac', 'HVAC'), ('painting', 'Painting'), ('pest', 'Pest'), ('plumbing', 'Plumbing'), ('roofing', 'Roofing'), ('property', 'Property'), ) jobType = models.CharField(max_length=30, choices=JOB_CHOICES, default='handyman') # If JobType = Carpentry: # CARPENTRY_CHOICES = ( # ('trim', 'trim') # ('sheetrock', 'Sheetrock') # ('windows', 'Windows') # ('doors', 'Doors') # ('cabinets and shelving', 'Cabinets and Shelving') # ('other', 'Other') # ) # jobType = models.CharField(max_length=30, choices=CARPENTRY_CHOICES, default='other') def __str__(self): return self.name Django Models Django Serializer /api editor -
Django : go back to correct paginator page
I have simple blog app that is using paginator for listing articles. I want to be able to add button in article detail page that will direct user to same page that this article is on. I want to take slug from current url and send it to paginator so that it directs user to ?page=X where article is on. I checked paginator docs and didn't find any info on how to retrieve page number of specific object. my views: def blog(request): posts = Article.objects.all() paginator = Paginator(posts, 3) page = request.GET.get('page') posts = paginator.get_page(page) return render(request,'blog.html',{'posts':posts}) def article_id(request,slug): articleid = Article.objects.get(slug=slug) return render(request, 'blogid.html', {'article':articleid}) my urls: urlpatterns = [ url(r'^$', views.blog, name = 'blog'), url(r'^(?P<slug>[\w-]+)/$', views.article_id, name = 'article_id'), ] -
How to add .html suffix in wagtail
The wagtail url only accept slug type, no '.' acceptable. Can I add suffix like ".html" at end of url, like "/faq.html" instead of "/faq/"? -
One table filter is working fine for me but ,here i need to filter two tables filter in django which is not working
models.py: class Department(models.Model): department_id = models.AutoField(primary_key=True) department_n_key = models.CharField(max_length=30,blank=True,unique=True) hospital_short_name = models.CharField(max_length=20) department_name = models.CharField(max_length=50) class EmployeesMaster(models.Model): employee_id = models.AutoField(primary_key=True) employee_n_key = models.CharField(max_length=30,blank=True,unique=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) gender = models.CharField(max_length=12, blank=True, null=True) class PatientMaster(models.Model): patient_id = models.AutoField(primary_key=True) patient_n_key = models.CharField(max_length=30,blank=True,unique=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) age = models.IntegerField(blank=True, null=True) views.py i need to apply this in django: SELECT * FROM appointment_master WHERE patient_type='something' andappointment_master.department_n_key IN (SELECT department.department_n_key FROM department WHERE department.department_name='something') help somebody to apply this in django -
Sending GET request for an IP address
I need to send a request to a web server of mine to start a stream. The web server is located at 0.0.0.0 (of course I can change the address). How can I send a "GET" request to that server? I already tried using httplib or urllib2 or 3 and they seem not to work with IP address. Note: I know that a local DNS server will map the address to a url, but that is not the goal to set up the server every time I want to execute the code in a new network. Thank a lot. -
Out of memory issue with celery and redis - need help tuning celery
I have a django 2 app that uploads 1 to many photographs (~3-4 MB per image), and uses face_recognition to find the face locations and encoding. The images and created thumbnails are saved to the file system and the data in a mysql database. The app works, except that uploading and finding 16 faces in 3 photos takes about 2 min and uses about 6.5 GB of RAM and no swap (my Ubuntu 18.04 system has a total of 16 GB of RAM and runs with about 8 GB of free memory and 1 GB of swap.) When I use celery (v 4.2.1) and redis (v 2.10.6) and redis-server (v 4.0.9) to offload the face recognition from my django app, the celery tasks run out of memory and the workers are killed before they finish There is 1 celery task per photo for face recognition and django handles the file uploading, thumbnail creation and db writingfor the three photos. Usually 1 task will finish, but not always. I even added exponential retries for the celery tasks, but that did not help. Looking at top during the celery face recognition, I noticed that the amount of free RAM stayed around 6 … -
json loads taking unusually long time while running inside kubernetes pod
I have a http django server deployed through docker container in a kubernetes cluster. Issue is - json.loads in post request is taking too much time(~400ms) for 50Kb Json only. I tried the json.loads from shell_plus inside the pod, it is taking normal timing(<1ms). Also same django application is taking normal time in my local setup. What could be issue, that with django application same process is taking too much long inside pod ? How to debug such issue ? I am logging json load time like this - t1 = datetime.datetime.now() request_json = json.loads(request.body) print("time taken by json loads is {}".format(datetime.datetime.now() - t1)) Server configuration - django application via gunicorn server inside kubernetes pod Tried - Increasing CPU utilisation, memory utilisation different json parsers like (json and ujson), tried cpickle as well. -
Cannot upload image to MEDIA_ROOT using Mongoengine ImageField
I'm trying to upload images using Mongoengine ImageField. But after uploading a test image,I got page not found by visiting http://127.x.x.x:xxxx/media/testimage.png. "/Users/xxx/Documents/basedir/media/testimage.png" does not exist myproject/settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') myproject/myapp/models.py from mongoengine import Document, ImageField class Image(Document): image = ImageField(upload_to="") filename = fields.StringField() myproject/urls.py from django.conf import settings urlpatterns = [ #bla ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What did I do wrong? -
Django - Page not found 404 but urls are defined?
Im trying to get from my test site to the results site after getting some inputs by a form but im getting this Error: Using the URLconf defined in UnserProjekt.urls, Django tried these URL patterns, in this order: 1. admin/ 2. test/ [name='ctest'] 3. test/ [name='results'] 4. instruction/ 5. 6. home/ 7. ^static\/(?P<path>.*)$ The current path, test/ctest, didn't match any of these. Why doesnt it work? If you need my views etc. just ask :) -
Error:inconsistent use of tabs and spaces in indentation
i have a model about. class About(models.Model): displayname=models.CharField(max_length=50) email=models.EmailField(max_length=70) website=models.CharField(max_length=200) photo=models.FileField(upload_to='uploaded_image') des=models.TextField() def __str__(self): return self.name it's giving me above error in this line email=models.EmailField(max_length=70) -
Change label on required select date widget in django
So I want to change the label on my select date widget on django, preferably to the current date, but even just saying "Month" "Year" etc would suffice. I dont want it to just say "January 1 1980" as is the default. I know that to use the empty_label in my widget, my field has to be blank, or not required, in my model. However, my field is required, but I want the field to match another non-required widget. Here is my form code: class AnimalForm(forms.ModelForm): class Meta: model = Animal fields = ['animal_id','species_strain','dob', 'dod', 'sex', 'source', 'parents', 'labloc', 'notes'] widgets ={ "dod":forms.SelectDateWidget(years=range(1980,2050), empty_label=("Year", "Month", "Day")), "dob":forms.SelectDateWidget(years=range(1980,2050), empty_label=("Year", "Month", "Day")), } For clarification, dob is required while dod is not. But I want them to at least look the same on the webpage. If possible, I would LOVE to make the default value the current date, but I need to be able to at least edit the fields first. So how can I do this? I've tried googling it to no avail. Thank you!