Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: a modelChoiceField depend on another modelChoiceField
i have two ModelChoiceFields that are populated with database : t1=MyModelChoiceField1(queryset=operation_Bancaire.objects.all(),to_field_name='type_tiers',required=False) t2=MyModelChoiceField2(queryset=operation_Bancaire.objects.all(),required=False) i need to let the t2 depends on t1 . for example : if i choose value1 in t1 , t2 shows only values filtred by the value1 chooses in the first ModelChoiceField t1 i searched a lot about this and found some information that Ajax would help me to do so. but i'm not sure if it will let me control my ModelChoiceFields as i want specially that my ChoiceFields are populated from database, Because i have never worked with Ajax. Any Help please so i can be right oriented to achieve what i need. Thank You. -
django queryset api - using values method with a list of fields
I would like to make a query to a Django Model, but I do not know the fields to retrieve in advance. If I happen to know them and their number, I would do MyModel.objects.values('field1', 'field2') Indeed, I noticed that the values method takes optional positional arguments, *fields, as specified in the API reference. Therefore, I thought of making a function, which takes *fields arguments and then using such args for my query. The wrapper would look like this: def get_values(self, *fields): return MyModel.objects.values(fields) However, I get an AttributeError: 'tuple' object has no attribute 'split' as the QuerySet API does not like my tuple. How could I work it out? -
Object of type 'TypeError' is not JSON serializable
I try to build api with django rest framework And i got Object of type 'TypeError' is not JSON serializable what should i do to fix. Here's my view.py class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer def list(self, request, **kwargs): try: nba = query_nba_by_args(**request.query_params) serializer = NewsSerializer(nba['items'], many=True) result = dict() result['data'] = serializer.data result['draw'] = nba['draw'] result['recordsTotal'] = nba['total'] result['recordsFiltered'] = nba['count'] return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None) except Exception as e: return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None) -
Django dynamic form
I'm now facing a bit more challenging problem. I would like to dynamically create a form. The user should be able to select the component type, which could be a VALVE in which case the user should specify the Kv value. Or the user could select the PIPE component type in which case the user should specify the inner diameter and length of the pipe. I would think I would need at least three models: COMPONENT_TYPE_CHOICES = ( (1, 'k_v'), (2, 'pipe') ) class Component(models.Model): circuit = models.ForeignKey('circuit.Circuit', related_name='components', on_delete=models.CASCADE) component_type = models.IntegerField(default=1, choices = COMPONENT_TYPE_CHOICES) component_name = models.CharField(max_length=200) branch_number_collectors = models.IntegerField(default=4) # calculated properties branch_mass_flow_rate = models.FloatField(default=0) pressure_loss = models.FloatField(default=0) And two models which inherit from the Component model i.e.: class KvComponent(Component): k_v = models.FloatField(default=1) class PipeComponent(Component): DI = models.FloatField(default=0.025) length = models.FloatField(default=1) # calculated properties velocity = models.FloatField(default=0) reynolds = models.FloatField(default=0) friction_coefficient = models.FloatField(default=0) So far so good but how to go about specifying the Django-forms and views? Is this possible? An example would be very helpfull. -
How to initialize repeating tasks using Django Background Tasks?
I'm working on a django application which reads csv file from dropbox, parse data and store it in database. For this purpose I need background task which checks if the file is modified or changed(updated) and then updates database. I've tried 'Celery' but failed to configure it with django. Then I find django-background-tasks which is quite simpler than celery to configure. My question here is how to initialize repeating tasks? It is described in documentation but I'm unable to find any example which explains how to use repeat, repeat_until or other constants mentioned in documentation. can anyone explain the following with examples please? notify_user(user.id, repeat=<number of seconds>, repeat_until=<datetime or None>) repeat is given in seconds. The following constants are provided: Task.NEVER (default), Task.HOURLY, Task.DAILY, Task.WEEKLY, Task.EVERY_2_WEEKS, Task.EVERY_4_WEEKS. -
Unable to call Django REST API from within the same AWS EC2 Linux machine
I am working on a Django REST Framework web application, for that I have a Django server running in an AWS EC2 Linux box at a particular IP:PORT. There are URLs (APIs) which I can call for specific functionalities. In Windows machine as well as in other local Linux machine (not AWS EC2) I am able to call those APIs successfully and getting the desired results perfectly. But the problem is when I am trying to call the APIs from within the same EC2 Linux box. A simple code I wrote to test the call of one API from the same AWS EC2 Linux box: import requests vURL = 'http://<ipaddress>:<port>/myapi/' vSession = requests.Session() vSession.headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} vResponse = vSession.get(vURL) if vResponse.status_code == 200: print('JSON: ', vResponse.json()) else: print('GET Failed: ', vResponse) vSession.close() This script is returning GET Failed: <Response [403]>. In one thing I am sure that there is no authentication related issues in the EC2 instance because using this same script I got actual response in other local Linux machines (not AWS EC2) and also in Windows machine. It seems that the calling of the API (which includes the same IP:PORT of the same AWS EC2 … -
GeoDjango vary geometry type in model/serializer
I try to make some raster statistics based on Django and rasterstats lib. User requests geojson and in the response I should also provide geojson. Geometry should be stored in database model. For now I have things working using models.PolygonField, but would like add to that other geometry types. I am using django-rest-framework-gis models.py class CalculateLocation(Base): id = models.AutoField(primary_key=True) otherProperties = models.CharField(max_length=2000) geometry = models.PolygonField(blank=True) min = models.CharField(blank=True, max_length=20) max = models.CharField(blank=True, max_length=20) mean = models.CharField(blank=True, max_length=20) serializers.py class CalculateLocationSerializer(GeoFeatureModelSerializer): class Meta: model = CalculateLocation geo_field = "geometry" fields = ( 'id', 'otherProperties', 'min', 'max', 'mean' ) How can I store and serialize/deserialize vary geometry type in one field, for example Point, Polygon, Multipolygon etc.? -
Best way to introspect an object in django templates?
We can see the attributes and methods of an object by using dir(object_name) in django views in the views.py file. I want to introspect an object in django template in this case the variable message. {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %} What is the best way to do that? Thanks in advance. Regards. -
how to make front end and back end for the below python code using django
print("Category1 : Labour Charges") print("") print("") labourpay=float(input("Labour pay : ")) labour=[ ] labourpresent=[ ] labourcharge=[ ] counts=int(input("Enter no of labours :")) for i in range(counts): labourname=input("labour name : ") attendence=float(input("Attendence 1 or 0 :")) labourcharges=(attendence*labourpay) labour.append(labourname) labourpresent.append(attendence) labourcharge.append(labourcharges) totalLabourcharge=sum(labourcharge) labour.append(" ") labourpresent.append("totalcost ") labourcharge.append(totalLabourcharge) import pandas as pd attendancelist=pd.DataFrame({"labour":labour, "attendance":labourpresent, "Charges":labourcharge}) attendancelist[["labour","attendance","Charges"]] -
Deploying Django with Daphne to Heroku: App crashes--won't read proper ENV vars
I've deployed my app onto Heroku using Daphne as my server. The Daphne process will start, read through my config.production settings, output indication that it's searching for my ENV vars as listed in settings, then exit with status 0. The status 0 means that it thinks it was successful, but then I'll get a 2018-03-28T12:46:13.544776+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=paira.herokuapp.com request_id=d9518744-9b5b-4475-b39c-d55a4036fd4b fwd="124.56.195.112" dyno= connect= service= status=503 bytes= protocol=https saying that the app crashed. It will not open. This is the Daphne command I'm running: daphne -b 0.0.0.0:$PORT config.asgi:application -v2 Here's the output: 2018-03-28T04:36:00.894609+00:00 heroku[web.1]: Starting process with command `/bin/sh -c daphne\ -b\ 0.0.0.0:\19859\ config.asgi:application\ -v2` 2018-03-28T04:36:02.946809+00:00 app[web.1]: 2018-03-28 04:36:02,946 DEBUG Importing BmpImagePlugin 2018-03-28T04:36:02.950317+00:00 app[web.1]: 2018-03-28 04:36:02,950 DEBUG Importing BufrStubImagePlugin ... 2018-03-28T04:36:03.092570+00:00 app[web.1]: 2018-03-28 04:36:03,092 DEBUG get 'DJANGO_READ_DOT_ENV_FILE' casted as '<class 'bool'>' with default 'False' 2018-03-28T04:36:03.092881+00:00 app[web.1]: 2018-03-28 04:36:03,092 DEBUG Read environment variables from: /usr/src/app/.env 2018-03-28T04:36:03.094088+00:00 app[web.1]: 2018-03-28 04:36:03,093 DEBUG get 'DJANGO_DEBUG' casted as '<class 'bool'>' with default 'False' 2018-03-28T04:36:03.096322+00:00 app[web.1]: 2018-03-28 04:36:03,094 DEBUG get 'DATABASE_URL' casted as 'None' with default '<NoValue>' 2018-03-28T04:36:03.096324+00:00 app[web.1]: 2018-03-28 04:36:03,094 DEBUG get 'DJANGO_EMAIL_BACKEND' casted as 'None' with default 'django.core.mail.backends.smtp.EmailBackend' ... According to this output, it imports lots of things that seem to … -
Django remove field from CreateView
I created a CBV of which I want to remove one or more fields, depending on the user. The idea is a jobsite and if the logged in user is a recruiter, than the 'employer' field should stay, otherwise it has to go. This is the forms.py and views.py forms.py class JobCreationForm(forms.ModelForm): class Meta: model = Job # exclude = ['posted', 'provider', 'ext_id'] fields = ('title', 'job_desc', 'agency_name', 'employer', 'contact_name', ) views.py class JobCreateView(LoginRequiredMixin, CreateView): template_name = 'job/job.html' form_class = JobCreationForm success_url = '/' def get_context_data(self, **kwargs): context = super(JobCreateView, self).get_context_data(**kwargs) # import the Customers of this Company self.fields["agency_name"].remove() recruiter = self.request.user self.fields["contact_name"].queryset = Profile.objects.filter(user_id = self.request.user) # if the user is a recruiter, delete the employer field. if Company.objects.filter(user_id = self.request.user).values('is_recruiter') == False: pass # self.fields.remove("employer") del self.fields["employer"] return context The current error is "NoneType' object has no attribute 'getitem'". My question: how can I remove a field from the form based on logic? I tried these versions: self.fields["employer"].delete() self.fields.remove("employer") del self.fields["employer"] Any tips? -
How to make a optional Django database filter
I have created a small method that filters data on a form. The problem is that it requires all of them to produce a result. I am creating a selector and want to submit the button at any time. def search(request): goodwithchildren = request.POST['goodwithchildren'] drooling = request.POST['drooling'] coatlength = request.POST['coatlength'] activitylevel = request.POST['activitylevel'] sheddinglevel = request.POST['sheddinglevel'] groominglevel = request.POST['groominglevel'] intelligencelevel = request.POST['intelligencelevel'] size = request.POST['size'] breeds = Breed.objects.filter(good_with_children=goodwithchildren,).filter(drools=drooling).filter(coat_length=coatlength).filter(activity_level=activitylevel).filter(shedding_level=sheddinglevel).filter(grooming_demand=groominglevel).filter(intelligence=intelligencelevel).filter(size=size) return render(request, 'polls/search_results.html',{'breeds': breeds}) Its definitely not the most elegant and most likely not correct but works but want it to be optional in some kind of way -
displaying a user tasks
model.py class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __unicode__(self): return self.user.username class Task(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) titre = models.CharField(max_length=100) date = models.DateField() objectif = models.CharField(max_length=1000) theme = models.CharField(max_length=20) #views.py tasks = Task.objects.filter() return render_to_response('home.html',{'tasks':tasks}) the problem is it display all the tasks in the table but i want to display just the tasks of the user who is logged in how can i do that -
Using DetailView to view UserProfiles
I need help with simple blog site. Where users can write Posts. Each Post writer has to signed in to write a Post. But the reader does not have to be signed in. I am using django DetailView to allow readers to view Profiles of the Post writers. The Profile View will have details of the writers along with other Posts the writer has written. Below are the Details: All this is in the accounts app in my site accounts/views.py: class ProfileView(DetailView): model = User template_name = 'accounts/profile.html' def get_user_profile(self, username): return get_object_or_404(User, pk=username) #I know pk=username is not correct. I am not sure what to put pk=? # I was able to get the writers other posts using the code below. I did not have to show this code for this question. But just to show you that the pk above has to be username. Or Else the code below won't work(I guess) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['post_list'] = Post.objects.filter(user__username__iexact=self.kwargs.get('username')) return context My models are as below accounts/models.py: from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) country = models.CharField(max_length=100) bio = models.TextField(default='', blank=True) profile_image = models.ImageField(default='', blank=True, … -
Understanding Django Class-Based (DetailView and View)
I'm transitioning some Function-Based Views to Class-Based Views in order to make my views more readable. But I am not understanding quite well the use of DetailView and how I can actually integrate it to my code in order to pass a slug into my function. For now, I am using View and passing the slug into my function as below: #urls.py path('preview/<slug:slug>/', views.Preview.as_view(), name='toPreview') #views.py @method_decorator(auth0_login_required, name='dispatch') class Preview(View): template_name = 'authenticated/preview.html' @card_is_chosen def get(self, slug, request, *args, **kwargs): person = get_object_or_404(Person, slug=slug, status=True) ... return render(request, self.template_name, {...}) I'm am also not quite sure if it's the best practice, in case it is then what does DetailView offer? -
transition of authorized users on the site django
How to make sure that when a user is authorized, he immediately went to a certain page. And when he was not authorized, he went to the authorization page. -
Django Logger with User info
I'm just curious. Is it possible to put User info within the formatters info in LOGGING config in setting.py? Right now I just put that info in the message to log but maybe there's a way to set it in formatters argument. This is my LOGGING configuration right now: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '[%(asctime)s] %(levelname)s [%(funcName)s] %(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': BASE_DIR + '/logs/uca_{:%d_%m_%Y}.log'.format(time.now()), 'formatter': 'simple' } }, 'loggers': { 'ucalog': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True } } } I haven't seen anything similar in django's documentation and I think it would be usefull to get records of WHO did WHAT. -
how to generate json data with json array name in django rest framework?
[ { "id": 1, "title": "t-shirt", "description": "this is a good t-shirt", "price": "39.99" }, { "id": 2, "title": "Jeans", "description": "this is a jean", "price": "89.99" } ] This is my json data without array name. I want to get its array name.How can i get it? class productsSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id' , 'title' , 'description','price' ) This is my serializers.py -
#django Cannot use ImageField because Pillow is not installed
i am using python 3.7.0a2 and DJango (2, 0, 2, 'final', 0) in window 10. while i was migratting my project i get the following error: ERRORS: accounts.UserProfile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". then i run the 'pip install Pillow' command and i get the following error: Traceback (most recent call last): File "C:\Users\VIKASV~1\AppData\Local\Temp\pip-build-hfzb5tde\pillow\setup.py", line 792, in zip_safe=not (debug_build() or PLATFORM_MINGW), ) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\command\build_ext.py", line 339, in run self.build_extensions() File "C:\Users\VIKASV~1\AppData\Local\Temp\pip-build-hfzb5tde\pillow\setup.py", line 580, in build_extensions raise RequiredDependencyException(f) main.RequiredDependencyException: zlib During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "C:\Users\VIKASV~1\AppData\Local\Temp\pip-build-hfzb5tde\pillow\setup.py", line 804, in … -
Docker + Django executing external node.js script
I have a problem with executing my node js script. When i run this script normally from command line everything is ok. But when i want to execute that script directly from django it will print error like this: the first line says that you are in the code before that line of code what execute that script. Second is path and is correct as you see. Third and to the error are files in that directory (I was checking if executing commands from command line works) I recall that this django project runs in docker container so i think that error might be there. Here is my line of code where i run that script in my view.py: def prepare_log_img(picture): string_without_header = re.sub('^data:image/.+;base64,', '', picture) img_data = base64.b64decode(string_without_header) filename = SITE_ROOT + "/faceId/logged.png" with open(filename, 'wb') as f: f.write(img_data) os.chdir(SITE_ROOT + "/static/scripts") print("Pred face detection") print(SITE_ROOT + "/static/scripts") print(os.system("ls")) os.system("node face-detection.js logged.png") The last line is that executing. Anyone knows what is the problem? Thank you. -
Customize Django admin template
i tried customizing navbar like this Base_site.html {% block nav-global %} <img class = "brand_img" src = "{% static 'images/ic_launcher.png'%}" width = "50" height = "50" alt = "logo"> {%block branding%} {% endblock %} <div class = "head"> <h1 id = "name">Admin Dashboard</h1> </div> {% endblock %} which looks like this now i try to add header for login page inside {%block branding%} but if i add inside branding block it is displayed in navbar also and if i try to add both image and header in branding block image is displayed login page header. how to add different titles for navbar and login page header? -
django rest API passing several list to URL
Im trying to pass several list to my URL through AJAX for filter purposes in my REST APIVIEW, but I couldn't get it right. i try to print using request.get function as well, but its now printing anything. below is my code : Javascript : a = "/api/dashboard/project_workorder_filter/{{selected_project.id}}/?search_type_list=" + search_type_value.join(',') + "/?parent_list=" + parent_value.join(',') + "/?status_list=" + status_value.join(',') + "/?task_list=" + task_value.join(',') + "/?user_list=" + user_value.join(',') + "/"; console.log(a) content_workorder_filter_json = $.ajax({ type: "GET", url: a, dataType: "application/json", async: false }).responseText; content_workorder_filter = JSON.parse(content_workorder_filter_json); console.log(content_workorder_filter) URl : url(r'^api/dashboard/project_workorder_filter/(?P<project_id>\d+)/(?P<search_type_list>\w{0,1000})/(?P<parent_list>\w{0,1000})/(?P<status_list>\w{0,1000})/(?P<task_list>\w{0,1000})/(?P<user_list>\w{0,1000})/$', api.ProjectWorkorderFilterAPI.as_view(), name='project_workorder_filter'), API.py class ProjectWorkorderFilterAPI(APIView): def get(self, request, project_id, search_type_list,format=None): a = request.GET.get('search_type_list') print(a) model_object = WorkOrder.objects.filter(parent_project_content__project=project_id, search_type__id__in=[search_type_list], parent_project_content__parent__in=[parent_list], status__id__in=[status_list], task__id__in=[task_list], assign_to__id__in=[user_list] ) serializer = ProjectWorkorderSerializer(model_object, many=True) return Response(serializer.data) -
Getting error when run django server
I am trying to make my app using django. I have set my setting.py file aas below mention code. when I have tried to run server getting below mentioned error, to resolve this I have tried all things like removed django folder and other thing but the error is still not resolved. error in terminal Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fc0902866a8> Traceback (most recent call last): File "/home/ajay/.local/lib/python3.5/site-packages/django/template/utils.py", line 64, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ajay/.local/lib/python3.5/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ajay/.local/lib/python3.5/site-packages/django/templatetags/future.py", line 4, in <module> from django.utils.deprecation import RemovedInDjango110Warning ImportError: cannot import name 'RemovedInDjango110Warning' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ajay/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ajay/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in … -
Django jobs board post
I'm new to Django and am learning by creating a website, as I find the django docs and most tutorials to be fair too technical for me to read. I'm trying to create a webpage within my site that would post jobs as they become available, for a user base of employees to search through and accept jobs as they wish. The problem is I'm struggling to conceptualise it in Django. For example, could I write a class-based view: class JobPost(generic.CreateView): # more job specific relevant stuff goes here #... template_name = 'jobpost.html' jobpost.html would then be a small section of code that gets included onto a larger webpage (jobsboard.html). Is this the right track to be moving down? I've looked everywhere for an answer/clues to how to do this. I find Django has very little in the way of beginner-friendly, jargon-free help and tutorials, and it's hard even to formulate the google search that would yield results. Even just a link to put me on the right track would be a fantastic answer to my question. Thanks for your patience! -
How to keep from manually changing google token in django?
How to make google token live longer so that I don't need to manually change it every time in my django code !?