Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LDAP group search Issue
I am trying to implement LDAP in Django. I am able to login using LDAP in Django. But when I am trying to limited access for some particular group, I can not login any more. Here is my code: Settings.py import ldap from django_auth_ldap.config import ldapsearch, GroupOfUniqueNamesType, GroupOfNamesType ,LDAPGroupQuery, PosixGroupType #(I imported many, as I was trying differently) AUTH_LDAP_SERVER_URI = 'ldap://ldap.mydomain.de' AUTH_LDAP_USER_DN_TEMPLATE = 'uid=%(user)s,ou=user,dc=mydomain,dc=de' #AUTH_LDAP_START_TLS = True AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" #AUTH_LDAP_FIND_GROUP_PERMS = True #added for group AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } #ldap AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=My_group_Name, dc=mydomain,dc=de", ldap.SCOPE_SUBTREE, "(objectClass=posixAccount)" ) #AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_GROUP_TYPE = PosixGroupType (name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "cn=My_group_Name, dc=mydomain,dc=de" AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] If I turn off Require_Group, I can login successfully. but if I turn on, error arises. (I am in the group) The log is like search_s('uid=shaondebnath,ou=user,dc=mydomain,dc=de', 0, '(objectClass=*)') returned 1 objects: uid=shaondebnath,ou=user,dc=mydomain,dc=de Caught LDAPError while authenticating shaondebnath: NO_SUCH_OBJECT({'matched': u'dc=mydomain,dc=de', 'desc': u'No such object'},) The information I Have from my Organization is $ conf ['authtype'] = 'authldap'; $ conf ['plugin'] ['authldap'] ['server'] = 'ldap.mydomain.de'; $ conf ['plugin'] ['authldap'] ['usertree'] = 'ou = user, dc = mydomain, dc = … -
How to have PyCharm show the tables in a Django SQLite database?
I'm not very familiar with Django (I've used more Flask, Web.py, and Falcon), and one thing that I'm finding strange is that when I look at the 'Database' tab in PyCharm, I don't see a list of all of the tables that seem to be getting used in the database: If I use python manage.py dbshell to start a sqlite3 session and then type .tables, this is the list of tables that I see: How do I get those tables to be browsable from within the PyCharm database viewer? -
Django LDAP authentication not authenticating to backend
The code runs and i don't exactly know why it isn't working. It doesn't seem to be authenticating the user info to the LDAP backend i have connected to. When i fill out the form it will always return with "inactive user", when i know the user is on the test server. All i want is to just have it recognize that it is a "valid user" I'm running it against a LDAP test server found here http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/ here are the changes i've made in the project: settings.py import ldap from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = "http://ldap.forumsys.com:389/" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch( "cn=read-only-admin,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', ] views.py from django.contrib.auth import authenticate, login from django.shortcuts import render def login_user(request): email = password = "" state = "" if request.POST: email = request.POST.get('email') password = request.POST.get('password') print (email, password) user = authenticate(username=request.POST.get('email'), password=request.POST.get('password')) if user is not None: login(request, user) state = "Valid account" else: state = "Inactive account" return render(request, 'KPI/auth.html', {'state': state, 'email': email}) auth.html <html> <head> <title>Login</title> </head> <body> {{state}} <form action="" method="post"> {% csrf_token %} Email address: <input type="text" name="email" value="{{ … -
Limit the queryset of autocomplete fields in Django
I have a ModelAdmin in Django 2.1.3 like this: class BoxAdmin(admin.ModelAdmin): autocomplete_fields = ['testkit'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'testkit': kwargs['queryset'] = Barcode.objects.exclude(testkit__in=Box.objects.all().values('testkit')) return super().formfield_for_foreignkey(db_field, request, **kwargs) the formfield_for_foreignkey method is written for "traditional" foreign key fields. For the autocomplete field it ensures that an error is displayed when a testkit outside of the queryset is selected. It doesn't however limit the results found in the autocomplete field. The documentation does not mention any restrictions for custom querysets. How can I correctly limit the queryset of the autocomplete field? -
Filter results of One to One Field in Django Admin
First of all, here is the model that I'm trying to restrict: Question class: class Question(models.Model): title = models.CharField( max_length = 200, verbose_name = "Question title") description = models.TextField( verbose_name = "Question description") block = models.ForeignKey( to=Block, null=True, on_delete=models.SET_NULL, verbose_name='Subject part to which this question belongs') timestamp = models.DateTimeField( auto_now_add=True, verbose_name='Date at which the question was added') Poster class that contains the One to One field to Question that I want to restrict: class Poster(models.Model): title = models.CharField( max_length = 200, verbose_name = "The poster's title") description = models.TextField( verbose_name = "The poster's description") authors = models.CharField( max_length = 200, verbose_name = "Authors' names") image = models.ImageField( upload_to = 'images', verbose_name = 'Poster image') block = models.ForeignKey( to = Block, null = True, on_delete = models.SET_NULL, verbose_name = 'The subject part to which the poster belongs') associated_question = models.OneToOneField( Question, null=True, blank=True, on_delete=models.SET_NULL, unique=True, verbose_name='Question associated to this poster') What I'm trying to do is restrict the options that the "associated_question" field shows in the admin. What I mean by that is that if for example, I just wanted to show in the admin the questions that had a timestamp over a certain limit, how would I do that? Thank … -
Django POST not working wit non-admin user in React
I set up my permissions as so: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ #'rest_framework.permissions.AllowAny', 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } with my viewset class TripReportViewSet(viewsets.ModelViewSet): serializer_class = TripReportSerializer queryset = TripReport.objects.all().order_by('-pk') filter_backends = (filters.SearchFilter,) search_fields = ('author__username',) and serializer class TripReportSerializer(serializers.ModelSerializer): author = AuthorField(queryset=User.objects.all()) countries = CountryField(queryset=Country.objects.all(), many=True) class Meta: model = TripReport fields = ('__all__') I got everything working with my admin User to make a post request with this axios call on my React/Redux front end export const postTripReport = (author, title, content, countries) => { const token = localStorage.getItem('token'); return dispatch => { dispatch(postTripReportsPending()); axios.post( 'http://localhost:8000/api/v1/reports/', { title: title, content: content, author: author, countries: countries }, {headers: { 'Authorization': `Token ${token}`}} ) .then(response => { dispatch(postTripReportsFulfilled(response.data)); }) .catch(err => { dispatch(postTripReportsRejected(err)); }) } } It worked fine with admin users, but when I tried to do it for a normal user, I get the respose, 403 forbidden 'You do not have permission to perform this action' So naturally I went to Django Rest Permissions to figure it out, but I tried setting up my view permissions as in their example from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, … -
How do i include related fields in django one-to-many relationship
I have the following models class ExpenseCategory(models.Model): """description of class""" ExpenseCategoryId=models.AutoField(primary_key=True) ExpenseCategoryName=models.CharField(max_length=250) class Meta: db_table="ExpenseCategory" class ExpenseData(models.Model): """description of class""" Id=models.AutoField(primary_key=True) Description=models.CharField(max_length=500) ExpenseType=models.ForeignKey(ExpenseCategory,related_name="ExpenseType",on_delete=models.CASCADE,default=1,null=True) class Meta: db_table="ExpenseData" ModelSerializers class ExpenseCategorySerializer(serializers.ModelSerializer): """description of class""" class Meta: model=ExpenseCategory fields=["ExpenseCategoryId","ExpenseCategoryName"] class ExpenseDataSerializer(serializers.Serializer): """description of class""" ExpenseType=ExpenseCategorySerializer() class Meta: model=ExpenseData ReadOnlyField=["ExpenseCategoryId"] fields=("Id","Date","Description","Deposit_Withdrawal","Available_Balance","ExpenseType") I want to get response like `{ "ID":1, "Description":"XYZ", "ExpenseType": { "ExpenseCategoryId": 1, "ExpenseCategoryName": "Fuel" } }` -
django modelform hook into post model validation
I had written a modelform clean() method which I wanted to run after the field had fully validated... this includes validators in the model field eg. account_number = models.CharField( validators=[RegexValidator(regex='^.{8}$', message='Your account number should be 8 digits.',)], max_length=8) however the regexvalidator above has not run by the time I get to the form's clean() method. Is there an eg post_model_clean() hook for forms that I can use or do I need to duplicate any validators I use in a model field in the form field? (My form clean() method is being used to do additional validation via an external api) -
Django __date not working with date() or string
I have the following model field: inbound_date = models.DateTimeField() I want to filter on date, and not care about the time. I have inserted two test objects which return the following values for inbound_date: 2018-11-14 00:00:00+00:00 2018-11-15 08:37:09+00:00 But all my attempts at retrieving the objects fail: AppInbound.objects.filter(inbound_date__date=datetime.date(2018, 11, 15)) Or AppInbound.objects.filter(inbound_date__date='2018-11-15') But all seem to return an empty QuerySet. The only one I did manage to get working was: AppInbound.objects.filter(inbound_date__startswith='2018-11-15') Which returns the the last objects, with datetime of 2018-11-15 08:37:09+00:00. Can someone explain what is going wrong here? It is an MySQL database, and we have TZ enabled. -
MongoDB check if list item exists for an item in collection before inserting to DB
Im developing a django application uisng python and mongoDB. Im developing a form and take user inputs and save to DB. Before inserting i want to check if data is already present DB. I have a mongo collection which looks something like below : coll_1 : { "_id" : ObjectId("56e0a3a2d59feaa43fba49d5"), "timestamp" : ISODate("2017-11-18T10:23:29.620Z"), "City_list" : "[PN-City1, PN-City2,PN-City3, PN-City4]", "LDE" : "LDE-1234, LDE-345, LDE-456" , "Name": "ABC"} { "_id" : ObjectId("56e0a3a2d59feaa43fba49d6"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City_list" : "[PN-City4, PN-City5,PN-City6,PN- City7]", "LDE" : "LDE-444, LDE-3445, LDE-456", "Name": "BCD"} { "_id" : ObjectId("56e0a3a2d59feaa43fd67873"), "timestamp" : ISODate("2016-12-18T10:23:29.620Z"), "City_list" : "[PN-City1, PN-City6,PN-City9,PN- City10]", "LDE" : "LDE-444, LDE-3445, LDE-456", "Name": "XYZ"} I have a form from where i take user inputs : Name, Cities (one or more comma separated), LDE (comma separated) In my script i want to check before inserting into mongodb If the user is new user insert directly db. If old user, check if cities inputed by user is present in db already if not update db else throw a messagee to html with message saying city already present in DB. Say my input is something like this : Name: PQR City_list : PN-City4, PN-City12 LDE: LDE-6767 My code is as below : if … -
Django StaticLiveServerTestCase sometimes ends with: An existing connection was forcibly closed by the remote host
In an Django application that I freshly created, where I changed it to use PostgreSQL and I created one app, I have the following test: from django.contrib.auth.models import User from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys class TestWebBrowser(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.webdriver = webdriver.Chrome() cls.webdriver.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.webdriver.close() cls.webdriver.quit() super().tearDownClass() def setUp(self): self.admin = User.objects.create_superuser(username="username", password="password", email="example@example.com") def test_navigate_to_import_crm_data(self): self.webdriver.get(f"{self.live_server_url}/admin") self.webdriver.find_element_by_id("id_username").send_keys("username") self.webdriver.find_element_by_id("id_password").send_keys("password") self.webdriver.find_element_by_id("id_password").send_keys(Keys.RETURN) self.webdriver.find_element_by_link_text("Users").click() Sometimes, it runs ok, but sometimes, the test suite spits out: Exception happened during processing of request from ('127.0.0.1', 55283) Traceback (most recent call last): File "C:\Users\pupeno\scoop\apps\python\current\lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "C:\Users\pupeno\scoop\apps\python\current\lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\pupeno\scoop\apps\python\current\lib\socketserver.py", line 717, in __init__ self.handle() File "C:\Users\pupeno\Temporary\untitled\venv\lib\site-packages\django\core\servers\basehttp.py", line 139, in handle self.raw_requestline = self.rfile.readline(65537) File "C:\Users\pupeno\scoop\apps\python\current\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host Any ideas why? Am I missing some tearing-down? -
How Super user can access tokens of other users
I need to delete normal user account from superuser account. As user accounts are authenticated using token authentication, I think it will be needed to access user's token and pass it with the request header to make POST,PUT,DELETE actions on it. So is there any way to access it? Or is there any other substitute way to implement this? -
Why does API test issued by apiary fail to pass request.POST processing of Django?
It's the apiary's API doc + Request (application/json) { 'name':"testUser", 'password':"1234" } When I click ”Call Resource“ on the right side,my django server get this request,but when i print(request.POST) and print(request.body) in django,it display: <QueryDict: {}> b'{\n \'name\':"testUser",\n \'password\':"1234"\n\n}' when I use another APi test tools,django server display <QueryDict: {'name': ['testUser'], 'password': ['1234']}> b'name=testUser&password=1234' Why does apiary have such a situation? What should I do so that I can use it correctly? -
How to filter the child object from Parent model in Django Rest API?
class Tyre(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) product_type = models.CharField(max_length=128) class TyrePrices(models.Model): tyre = models.ForeignKey(Tyre, on_delete=models.CASCADE) price = models.IntegerField() discount = models.IntegerField() description = models.TextField(max_length=256) discount_price = models.IntegerField() stock = models.BooleanField(default=True) This is model, and the requirement is want to filter the tyre according to tyre price range(which is at the second model). How I can do ?? Thanks in advance. -
File download manager - Django
I have a server which create some large files. Users use a django/website to interface the server. Actually, to retrieve these files, they have to connect to the server by ssh, samba, ... I would like propose a webpage where users can list the files and download some. Then, this page could display the download's progress. I look trough the web for a project which do this but I mainly found project for upload to the server. Does anyone know about a project for provide some files from a server ? Perhaps with JS ? I truly thank you! -
Django not logging to file
My Logging configuration is as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/opt/logs/info.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter': 'standard', }, 'request_handler': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/opt/logs/request.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { ' ': { 'handlers': ['default'], 'level': 'INFO', 'propagate': True }, 'django.request': { # Stop SQL debug from logging to main logger 'handlers': ['request_handler'], 'level': 'INFO', 'propagate': False }, } } In my views, I try to log the following message: import logging logger = logging.getLogger(__name__) class IPGroupDeleteView(generics.DestroyAPIView): queryset = IPGroup.objects.get_queryset() serializer_class = IPGroupSerializer def destroy(self, request, *args, **kwargs): try: instance = IPGroup.objects.get(id=kwargs['pk']) except IPGroup.DoesNotExist: logger.info("instance not found") return Response(data={"errors": f"IP Group with id {kwargs['pk']} not found"}, status=status.HTTP_404_NOT_FOUND) In my request.log, the logs get populated for every time a 404 happens as follows: 2018-11-15 12:49:44,616 WARNING django.request Not Found: /api/v1/ip-group/190/delete/ 2018-11-15 12:49:57,364 WARNING django.request Not Found: /api/v1/ip-group/190/delete/ 2018-11-15 12:54:24,947 WARNING django.request Not Found: /api/v1/ip-group/190/delete/ However, inside info.log, where I hope to see my custom message, nothing is found.What am i doing wrong ? -
django allauth display all error messages
Is there a way to display all error messages in a customized login.html template using django with allauth? I do it with: {% for field in form %} {% for error in field.errors %} {{ error }} {% endfor %} {% endfor %} {% for error in form.non_fields_errors %} {{ error.message|escape }} {% endfor %} But the error "Too many failed login attempts. Try again later." is not displayed with this approach. -
Django - Altering a Form field into a choices field and populating dynamically
In my models I have a char field as per the below: alerting_tier = models.CharField(max_length=200, blank=True, null=True) However in my form I'm pulling external data that I would like to use a choices for this field. My attempt thus far is not showing errors but is not showing a choice field either, its just a textbook. class DeviceForm(forms.ModelForm): class Meta: model = Device fields = ['site', 'switches', 'hostname', 'serial_no','version', 'template', 'model', 'install_date', \ 'ospf_area','snmp_data','alerting_tier','host_data','solarwinds_id','smartnet','bau', \ 'smartnet_contract_id','smartnet_contract_start_date','smartnet_contract_end_date','alerting_tier'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) device_id = kwargs.pop('device_id', None) self.is_add = kwargs.pop("is_add", False) self.blank_site = kwargs.pop("blank_site", False) super(DeviceForm, self).__init__(*args, **kwargs) # get the alerting tiers from solarwinds swis = solarwinds_conn() tier_query = """ SELECT c.Field, c.Value, c.DisplayName FROM Orion.CustomPropertyValues c WHERE Field = 'AlertingTier' """ tier_results = swis.query(tier_query) tiers = tier_results["results"] tier_options = [] for i in tiers: tier_options.append(i['Value']) self.fields['alerting_tier'].choices = tier_options self.fields['alerting_tier'].widget.choices = tier_options -
Modify response from Django REST API using CustomUserModel extending default User Model and API classes
I have a Django Project with CustomUserModel. I have extended Django default RegisterView with my CustomRegisterView, and also created CustomLoginView by extending LoginView. Everything works fine, data too get saved with custom fields, and while loging in and registering, I get a "key" in response, but I want to customize response of both the APIs with additional fields such as primary key value and a result_flag which will be either 0 or 1. My CustomRegisterSerializer class is defined as- class CustomRegisterSerializer(RegisterSerializer): email = serializers.EmailField() password1 = serializers.CharField(write_only=True) name = serializers.CharField() phone_no = serializers.IntegerField() user_android_id = serializers.CharField() user_fcm_token = serializers.CharField(required=True) user_social_flag = serializers.IntegerField() user_fb_id = serializers.CharField(required=True) user_android_app_version = serializers.CharField() class Meta: model = User fields = ('email', 'name', 'phone_no', 'user_android_id', 'user_fcm_token', 'user_social_flag', 'user_fb_id', 'user_android_app_version') def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'phone_no': self.validated_data.get('phone_no'), 'name': self.validated_data.get('name'), 'user_android_id': self.validated_data.get('user_android_id'), 'user_fcm_token': self.validated_data.get('user_fcm_token'), 'user_social_flag': self.validated_data.get('user_social_flag'), 'user_fb_id': self.validated_data.get('user_fb_id'), 'user_android_app_version': self.validated_data.get('user_android_app_version'), } def save(self, request): user = super(CustomRegisterSerializer, self).save(request) print(user.pk) return user Views file: from rest_auth.registration.views import RegisterView, LoginView from app.models import User class CustomRegisterView(RegisterView): queryset = User.objects.all() class CustomLoginView(LoginView): queryset = User.objects.all() urls.py: (In apps directory) from django.urls import re_path from . import views app_name = 'app' urlpatterns = [ re_path(r'^registration/$', … -
novalidate form attribute causes data to be omitted
HTML5 allows 'browser-side' validation of certain form elements; for example for <input type="number"> a little bubble will pop up if you typed in anything that isn't a number. This validation before sending the form can be suppressed by adding a novalidate attribute to the form tag or a formnovalidate attribute to the submit buttons, making the server responsible for all validation. By default, django uses novalidate as its form errors are far better visible. But here's the catch: when using novalidate the data of any form element that could be validated client-side and has invalid data, will be omitted in the request that reaches the server. The server cannot validate the data for these faulty elements anymore and as a result, the user that put the bad data in will never be made aware of his mistake. forms.py class WorstFormEver(Form): a = IntegerField(required = False) # use the default NumberInput widget, allowing HTML5 validation b = IntegerField(required = False, widget = TextInput) # TextInput does not include HTML5 validation Take this form and fill both fields with letters. views.py class WorstViewEver(FormView): form_class = WorstFormEver template_name = 'admin/worst.html' success_url = reverse_lazy('worst') novalidate = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['novalidate'] … -
How can I select specific fields in django rest framework?
For example, I have a Person model and its serializer class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) sex = models.IntegerField() phone = models.CharField(max_length=255) class SimplePersonSerializer(serializer.ModelSerializer): class Meta: model = Person fields = ('first_name', 'last_name') Then in my view function, I can: @api_view(['GET']) def people(request): people = Person.objects.all() data = SimplePersonSerializer(people, many=True).data return Response(data) However, when I profiler it using django-debug-toolbar, it shows that the serializer ask SQL Server to select all field of Person model, despite I only need first_name and last_name. I know I can change people = Person.objects.all() to people = Person.objects.all().only('first_name', 'last_name') to make it. But I wonder if I can do this inside the serializer. -
What is the difference between the create and perform_create methods in Django rest-auth
I'm using the Django rest-auth package. I have a class that extends rest-auth's RegisterView, and which contains two methods, create and perform_create. What is the difference between these two methods? -
Mongoengine + Django-tables2: Expected table or queryset, not QuerySet
I'm starting to learn django and using it to build and interface to our mongoDB using also mongoengine. I'm following this tutorial to use django-tables2 but I can't even start it because I get the error Expected table or queryset, not QuerySet I see that mongoengine output is a QuerySet type. How can I convert it to some type I can input on django-tables? Thank you for the help! -
Elegant architectures for react/redux frontends with django backends for editing large data model structures?
Context We have a large Django application with a complex frontend that mixes several technologies. We are thinking about a big redesign and want to avoid some organic growth complexity from before, i.e. a lot of manual change tracking and individual endpoints in the REST API. The data model spans a dozen Django applications and 156 tables in PostgreSQL. Some resources are very large and contain lists of mappings to other, smaller resources. As an example, an AirplaneRepair, a data structure describing a to-be-planned operation contains hardware and personnel requirements, both with constraints regarding when they are needed. The frontend has a few common features that challenge the current architecture: auto-save on changes (similar to Google Drive) undo / redo (should work nicely with redux) versioning of operation-describing components (e.g. a version of the AirplaneRepair operation with all of its crew and hardware constrains) stored as JSON blobs in the DB for now created on explicit "create version" call by user Otherwise it's mostly data manipulation with backend enforced constrains / consistency checks. The proposed new architecture We defined all our models in Django. Those should stay. ORM maps them onto the DB. API The REST API should consist of … -
Django test: How to get the html string from a HTTPResponseRedirect object
I have a test in which the view redirects using HttpRepsonseRedirect(). In my test I pass a dict to a POST request which goes through this HttpResponseRedirect. data = {...data...} response = self.client.post(url, data) How do I check if strings are in the response HTML? I cant do: self.assertContains(response, 'my_string') or self.assertIn(response, 'my_string') Is there a way of accessing the HTML as a string from this response?