Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ansible Venv Django CMS
Im making an ansible role to install a clean Django CMS instance, when trying to activate my installed Virtual Env I'm getting a permission error, I have read up that sometimes this can be caused when making the env with different permissions to when you try and activate it. I have tried with and without root sudo in both instances. I am using a Ubuntu/Trusty64 box. Here is the error im getting from my task: TASK [dependancies : Activate Venv] ******************************************** fatal: [default]: FAILED! => {"changed": false, "cmd": ". env/bin/activate", "failed": true, "msg": "[Errno 13] Permission denied", "rc": 13} Here is my role file: --- - name: Update apt-get become: yes apt: update_cache: yes - name: Install Packages apt: name: "{{ item }}" with_items: - nginx - python3 - python-pip - nodejs - git - python-passlib # for htpasswd - postgresql - libpq-dev # for postgresql - python-psycopg2 # for postgresql - ansible # to run ansible-pull become: yes - name: Install Python Libraries pip: name: "{{ item }}" executable: pip become: yes with_items: - virtualenv - awscli # for backups - name: Create Venv command: virtualenv env args: creates: env/bin/activate - name: Activate Venv command: . env/bin/activate - name: … -
accessing request object in a SessionWizardView in django
I am using a django forms SessionWizardView to implement a form wizard. The url configuration is as follows; url(r'^contact/(?P<pk>\d+)/$', views.ContactWizard.as_view([DummyForm, OtherForm]), name='contact'), The idea here is that I am passing a primary key so that I can populate the form with some initial data. The form is loaded from another view as follows: def populate_review_form(request): pk = 2 return redirect('contact', pk=pk) Here I am trying to pass a hard-coded primary key to the form. Now, my form implementation is simple where I am overriding the get_form_initial to generate the initial value for the form as follows: class ContactWizard(SessionWizardView): def get_template_names(self): return "test.html" def get_form_initial(self, step): pk = self.request.GET.get('pk') # Just attempt to print the primary key print pk, self.request.GET return {} def done(self, form_list, **kwargs): return HttpResponseRedirect('index') The issue is that this always prints None <QueryDict: {}>. So, basically my parameter is not being passed or I am unable to access the correct request object. Is it possible in Django to have this communication? -
Django - authenticate() A user with that username already exists
Okay I'm confused. I'm trying to build a login page, but whenever I try to login, django gives the error that the username already exists. I haven't used save() anywhere. I'm using authenticate(), I referred the Django docs for that: https://docs.djangoproject.com/en/1.10/topics/auth/default/#how-to-log-a-user-in Here is my code, please tell me where I'm going wrong: forms.py class LoginForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) class Meta: model = User fields = ['username', 'password'] views.py class LoginFormView(View): form_class = LoginForm template_name = 'login.html' # display a blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # authenticate user def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('slrtcebook:home') return render(request, self.template_name, {'form': form}) login.html <div class="form-container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field }} {{ field.errors }} {% endfor %} <input id="submit" type="submit" value="Log in" /> </form> </div> <p>Don't have an account? <a href="/">Register here</a></p> -
Django template if inside a for loop - Invalid block tag on line 13: 'else', expected 'empty' or 'endfor'.
{% for letter in "ABCD"|make_list %} {% if letter == A or D} Yes {% else %} No {% endif %} {% endfor %} With my django template I am getting the following error message: Invalid block tag on line 13: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I don't understand what is wrong here. Can someone point out why I'm getting this error? -
model form, button submit, no action
I have the following code that lists once obtained the ID of a specialty a table with x elements that have a text compiled of the form of the model and a button that asks for the validation of the fields, once all of the fields have Quantity, The button has no action and is not inserted into the database. views.py: def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user if user.is_superuser: pedido = Pedido.objects.filter(especialidad=especialidad) if request.method == 'POST': form = PedidoEditForm() else: form = PedidoEditForm(request.POST) if form.is_valid(): form.save() pedido.estado = 'pendiente' pedido.fecha_pedido = datetime.now() pedido.save() return render(request, 'admindata.html', locals(),{'form':form}) model.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') fecha_entrega = models.DateTimeField(auto_now_add=False) fecha_pedido = models.DateTimeField(auto_now_add=True,null=True, blank=True) cantidad = models.IntegerField(blank=True) pendiente = models.CharField(max_length=999, null=True, blank=True) estado = models.CharField(max_length=20, blank=True, default='pendiente') form.py: class PedidoEditForm(forms.ModelForm): cantidad = forms.IntegerField(label='Cantidad:', widget=forms.TextInput(attrs={'size':'10'})) class Meta: model = Pedido fields = [ 'cantidad', ] html table: <section id="contenido"> <div class="container" style="margin:50px auto width="100%""> <form id="myform" method="post"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td>Ingresar</td> <td></td> </tr> </thead> <tfoot> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td></td> </tr> </tfoot> <tbody> {% if … -
How I can connect two variables of the same model?
I'm doing an app in Django witch a form that evaluate a candidate for a job vacancy. The form must have a candidate(ok), a valuer(ok) and a variable wich the criteria and a score for this criteria. So I create a model with this attributes(Avaliacao) to use it in the forms.py - this model connect the criteria(Criterio), the valuer(auth.user),the candidate (Candidato) and the attribute to receive the score for the criteria (nota). The model Criterio is the model that the user can create a criteria to evaluate the candidate, like 'work experience', for example, this model have just one attribute, the label that receive a text field. The model Candidato receive the dates of the candidate: name, e-mail, link for Github/Linkedin and etc, and it is used in another form (registration form). Well let me show you: forms.py: from .models import Candidato, Avaliacao#, Aval from django import forms class CandForm(forms.ModelForm): class Meta: model = Candidato fields = ('name', 'e_mail', 'github', 'linkedin', 'Ensino_superior','cover_letter') class AvalForm(forms.ModelForm): class Meta: model = Avaliacao fields = ('criterio','candidato','avaliador','nota') models.py: from django.db import models from jsonfield import JSONField from site_.settings import MEDIA_ROOT class Criterio(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidato(models.Model): name = models.CharField(max_length=100) e_mail … -
use django's reverse function in req.path
I was stumbling on invitation feature to understand how it works. I found the blog post on http://www.pythondiary.com/tutorials/create-invite-only-website.html. There the author says (It checks the path as this will cause an infinite loop if not checked). How to use reverse function to check the path? class Invite(models.Model): INVITE_CHOICES = ( ('G', 'General'), ('I', 'Invitational'), ) user = models.OneToOneField(User) cookie = models.UUIDField(default=uuid.uuid4) token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) def __str__(self): return self.user.username # def get_absolute_url(self): # return reverse('user_mgmt:confirm_invite', kwargs={'token': self.token}) class InvitedMiddleware(object): def process_request(self, req): if req.path == '/i.auth': return None if not req.user.is_authenticated(): if 'token' in req.COOKIES: return redirect('user_mgmt.views.login_user') return None def process_response(self, req, resp): if req.user.is_authenticated(): if req.user.is_staff: return resp if 'token' in req.COOKIES: token = req.COOKIES['token'] else: invite = Invite.objects.get(user=req.user) token = invite.token resp.set_cookie('token', token, MAX_AGE=1209600) return resp -
No getting Markdown editor in django admin pages
I am using django 1.8.6 and python 3.6 for creating a blog app . I am quite new to both. I have installed django_markdown for getting the markdown functionalities and the toolbar in the admin pages. But even after including them in setting.py and urls.py , I'm not able to get those nice Markdown editor. My admin.py file from django.contrib import admin from django_markdown.admin import MarkdownModelAdmin from . import models class EntryAdmin(MarkdownModelAdmin): list_display = ("title", "created") prepopulated_fields = {"slug": ("title", )} admin.site.register(models.Entry, EntryAdmin) Thanks in advance for your time and effort.It would be great help if you inform me what the problem is. -
Django URL white space Issue
I have just installed Django 1.10.3 and have made a project with application called profiles. I have added a url url(r'^profiles/', include('profiles.urls')), in my_site/urls.py and in profiles/urls.py I have added: urlpatterns = [ url(r'create^$', views.create_profile, name='create_profile'), ] but on my web page I get this: ^profiles/ create^$ [name='create_profile'] due to which I can not get into my webpage. Please help me out. I can't see webpage by either of these urls: http://localhost:8000/profiles/create http://localhost:8000/profiles/ create -
How to deploy existing django application on a server?
I have a django application and I want to deploy it on a server. All the tutorials I found were for new applications so they don't fit to me. Any suggestions? Thanks in advance! -
opening new url page using JS in django website
i'ev developed a django website (using Django 10, Python3, SQLite and Webfaction as a host). through the development i was testing the website using the local server and everything was working very well.Then, i upload it in the Webfaction server run all the needed changes but two issues came up that needed to be slove: 1. when i run the ./apache2/bin/restart: loading the page becomes very slow and i receive 500 ERROR, but when i refresh the page i worked fine a loads very fast. 2. i have i button that opens another webpage: when the user click on the button-after writing his/her name and chosen the gender ) based on the gender and the chosen radio button,ether this http://gadgetron.store/male_chatbot will open or http://gadgetron.store/female_chatbot, this is a part of the JS of the hom.html: $('.btn-xl').click(function(){ if(document.getElementById('radio01').checked == false && document.getElementById('radio02').checked == false ){ alert("--ارجوا الاختيار--"); } else{ var n = $('.message-input').val(); if ($.trim(n) == ''){ alert("--ارجوا كتابة اسمك الاول--"); document.getElementById('radio02').checked=false; document.getElementById('radio01').checked=false;} else{ var name = $('.message-input').val(); post(name); setTimeout(function(){gender_script();}, 400); setTimeout(function(){ var gender = find_gender(); if(gender.user_gender=="M" && document.getElementById('radio01').checked){ window.open('http://gadgetron.store/male_chatbot'); $('.message-input').val(null); document.getElementById('radio01').checked=false;} else{ if (gender.user_gender== "F" && document.getElementById('radio02').checked){ window.open('http://gadgetron.store/female_chatbot'); $('.message-input').val(null); document.getElementById('radio02').checked=false;} }, 700); } }); it is working fine (from POST the … -
Django Bad Handshake when run from Apache server but not from Django development server
I'm getting the following error ('bad handshake: SysCallError(0, None)',) when I run response = requests.get(film_url) from a website running a Django application in 'production' (ie an Apache2 webserver). I do not get this error when I run the system from my laptop using the Django development server. film_url is a link to a film (it could be any) on RottenTomatoes.com, for example https://www.rottentomatoes.com/m/myfilm I'm running python 2.7 and I take it this is an SSL issue but I don't know how to sort. I've tried to following this advice but I'm getting an error trying to install pyOpenSSL, namely: Command "/var/www/mga/env/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-DuLMZe/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-giimpi-record/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/mga/env/include/site/python2.7/cryptography" failed with error code 1 in /tmp/pip-build-DuLMZe/cryptography/ -
Django - How to process GET with a url: with varying parameters such as ?derivate=22&engine=73?start_date=2017-03-05?end_date=2017-05-05
So I need to process a url which can be like this: /api/timelinedata/merge/?derivate=22&engine=73?start_date=2017-03-05?end_date=2017-05-05 or it could just have start and end dates: /api/timelinedata/merge/?start_date=2017-03-05?end_date=2017-05-05 -
Comparing attributes of different objects return 'false'
I'm trying to append messages to specific conversations, but comparison between two values always return 'false'. I think that my program is not comparing extracted values of attributes, but just attributes themselves. How can i solve this problem? Code: all_messages = UserMessage.objects.all().order_by('-create_date') conversations = [] messages = [] for message in all_messages: if message.reciever == request.user: messages.append(message) if not message.sender in conversations: conversations.append(message.sender) elif message.sender == request.user: messages.append(message) if not message.reciever in conversations: conversations.append(message.reciever) print(conversations) print(messages) # The loop with a problem for conversation in conversations: print('current conversation:', conversation) print('current conversation username:', conversation.username) for message in messages: print('current message:', message) print('current message sender:', message.sender) print('current message reciever:', message.reciever) if conversation.username == message.reciever or conversation.username == message.sender: print('appending') conversation.append(message) else: print(conversation.username, ' and ', message.reciever, ' are not the same') print(conversation.username, ' and ', message.sender, ' are not the same') print(conversations) Example logs: [<User: test1>, <User: test3>] [<UserMessage: UserMessage object>, <UserMessage: UserMessage object>, <UserMessage: UserMessage object>] current conversation: test1 current conversation username: test1 current message: UserMessage object current message sender: test2 current message reciever: test1 test1 and test1 are not the same test1 and test2 are not the same current message: UserMessage object current message sender: test3 current message reciever: test2 … -
Get country code by coordinates using django gis
I develop the app with Django gis. I have coordinates of all users and I need to geocode them, meaning - get country, region and city of each user. So I user google maps API and it works great. But I need to get that data in the language of the country, the user is from. So I make one request to google API without language parameter to find out the country code, and then another one with language parameter to get needed information. As you understand it take many requests, so how can I get the country code of the coordinates using Django gis? -
How to set subdomains with django?
I've deployed my site on pythonanywhere.com, now I'd like to configure subdomains on some pages and I was wondering what I'm doing wrong using django-subdomains package ? Here is what my code looks like : settings.py : ... (already installed 'subdomains' in INSTALLED_APPS) MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'subdomains.middleware.SubdomainURLRoutingMiddleware', #before CommonMiddleware 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'site.urls' SUBDOMAIN_URLCONFS = { None: 'site.urls', 'www': 'site.urls', 'web': 'pages.urls.web', 'account': 'site.urls.login', } SITE_ID = 1 ... site/urls : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/login/$', auth_views.login, name='login'), url(r'^', include('pages.urls')), url(r'^accounts/', include('utilisateur.urls')), ] ... pages/urls : urlpatterns = [ ... url(r'^$', views.index, name="index"), url(r'^web/$', views.web, name="web"), ... ] When I type web.site.ch/web/, the adress is not found. www.site.ch/web/ still exist while it should be web.site.ch/web/, same for accounts.site.ch/..., why it isn't ? Am I missing something ? -
Authentication credentials were not provided with djangorestframework-jwt
I am trying to use django rest_framework_jwt. I can get it to generate a token but when i try and send it in the header to a protected view i get 'Authentication credentials were not provided.' The format of the header I am sending is: "Authorization": "Token SomeRandomToken" settings.py INSTALLED_APPS = [ ... rest_framework.authtoken ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } views.py class UserList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) queryset = User.objects.all() serializer_class = UserSerializer -
Assertion fails with same object
The unit test fails with the following exception: def test_question_form(self): question = Question(question_text='Dummy question', pub_date=timezone.now( ) + datetime.timedelta(days=1), allow_multiple_choices=True) question_form = QuestionForm( {'question_text': question.question_text, 'pub_date': question.pub_date, 'allow_multiple_choices': 'on' if question.allow_multiple_choices else 'off'}) self.assertTrue(question_form.is_valid()) self.assertEqual(question_form.save(commit=False), question) AssertionError: <Question: Dummy question> != <Question: Dummy question> After some manual assertion the object seem to be equal, what am I doing wrong? -
Form input template does not save
py in a def that lists me articles in a table, which have the inputtext of my model forms, RequestEditForm, input that appear next to each article, plus a button which saves the amount of inpuText saved. My problem is that the button does nothing, so it does not save in the database the amounts entered. def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user if user.is_superuser: pedido = Pedido.objects.filter(especialidad=especialidad) form = PedidoEditForm() if form.is_valid(): form.save() pedido.estado = 'pendiente' pedido.fecha_pedido = datetime.now() pedido.save() template = 'admindata.html' return render_to_response(template,locals()) html file: <form id="myform" method="post"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td>Ingresar</td> </tr> </thead> <tfoot> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> <td>{{ ped.articulo.stock }}</td> <td>{{ ped.cantidad }}</td> <td>{{ ped.fecha_pedido }}</td> <td>{{ ped.estado }}</td> <td>{% csrf_token %} {{form.as_p}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> <input type="submit" class= "btn btn-success" value="Guardar"> Because the button does not work, which I lack also I have the error of: UserWarning: … -
How to migrate data from foreign key in unmanaged model to managed model in Django 1.7?
We're slowly moving from unmanaged to managed models, one foreign key at a time. The current situation: class OldOrg(Model): pass class Meta: managed = False class OldService(Model): offered_by = models.ForeignKey(OldOrg) class Meta: managed = False class NewOrg(Model): org = models.OneToOneKey(OldOrg) class NewService(Model): service = OneToOneKey(OldService) The next step: class NewService(Model): service = OneToOneKey(OldService) offered_by = models.ForeignKey(NewOrg) The problem happens in the data migration using django's inbuilt migration system. The field OldService.offered_by does not exist, so we cannot use that to get to the NewOrg primary key for use in NewService.offered_by. # This works in the shell but not in a migration for ns in NewService.objects.all(): ns.offered_by = ns.service.offered_by.new_org In the migration, OldService doesn't have the field offered_by_id either. Is there some other way to get at the data in OldService? -
Firebase as central user database
for the moment we have 3 differt applications where our customers can login. We have a forum, a webshop and our application. We would like to implement firebase so that the users only need 1 account. Our webshop is based on OpenCart, our forum is based on vanilla forum and our application is written in django. So now the question : What would be the best way to make it possible to log in on all these sites with 1 account. Thanks in advance! -
How to register Django models that are only used in tests
I'm writing an app that has a custom model field. I want to test that field, using a model that is only used within tests, but I'm struggling to get the model working in tests. Some of my app structure is like this: myapp/ fields.py models.py tests/ fields/ models.py tests.py settings.py tests/fields/models.py is like this: from django.db import models from myapp.fields import MyCustomField class MyTestModel(models.Model): custom_field = MyCustomField() I then import MyTestModel and try to use it in tests/fields/tests.py. Things I've tried... 1. Initially I got: RuntimeError: Model class tests.fields.models.MyTestModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. 2. So I added "tests", to INSTALLED_APPS in tests/settings.py. But then I get: django.db.utils.OperationalError: no such table: tests_mytestmodel 3. I've seen this in the docs about isolating model registration in tests. So I've tried moving the models into tests/fields/tests.py: from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from myapp.fields import MyCustomField @isolate_apps('tests') class MyTestCase(TestCase): def test_things_work(self): class MyTestModel(models.Model): custom_field = MyCustomField() obj = MyTestModel.objects.create(custom_field='foo) self.assertEqual(...) But that still gets me: django.db.utils.OperationalError: no such table: tests_mytestmodel I've tried looking through the tests of lots of other Django projects that provide custom fields and can't see … -
passing a wizard instance to a django template
I have a need where I need to instantiate a django form wizard from a view. So, I have a wizard which I have defined as: from django.http import HttpResponseRedirect class ContactWizard(SessionWizardView): def get_template_names(self): return "test.html" def done(self, form_list, **kwargs): return HttpResponseRedirect('index') Now, I have a view where I am trying to instantiate this wizard and pass it a template to render it. So, I have something like: def populate_review_form(request): return render(request, 'test.html', {'wizard': ContactWizard.as_view([DummyForm, OtherForm])}) And now my test.html looks like (pilfered from documentation): {% load crispy_forms_tags %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %} <form action="." method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {% crispy form %} {% endfor %} {% else %} {{ wizard.form }} {% endif %} {% if wizard.steps.prev %} <button name="wizard_goto_step" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} </table> <input type="submit" class="btn btn-success" value = "Next"> </form> {% endblock %} Here I was hoping that the wizard variable would get initialized to my ContactWizard instance in the populate_review_form … -
Django Rest Framework with nginx caching requests
Since I started using DRF with nginx/gunicorn server I've noticed that queries are being cached somehow. I.e. I got 10 records of object A in database (Postrgres) - if I ask for them with GET, I got 10 - ok. But then, when I add another record, I got 10 instead of 11 (although I see 10 in database). I have to manually reset gunicorn to get the correct result, which is not how REST should work... Here's my nginx config (tried some cache settings): upstream myapp{ server unix:/var/django/gunicorn.socket fail_timeout=0; } server { listen 80; server_name myapp.example.com; client_max_body_size 4G; access_log /var/django/myapp/logs/nginx-access.log; error_log /var/django/myapp/logs/nginx-error.log; # DRF API below location /api { expires off; add_header Cache-Control "private, no-cache, must-revalidate, max-age=0"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_connect_timeout 75s; proxy_read_timeout 300s; proxy_pass http://myapp; } # JS for webapp (backbone) location / { alias /var/django/myapp_web/; } } and gunicorn as well: #!/bin/bash NAME="myapp" DJANGODIR=/var/django/myapp SOCKFILE=/var/django/gunicorn.socket USER=appuser GROUP=appuser NUM_WORKERS=5 DJANGO_SETTINGS_MODULE=myapp.settings DJANGO_WSGI_MODULE=myapp.wsgi TIMEOUT=300 echo "Starting $NAME as `whoami`" cd $DJANGODIR source /var/django/myapp/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /var/django/myapp_venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --reload \ --timeout $TIMEOUT \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug … -
Must I write front and end render code?
class Teacher(models.Model): name = CharField class Child(models.Model): name = CharField teacher = models.ForeignKey( 'Teacher', on_delete=models.CASCADE, related_name='nodes', ) I am wring a config page, does't like normal solution, use django template render the html page, and update with same template, I can click "add" then I can input the new children information, in other words, I can add multiple children with one teacher. class TeacherCreate(View): template_name = 'config/teacher_add.html' def get(self, request): teacher_form = TeacherForm() children_list = [ChildrenForm(), ] return render(request, self.template_name, { 'teacher_form': teacher_form, 'children_list': children_list, }) def post(self, request): received_json = json.loads(request.body) children_list = received_json['children_list'] children_form_list = [] teacher_form = TeacherForm({'name': received_json['name']}) valid = True try: with transaction.atomic(): teacher = None if teacher_form.is_valid(): teacher = teacher_form.save() else: valid = False for child in children_list: children_form = ChildrenForm(child) if children_form.is_valid(): if valid: children = children_form.save(commit=False) children.teacher = teacher children.save() else: valid = False children_form_list.append(children_form) if not valid: # rollback raise KeyError except KeyError: # rollback pass if valid: return redirect(reverse("config:teacher_list")) else: return HttpJson({ 'teacher_form': teacher_form, # here I have to convert to normal data, and extract errors 'children_list': children_form_list, # here I have to convert to normal data, and extract errors }) but as you can see, I have to convert …