Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelForm with user-defined fields and choices from foreign keys
In my app, I have Study as the central model. Studys have multiple Strata, and each Strata has multiple Levels. Users create Allocations for a study by choosing one level for each Strata linked to that study, like: class Study(models.Model): name = models.CharField(max_length=100) class Stratum(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='strata') name = models.CharField(max_length=100) class Level(models.Model): stratum = models.ForeignKey(Stratum, on_delete=models.CASCADE, related_name='levels') label = models.CharField(max_length=100) class Allocation(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='allocations') code = models.CharField(blank=False, max_length=100) levels = models.ManyToManyField(Level, related_name='allocations') In order to create fields for the allocation creation form, I am currently finding all the Strata and associated levels in the form's constructor, but hiding the strata as the user doesn't interact with them: class AllocationForm(forms.ModelForm): class Meta: model = Allocation fields = ('code',) def __init__(self, *args, **kwargs): study = kwargs.pop('study') super(AllocationForm, self).__init__(*args, **kwargs) strata = Stratum.objects.filter(study=study) for stratum in strata: self.fields[stratum.name] = forms.IntegerField( widget=forms.HiddenInput() ) self.fields[stratum.name].initial = stratum.id self.fields[stratum.name].disabled = True self.fields[stratum.name + '_level'] = forms.ModelChoiceField( queryset=Level.objects.filter(stratum=stratum) ) Is this a safe and sensible way to attach the associated objects to the form? I worry that I will lose track of the connection between Strata and Levels when trying to create the allocation. Is this something that would be better … -
django multi user request(a,b concurrent request)
I make django rest api. ( window server ) this api receive json data from user. and return json data for request user. I test A and B two user same time request. A receive B result data and B can not receive any data. how to solve please help me @csrf_exempt def ex(request, question_id): received_json_data = json.loads(request.body.decode("utf-8")) return JsonResponse(json.loads(returnData), safe=False) -
Django - create or delete object
I am wondering what is the best way of creating (if it doesn't exist) or deleting (if it does exist) an object in Django. I know I can do something like this: if Like.objects.filter(user=request.user, post=post).exists(): Like.objects.filter(user=request.user, post=post).delete() else: Like.objects.create(user=request.user, post=post) Is there a better way, like for instance the get_or_create method that Django provides? -
Django modelformset_factory does not save to database
The issue is that Django modelformset_factory does not save to database when inputs are inserted into the forms. It appears that only else statement is reached after forms are submitted for processing. Clearly the issue is with part in views.py where if 'name' in request.POST: then do sth. Advise how to solve it would be highly appreciated. Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions model_names = ['Form1', 'Form2'] def get_assumptions(request): if request.method == 'POST' and 'name' in request.POST: formset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if formset.is_valid(): print('valid form') for form in formset: if form.is_valid(): print('in for loop after valid form1') assumptions = form.save(commit='False') assumptions.Name = 'name' assumptions.save() else: formset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) print('reached else') return render(request, 'assumptions.html', {'formset': formset, 'model_names': model_names}) models.py from django.db import models from django.forms import ModelForm class Assumptions(models.Model): Worst_Case = models.FloatField(null=True, blank=True, default=None) Grey_Case = models.FloatField(null=True, blank=True, default=None) Red_Case = models.FloatField(null=True, blank=True, default=None) Blue_Case = models.FloatField(null=True, blank=True, default=None) Green_Case = models.FloatField(null=True, blank=True, default=None) Best_Case = models.FloatField(null=True, blank=True, default=None) Name = models.TextField(null=True, blank=True, default=None) forms.py from django import forms from django.forms import modelformset_factory, ModelForm from .models import Assumptions class AssumptionsForm(ModelForm): class Meta: model = Assumptions fields … -
Inherent python abstract base class in django
I would like to make an generic module in python which uses data from a Django model, and use typing to document the interface. The module should be independent of the Django model. How should this by done in a pythonic way? I'm thinking of using ABC class, the independent python file should then be something like (shape.py): from abc import ABC class Shape(ABC): @property @abstractmethod def height(self) -> float: pass @property @abstractmethod def area(self) -> float: pass class VolumeCalculation: def __init__(self, shape: Shape) -> None: self.shape = shape def volume(self) -> float return self.shape.area*self.shape.height While the django model is defined in another file: from django.db import models from shape import Shape class Box(models.Model, Shape): height= models.FloatField('height') area = models.FloatField('area') When I do this I get the following error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Alternatively I can remove the base class and construct VolumeCalculation with the needed parameters from Shape. But as the real object contains many parameters the list becomes quite long. -
Django Case When Select
I use raw SQL as subquery to achieve the result. But if I make filtering by annotated field, it throws an error connected to wrong (or not stated) alias like this: django.db.utils.ProgrammingError: invalid reference to FROM-clause entry for table "catalog_good" HINT: Perhaps you meant to reference the table alias "v0". I want to know if there is an opportunity to make CASE-WHEN-SELECT by Django. This is a part of code I would like to improve by Django classes: CASE WHEN ( SELECT (score - "catalog_tag"."weight") ^ 2 FROM "catalog_tag" WHERE "catalog_tag"."word" = 'chair' AND "catalog_tag"."good_id" = "catalog_good"."id" ) IS NOT NULL THEN ( SELECT (score - "catalog_tag"."weight") ^ 2 FROM "catalog_tag" WHERE "catalog_tag"."word" = 'chair' AND "catalog_tag"."good_id" = "catalog_good"."id" ) ELSE (score ^ 2) END Thanks in advance. -
Trying to make Check reCaptcha Mixin for login form - django
I am trying to make a mixin which will check for valid reCaptcha. I am new in django, I tried to make it with what I know It is checking correctly but problem is with Permission. Instead of redirecting again to login view it is redirecting to Dashboard, means success page. Have a look at mixin. class CheckRecaptchaMixin(AccessMixin): error_message = 'Invalid reCAPTCHA. Please try again.' def get_error_message(self): return self.error_message def handle_not_valid_recaptcha(self): message = self.get_error_message() if self.raise_exception: raise PermissionDenied(message) messages.error(self.request, message) print('login redirect') return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) def dispatch(self,request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: print('This is success') request.recaptcha_is_valid = True else: print('This is error') request.recaptcha_is_valid = False self.handle_not_valid_recaptcha() return super(CheckRecaptchaMixin, self).dispatch(request,*args, **kwargs) In my views.py class UserLoginView(CheckRecaptchaMixin,LoginView): template_name = 'accounts/login.html' redirect_field_name='next' When reCaptcha is correct it is printing This is success only and when reCaptcha is incorrect it is printing This is error and login redirect. This means it is handling reCaptcha successfully but not redirecting to login page, one more important thing to notice, on my logout page I see error_message that I have defined in … -
Unexpected Django Error [Django 1.5.1]
I am just trying to Migrate on of my Django project from version 1.4.22 to 1.5.1. It all goes well, but when I tried to run the server it started throwing the following error: from django.http import HttpResponseRedirectBase, HttpResponse ImportError: cannot import name HttpResponseRedirectBase But the thing is this line is not being used anywhere in my code. Note: I am running the project on a virtual environment. and here is the complete error message: from django_ajax.encoder import serialize_to_json File "/home/dev31/.virtualenvs/AcornAccounting/local/lib/python2.7/site-packages/django_ajax/encoder.py", line 8, in from django.http import HttpResponseRedirectBase, HttpResponse ImportError: cannot import name HttpResponseRedirectBase I tried to resolve this error but nothing helped. Please help me to sort out this issue. Thanks. -
Python Process getting Killed Suddenly
I am using Django UI with wsgi, apache, gunicorn. The flow of my UI is I submit the details to UI and a python process is started for each submission of details. The above-created processes are getting killed abruptly. Unable to get PPID or anything. Is this issue seen before or is there a way to debug it -
Selenium and Chromedriver Error on ubuntu
I use the Ubuntu app on Windows 10 I ran python3 functional_test.py but I have a provelm like this traceback Traceback (most recent call last): File "functional_test.py", line 3, in browser = webdriver.Chrome('/usr/local/bin/chromedriver') File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 75, in init desired_capabilities=desired_capabilities) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in init self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 320, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist (Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee976b2c3e3b9f335cde7),platform=Linux 4.4.0-17134-Microsoft x86_64) this is functional_test.py from selenium import webdriver browser = webdriver.Chrome('/usr/local/bin/chromedriver') browser.get('http://localhost:8000') assert 'Django' in browser.title -
psycopg2 install returns error : Microsoft Visual C++ 14.0 is required
Im trying to install psycopg2 for postgresql. The following error shows up when i use pip install psycopg2 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools":http://landinghub.visualstudio.com/visual-cpp-build-tools The link seems to be broken. I tried installing Visual C++ and then psycopg2, but i still get the error. What has to be done. Many thanks in advance. -
Extracting torrent information using python django
I have magnet link of torrent,using that magnet link i want to extract all information about that torrent like number of peers ,ip addresses and geographical locations from downloading is done using python or angular. Your help will be appreciated, Thanks in advance. -
Django signals vs channels
I have a Django-based project that I would like to make real-time so I thought of Django channels. However, I am still not sure whether this is the right project to apply Django channels and which part of the project I should apply it. I have a bunch of sensors continuously reading data and saving/updating them into a database in the backend. Data from the database is then passed to the frontend, displayed on a webpage. Data flow: Sensors > Gateway > Backend (database) > Frontend I have implemented Django signals to continuously listen to any updates on the database at the backend, in order to perform some notification functions to the user on the frontend. My Questions 1) In this example, where should I implement Django channels? from sensors to Gateway from gateway to backend (database) from backend to frontend all of the above 2) Django signals vs Django channels -- overlap? It feels like Django signals is doing its job in real-time when it listens to the updates on the database. When it notifies me that there is an update, I'd just call on my bunch of code that performs some notifications I want it to. Isn't this … -
whether worked who in a linking of reactjs + with react-router + django-restframework(for api)
I use async await fetch for an output to the client with backend correct way, or slippery footpath? there is a judgement....? async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/news/?format=json'); const newsList = await res.json(); this.setState({ newsList }); } catch (e) { console.log(e) } } -
How to solve error 405 method not allowed, for django graphql server and react axios in front end
Hi I am having hard time to solve this problem i have django graphql server which running for my local machine port 8000 when i query it in insomnia everything works well but i am integrating with front-end reactjs and axios i am getting error: xhr.js:178 OPTIONS http://127.0.0.1:8000/graphql/ 405 (Method Not Allowed)enter image description here my setting.py from django graphql server my front-end request from reactjs using axios ``javascript export function getProducts(args = {}) { return (dispatch) => { // optionally you can have getState as the second argument dispatch({ type: HOME_GET_PRODUCTS_BEGIN, }); const promise = new Promise((resolve, reject) => { const query = { url: 'http://127.0.0.1:8000/graphql/', method: 'POST', headers: { "Accept": "application/json", 'Content-Type': 'application/json' }, data: { query: `products{ userKey{ id username email password } id title price image } `, }, }; axios(query).then( (res) => { dispatch({ type: HOME_GET_PRODUCTS_SUCCESS, data: res.data, }); resolve(res); }, // Use rejectHandler as the second argument so that render errors won't be caught. (err) => { dispatch({ type: HOME_GET_PRODUCTS_FAILURE, data: { error: err }, }); reject(err); }, ); }); return promise; }; } ``` please i need help -
Django Admin: Show different models to different users
I have two superusers (user1 and user2) and two models (modelA and modelB). In the admin page, I want to show just ModelA to user1, so user1 can only edit ModelA instances but not modelB instances. Similarly, I want to have user2 able to edit modelB instances only. Is there a way to achieve this? -
Why forms.ModelForm loss data from FileField in Django 2.0
I have a CustomForm that extends from forms.ModelForm and use a FileField like this: avatar = forms.FileField(required=False, label="avatar") When I save the model, everything works, and file was saved in directory. But when I re-enter in view (file is over there), and just click in "Save", the file is lost. My views.py is: def edit_user(request): if request.method == "POST": form = CustomForm(request.POST, request.FILES) if form.is_valid(): user= form.save(commit=False) user.save() else: user= User\ .objects\ .get_or_create(user=request.user, defaults={'name':request.user.first_name, 'email':request.user.email}) form = CustomForm(instance=user) return render(request, 'user.html', {'form':form, 'user':user}) I'm using Python 3.6 and Django 2.0 -
Django Deploy Root Url setting
Question 1, When I deploy my website to cloud. i have to setting 'Debug = False' But just index view can load the 'statics', other views always load sub dir static. I check the uwsgi log. Message as follow: [pid: 6505|app: 0|req: 141/141] 117.10.182.55 () {42 vars in 836 bytes} [Fri Jul 01:50:58 2018] GET /search/static/js/bootstrap-datetimepicker.min.js => gene rated 122 bytes in 0 msecs (HTTP/1.1 404) 3 headers in 101 bytes (1 switches on core 0) [pid: 6505|app: 0|req: 142/142] 117.10.182.55 () {42 vars in 792 bytes} [Fri Jul 6 01:50:58 2018] GET /search/static/js/search.js => generated 100 bytes in 0 m secs (HTTP/1.1 404) 3 headers in 101 bytes (1 switches on core 0) I have finish 'collectstatic' to my project/static folder. Here is my setting: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) Follow Is static setting in nginx. location ^~ /static { alias /var/www/erp/src/static/; } Question 2, In one page, while i want to switch to other page the link always include current page. eg when i open a search page ,and click a href link to index. the href will be /search/index/ href link in templete is write as: href=‘{% url 'name' … -
Elasticsearch with Django and Monhoengine
I have a django REST appilication that uses Mongoengine. I want to integrate the application with elasticsearch. I understand that DBs like MySQL, PostGres etc can be integrated with elasticsearch using haystack but how to do it with MongoDB? -
Django template does not output multiple forms and save to modelform
the issue is that template does not output multiple forms and save to Assumptions modelform. I am trying to save input from multiple forms by adding different names from template to Assumptions.Name field in Assumptions model. However, this approach does not work for some reason. Advise how to solve it would be highly appreciated. Thank you in advance. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions def get_assumptions(request): if request.method == 'POST': if 'name' in request.POST: formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) if formset.is_valid(): print('valid form') for form in formset: print('Looping forms') assumptions = form.save(commit='False') assumptions.Name = 'name' assumptions.save() formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) return render(request, 'assumptions.html', {'formset': formset}) assumptions.html {% for name in "AB" %} <div class="form"> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% … -
Django Smart Selects: Dropdown not populating
I've been wanting to implement Django Smart-Selects for dependent dropdowns. I wrote the code as seen on https://github.com/digi604/django-smart-selects But the second field is not populated Here are the Models for the project: # Model: class ObjectName(models.Model): objectName=models.CharField(max_length=100) objFullForm=models.CharField(max_length=100, default='') def __str__(self): return self.objectName class ActionObject(models.Model): objectName=models.ForeignKey(ObjectName,on_delete=models.CASCADE) action=models.CharField(max_length=100) def __str__(self): return self.action class Priority(models.Model): priorityName=models.CharField(max_length=100) priotityScore=models.IntegerField() def __str__(self): return self.priorityName from smart_selects.db_fields import ChainedForeignKey class ActionObjectPriority(models.Model): objectName=models.ForeignKey(ObjectName, on_delete=models.CASCADE) actionName = ChainedForeignKey( ActionObject, chained_field="objectName", chained_model_field="objectName", show_all=False, auto_choose=True, sort=True) priority=models.ForeignKey(Priority, on_delete=models.CASCADE) The Base.html Template: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Base</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> --> {% load static %} <script src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> </head> <body> {% block body %} {% endblock %} </body> </html> Priority Template: {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Add Priority</h1> <form method="POST" class="post-form form-control"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-primary">Save</button> </form> </div> {% endblock %} The Action Field is not populated. Form -
Django list of Models
I just want to ask if there any way that I can query all my models in my views.py ? Like, I want to get all my models created and use it in my views.py. I want to do is I have string to be compar to list of my models names -
Find object in child class from parent class instance in django
Let's say I have a parent class (Products) and child class related by OneToOneField. Now let's say I have a Products instance object. How will I be able to access all the fields of child ? class Products(models.Model): ...... class Child1(models.Model): parent=models.OneToOneField(Products) ...... class Child2(models.Model): parent=models.OneToOneField(Products) ...... Now let product_instance=Products.objects.get(id=id) How can I access child fields without knowing the child class name? -
Find object in child class from parent class instance in django
Let's say I have a parent class (Products) and two children (product1 and product2) related by OneToOneField. Now let's say I have a Products instance object. How can I find if it is a product1 or product2? Also How will I be able to access all the fields of child (product1 or product2 )? Products may have many children later so please help me to find the most efficient way to do this. -
Django / Ajax - How to filter and display result based data query table
I am trying to filter and display data in Django based on the selection made by the user from drop down box. I'm using ajax call to send a request to Django views. When a user selects, for example, masterjabatan, then Ajax will send the 'value' of that selection which is an integer to Django backend to filter data and send it back to frontend. Here is my code: models.py class Masterjabatan(models.Model): jenissistem = models.IntegerField(primary_key=True) isskpd = models.IntegerField() urut = models.IntegerField() urai = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'masterjabatan' unique_together = (('jenissistem', 'isskpd', 'urut'),) def __str__(self): return self.isskpd views.py def masterjabatan(request): jenissistem = request.GET.get('jenissistem', None) isspkd = request.GET.get('id', None) urut = request.GET.get('urut', None) urai = request.GET.get('urai', None) cursor = connection.cursor() cursor.execute("SELECT * FROM masterjabatan where jenissistem='2' and isskpd='0' order by urut asc") jabatan_list = dictfetchall(cursor) data = { 'jenissistem': jenissistem, 'isspkd': isspkd, 'urut': urut, 'urai': urai, 'jabatan_list':jabatan_list } return render(request, 'konfig/masterjabatan.html', data) html template <div class="isi-konten"> <form action="{URL_SAVE}" method="POST" id="myForm" name="myForm"> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 batas-atas" style="margin-bottom:15px;"> <span>Jenis Jabatan</span> <div class="input-group"> <select id="jns_pejabat" name="jns_pejabat" onchange="gantiJenisJBTN(this.value)" style="padding:5px; height:30px;"> <option value="0">PEJABAT SKPD</option> <option value="1">PEJABAT SKPKD</option> </select> <input id="url_tabel" type="hidden" style="display:none;" value="/apbd/konfig/masterjabatan/"> </div> </div> <div style="padding: 15px …