Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error: 'int' object is not iterable Django
I have this error when creating the cycle to get all the quantities of the ModelForm text "PedidoEdirForm" Here the queryset where I intend to do this function: Views.py: def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad).order_by('- articulo') pedido2 =Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').order_by('-articulo') pedido3 =Pedido.objects.filter(especialidad=especialidad).filter(estado='entregado').order_by('-articulo') if request.method == 'GET': form = PedidoEditForm(instance=especialidad) else: form = PedidoEditForm(request.POST, instance=especialidad) if form.is_valid(): for cantidad in form.cleaned_data['cantidad']: pedido.cantidad.add(cantidad) return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad) return render(request, 'ingresa.html', {'form':form, 'pedido':pedido, 'pedido2':pedido2, 'pedido3':pedido3, 'especialidad':especialidad}) forms.py: class PedidoEditForm(forms.ModelForm): cantidad = forms.IntegerField(widget=forms.TextInput(attrs={'type':'number'})) class Meta: model = Pedido fields = [ 'cantidad', ] html table: <form id="myform" method="POST"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Nombre</td> <td>Cantidad</td> </tr> </thead> <tfoot> <tr> <td>Nombre</td> <td><input type="submit" class= "btn btn-primary" value="Guardar"></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.articulo.nombre }}</td> <td>{% csrf_token %} #inputext "cantidad" {{form.as_p}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> Help please if you understand and could recommend me how to perform this function when entering each value to the textinput of the modelform and then save it. -
how to run django on parse stack by bitnami at AWS
I want to make mobile app so I got a parse server by bitnami through parse stack at AWS. And I all so want to make web site by Django. So i install django on parse server by not a stack. installed by "pip install django" and I tried to runserver. but there are errors. bitnami@ip-172-31-11-49:~/wanote$ python3 ./manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 14, in <module> import django ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? could you help me? -
Somehow import Django object inside a js script
I would like to access a django object inside a js script. In other words, I want the output of {{ contract.request.customer.fax }} with something like var fax = {{ contract.request.customer.fax }}, but it did not work. What is the correct solution? -
Django to make an app to manage a linux server
I would like to use django to make an app to manage my linux server. I'll need to execute script and get the result. Do you thinks websoket and Django Channel ( https://github.com/django/channels ) are a good solution ? Or I missing something and there is a better way to do that ? Thanks -
Django Views file showing tab error when deployed on AWS Beanstalk
My views.py is working absolutely fine on my local server but when deployed on AWS Beanstalk it's showing this error : enter image description here My views.py file is : # -*- coding: utf-8 -*- from django.views.generic.base import TemplateView from django.http import HttpResponseRedirect, HttpResponse from django.core.mail import send_mail from django.shortcuts import render from models import EmailForm def home(request): return render(request, 'index.html', {}) def sendmail(request): if request.POST: form = EmailForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail(subject, message + " from " + email, 'akshat.akshat6@gmail.com', ['akshatuppalweb@gmail.com']) return HttpResponseRedirect('/') except Exception, e: return HttpResponse('Except Block executed.' + str(e)) else: return HttpResponse("Form not Valid") else: return HttpResponseRedirect('/') -
Django - Pool not running functions
I have a server with 2 cpus and 2gb of ram running Nginx and Gunicorn. For some reason, code works outside of django views on raw python but not when sending a JSON POST request. from multiprocessing import Pool @csrf_exempt def audio(request): if request.method == 'POST': print("Post received") def result1(a): print("Executed result1") return(a) def result2(b): print("Executed result2") return(b) pool = Pool() result1 = pool.apply_async(result1, ['A']) # evaluate "solve1(A)" asynchronously result2 = pool.apply_async(result2, ['B']) # evaluate "solve2(B)" asynchronously a = result1.get(timeout=10) b = result2.get(timeout=10) print(a) print(b) When I check the gunicorn logs: Post received 2017-05-20 17:07:52 [3326] [CRITICAL] WORKER TIMEOUT (pid:3332) 2017-05-20 17:07:52 [3326] [CRITICAL] WORKER TIMEOUT (pid:3332) 2017-05-20 17:07:53 [3353] [INFO] Booting worker with pid: 3353 It looks like none of the pool functions was executed, how can I fix this? -
Issue to enter in a condition function
In the interactive shell of Django, I got In [1]: contract = Contract.objects.get(pk=2) In [2]: contract Out[2]: <Contract: Contract with David Bouchard (en)> In [3]: contract.request.customer.convert_fax_number Out[3]: '' In a JavaScript function, I created a variable var fax_number = "{{ contract.request.customer.convert_fax_number }}"; and create the following if condition function if (fax_number == '') { alert('Please, attach the fax number to your profile'); return; } I put a breakpoint of the first line of that code. Hence, I know that the compiler stopped on this line, but it has never executed the statement of that if condition. Here is the whole function : (function($){ var bindEvents = function(node){ $('.btn-fax', node).bind('click', function(e){ e.preventDefault(); var data = {}; var fax_number = "{{ contract.request.customer.convert_fax_number }}"; $.ajax({ url : $(this).attr('href'), type: 'POST', data : data, success: function(data, textStatus, jqXHR) { if (data.success) { if (data.redirect_to) { window.location.href = data.redirect_to; } else if (data.reload) { window.location.reload(); } } else { alert('Error! See console for details :('); console.error(textStatus, data); } }, error: function (jqXHR, textStatus, errorThrown) { if (fax_number == '') { alert('Please, attach the fax number to your profile'); return; } console.error(textStatus, errorThrown); } }); return false; }); }; and here the modification I did to … -
Django forms not working on DigitalOcean Server
Hi I've recently been trying to deploy a Django web app on a DigitalOcean Ubuntu 16.4 server, and was finally able to have the views load with uWSGI, nginx, and lets encrypt for a secure connection. My only issue is: there are a few views which rely on submitting a django form to retrieve objects based on distance from the user (GeoDjango query in the view). The form in question looks like this: <form method= 'get' action="/foo/">{% csrf_token %} <input id='latload' type= 'number' step='any' value='0' name='latitude' style="display:none"> <input id='lonload' type= 'number' step='any' value='0' name='longitude' style="display:none"> <p id= 'walltext' >Here you can listen to the sounds in your area. To use your current location, turn GPS on <input class="btn btn-success" style="color:#34373a;" font-size: 25px; width: 100% value="Get Location" onclick="getLocationWall()" /> , then click </p> <input class="btn btn-success" type='submit' id='submit' value='here' style="color:#1d3b77; font-size: 25px; width: 100%;" disabled /> </form> It takes the lat and long retrieved from a previous Javascript getLocation() function, then is passed to the /foo/ view, which queries objects by distance (GeoDjango) and looks like this: def fetch_places_loc(request): lat= request.GET['latitude'] lon= request.GET['longitude'] finder_location = Point(float(lon),float(lat)) nearby= Places.objects.filter( location__distance_lte=( finder_location, D(km=40))).distance(finder_location).order_by('distance').order_by('-rating__average')[:10] context= { 'object_listboy': nearby, 'title': 'wall', } return render(request, 'location/wall.html', … -
Unicode problematic
In the interactive shell of Django, I got In [1]: contract = Contract.objects.get(pk=2) In [2]: contract Out[2]: <Contract: Contract with David Bouchard (en)> In [3]: contract.request.customer.fax Out[3]: u'' In a JavaScript function, I created a variable var fax_number = "{{ contract.request.customer.fax }}"; and create the following if condition function if (fax_number == '') { alert('Please, attach the fax number to your profile'); return; } I put a breakpoint of the first line of that loop. Hence, I know that the compiler stopped on this line, but it has never executed the statement of that if condition. How could I fix it? -
How to save multiple quantities with modelform in table
I'm calling the PedidoEditFrom class which contains the text input field of the "cantidad" field then I save the form with the form.save entered: models.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') blank=True) fecha_pedido = models.DateTimeField(auto_now_add=False,null=True, blank=True) cantidad = models.IntegerField(blank=True, default=0) estado = models.CharField(max_length=20, blank=True) form.py: from django import forms from django.forms import ModelForm from .models import Pedido class PedidoEditForm(forms.ModelForm): cantidad = forms.IntegerField(widget=forms.TextInput(attrs= {'type':'number'})) class Meta: model = Pedido fields = [ 'cantidad', views.py: def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad).order_by('- articulo') pedido2 = Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').order_by('-articulo') pedido3 =Pedido.objects.filter(especialidad=especialidad).filter(estado='entregado').order_by('-articulo') if request.method == 'GET': form = PedidoEditForm(instance=especialidad) else: form = PedidoEditForm(request.POST, instance=especialidad) if form.is_valid(): form.save() return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad) return render(request, 'ingresa.html', {'form':form, 'pedido':pedido, 'pedido2':pedido2, 'pedido3':pedido3, 'especialidad':especialidad}) Then the table containing the assigned items is displayed and the {% csrf_token%} to enter the amount to each one after the "send" button to save all the values entered in the quantity field <form id="myform" method="POST"> <h3>Solicite pedido para: <b>{{ especialidad.nombre }}</b></h3> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> </tr> </thead> <tfoot> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td><input type="submit" class= "btn btn-primary" value="Guardar"></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} … -
ElasticBeanstalk Django: Please supply ENGINE value
I am trying to install a Django app with ElasticBeanstalk. It's failing with the exception settings.DATABASES is improperly configured. Please supply the ENGINE value Full error: Command failed on instance. Return code: 1 Output: (TRUNCATED)... in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. container_command 01_migrate in .ebextensions/15_my.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.` I am getting this error while one of my command is getting executed: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: True Here's my config/settings/production.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ebdb', 'USER': 'djangousername', 'PASSWORD': 'djangopassword', 'HOST': env('RDS_HOSTNAME'), 'PORT': '5432' } } I am kind of sure that EB is picking the config from this file only and not any other file because if I am changing something in this file, it is reflected while ElasticBeanstalk env creation. I have also searched in my whole application that DATABASES is mentioned only in either this file i.e. <app-rot>/config/settings/production.py or <app-root>/config/settings/local.py. At both the places, I have provided the ENGINE value as above. Please let me know if I need to add any other … -
Django - Foreign key, set of ids
Let's say that models are construct like this : class Worker(models.Model): name_char = models.CharField(max_length=4,null=True, blank=True) body_parts_mtm = models.ManyToManyField('BodyPart') class Job(models.Model): job_name = models.CharField(max_length=6,unique=True) job_reference_mtm = models.ManyToManyField('JobReferenceCode') class JobReferenceCode(models.Model): job_ref_char = models.CharField(max_length=13) worker_mtm = models.ManyToManyField('Worker') class BodyPart(models.Model): body_part_name_text =models.TextField() class MembersSimilarity(models.Model): similarity_score_float = models.FloatField(max_length=10) worker_fk = models.ForeignKey(Worker,on_delete=models.CASCADE) job_fk = models.ForeignKey(Job,on_delete= models.CASCADE) #not sure if I need this field to do what I want but here it is: bodypart_fk = models.ForeignKey(BodyPart,on_delete=models.CASCADE) On my website user can look for a JobReference, and I would like to give a specific output : a table where number of lines is controlled by combination of (Job,[BodyParts]). In order to do it, on my view, I think what a found to solve this problem is to make a function that that has this structure (simplified): job_ref_code = 1 job_query = Job.objects.filter(job_reference_mtm=job_ref_code) for job in unique_job_query: sims = MembersSimilarity.objects.filter(job_fk=job) workers_from_sim= Worker.objects.filter(id__in=sims.values('worker_fk')) unique_ids_list = [] for worker in workers_from_sim: combination = set(worker.cath_mtm.all()) if combination not in unique_ids_list: unique_ids_list.append(combination) #All of this "for worker" loop to construct this list; do I need to acces like it ? Let say this lsit has this structure = [[1,2,3],[1],[1,2]] for body_part_combination in unique_body_ids_list: sim_queryset=MembersSimilarity.objects.filter(job_fk=job_query,bodypart_fk=set of ids) #Note sim_query_set : if I can access … -
Can't connect to django server running inside docker container
I have a docker container running on my system which i started using this command : docker run -it -v ~/some/dir -p 8000:80 3cce3211b735 bash Now docker ps lists this : CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 44de7549d38e 3cce3211b735 "bash" 14 minutes ago Up 14 minutes 22/tcp, 443/tcp, 8082/tcp, 0.0.0.0:8000->80/tcp hardcore_engelbart Inside the container i run my django app using the command : python manage.py runserver 80 But i am not able to view the page on using either of these : 1.localhost:8000 2.127.0.0.1:8000 I do understand that my 8000 port is mapped to 80 port on the container . But why am i not able to access it . I am using docker for mac not docker toolbox . Please help and comment if you need any more info . -
Unable to install a Library using PIP
So I'm trying to follow a tutorial to connect to an SQL database, using Connector/Python. I have to import it, obviously: import mysql.connector So I tried pip install mysql in the terminal. This is what I got: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/g6/yrxcmygn3ls375rm9rh3p86r0000gn/T/pip-build-a0d0rzdl/MySQL-python/ What I've tried from looking up on Google: pip install --upgrade setuptools pip install ez_setup pip install unroll easy_install -U setuptools Nothing worked Thanks -
How to set up nginx, django, uwsgi and postgressql in two different droplets on digitialocean?
I currently have a droplet in digitialocean which host both the mariadb database and django app. I use nginx as the public web server and uwsgi to communicate with the django app via socket. I want to separate the database and django app to two different droplets. But I have no idea how to do it in a proper and secure way. I read that digitialocean doesn't provide true private networking but share the same network with all droplet in the warehouse. I want to know the following: How to secure the communication between the droplets? Should I run postgressql independently or use nginx+postgres in the droplet or any other settings? Do I need to run additional database client in the django app droplet to communicate with postgres? Any extra tips for security and performance is appreciated. -
Such as Enter amounts entered in form.py input text
I'm calling the OrderEditFrom class which contains the text input field of the quantity field then I save the form with the form.save entered: models.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') blank=True) fecha_pedido = models.DateTimeField(auto_now_add=False,null=True, blank=True) cantidad = models.IntegerField(blank=True, default=0) estado = models.CharField(max_length=20, blank=True) form.py: from django import forms from django.forms import ModelForm from .models import Pedido class PedidoEditForm(forms.ModelForm): cantidad = forms.IntegerField(widget=forms.TextInput(attrs={'type':'number'})) class Meta: model = Pedido fields = [ 'cantidad', ] views.py: def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad).order_by('-articulo') pedido2 = Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').order_by('-articulo') pedido3 = Pedido.objects.filter(especialidad=especialidad).filter(estado='entregado').order_by('-articulo') if request.method == 'GET': form = PedidoEditForm(instance=especialidad) else: form = PedidoEditForm(request.POST, instance=especialidad) if form.is_valid(): form.save() return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad) return render(request, 'ingresa.html', {'form':form, 'pedido':pedido, 'pedido2':pedido2, 'pedido3':pedido3, 'especialidad':especialidad}) Then the table containing the assigned items is displayed and the {% csrf_token%} to enter the amount to each one after the "send" button to save all the values entered in the quantity field The problem is that it does not add anything and only reloads the page and does not save the values entered Any suggestions please help me colleagues! -
NOT NULL constraint failed: app_userprofile.user_id
I am new to django and trying to learn how to make a simple app with it. I did managed to get a sign in sign up in the same view function working. However when I started adding models and and forms I messed it up and I do not really understand what is wrong. I have spend a day looking for solution, but just I can't figure it out. Any help? models.py class UserProfile(models.Model): user = models.OneToOneField(User) def __unicode__(self): return self.user.username class Posts(models.Model): content = models.CharField(max_length=150) user = models.ForeignKey(UserProfile) creation_date = models.DateTimeField(auto_now=True, blank=True) forms.py class UserSignUpForm(forms.ModelForm): username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username', 'class' : 'username'})) password = forms.CharField(required=True, widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password', 'class' : 'password'})) def is_valid(self): form = super(UserSignUpForm, self).is_valid() for f, error in self.errors.items(): if f != '__all_': self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)}) return form class Meta: model = UserProfile fields = ('username', 'password',) class PostsForm(forms.ModelForm): posts = forms.CharField(max_length=150, widget=forms.widgets.TextInput(attrs={'placeholder': 'What\'s in your mind?'})) class Meta: model = Posts fields = ('posts',) views.py def index(request): if request.user.is_authenticated(): user = request.user return render(request, 'userHome.html', { 'user': user, 'posts' : posts }) return render(request, 'userHome.html') def signup(request): context = RequestContext(request) registered = False if request.method == 'POST' and 'signIn' in request.POST: username = … -
ERROR: Your requirements.txt is invalid. Snapshot your logs for details
I am new to AWS CLI USAGE. So do explain me the error clearly so that i don't make that mistake next time. Here is my requirements.txt file : appdirs==1.4.3 cssselect==1.0.1 dj-database-url==0.4.2 Django==1.11 django-ckeditor==5.2.2 Markdown==2.6.8 packaging==16.8 psycopg2==2.5.4 pyparsing==2.2.0 pytz==2017.2 six==1.10.0 Here are my files inside .ebextensions directory : django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "awsbean.settings" aws:elasticbeanstalk:container:python: WSGIPath: cv_web/wsgi.py packages.config packages: yum: git: [] python.config container_commands: 01_migrate: command: "python src/manage.py migrate --noinput" leader_only: true And here is my config.yml file inside .ebextensions/.elasticbeanstalk : branch-defaults: default: environment: environment environment-defaults: environment: branch: null repository: null global: application_name: cv_web default_ec2_keyname: aws-eb2 default_platform: Python 3.4 default_region: ap-south-1 instance_profile: null platform_name: null platform_version: null profile: eb-cli sc: null workspace_type: Application -
Django cannot find my static files
I am relatively new to web dev. and I am trying to build my first web application. I have my static folder in project_root/static but for some reason, I keep getting 404s when I run the server: Not Found: /users/login/js/bootstrap.min.js for example. I have {% load staticfiles %} at the top of my html and in my settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Thanks. -
Django Admin: Why does my model name have a space after underscore?
My Model: class Venue_Event(models.Model): user = models.ForeignKey(Profile, db_index=True, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, on_delete=models.CASCADE) When I go into the admin UI, I see a space after the underscore. Any idea why? screenshot -
How validate my html form in django?
I have a problem with validate my form in django. When i choose for example "Premia" in my form i received error : ValueError at /add_income invalid literal for int() with base 10: 'Premia' What's get wrong ? models.py class Przychod(models.Model): autor = models.ForeignKey('auth.User') kategoria = models.CharField(max_length=100) typ = models.CharField(max_length=50) nazwa = models.CharField(max_length=200) kwota = models.FloatField() data = models.DateField(default=timezone.now) views.py def add_income(request): c = {} c.update(csrf(request)) kategoria = request.POST.get('kategoria') typ = request.POST.get('typ') nazwa = request.POST.get('nazwa') kwota = request.POST.get('kwota') data = request.POST.get('data') income = Przychod(kategoria,typ,nazwa,kwota,data) income.save() return render(request, 'budzet_domowy_aplikacja/twoje_przychody.html', c) html file <!-- HTML Form (wrapped in a .bootstrap-iso div) --> <div class="bootstrap-iso"> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <div class="formden_header"> <h2> </h2> <p> </p> </div> <form class="form-horizontal" method="post" action="add_income">{% csrf_token %} <div class="form-group "> <label class="control-label col-sm-2" for="kategoria"> Kategoria </label> <div class="col-sm-10"> <select class="select form-control" id="kategoria" name="kategoria"> <option value="Pensja"> Pensja </option> <option value="Umowa o dzieło "> Umowa o dzieło </option> <option value="Premia"> Premia </option> <option value="Odsetki z lokat"> Odsetki z lokat </option> <option value="Przychody z najmu"> Przychody z najmu </option> <option value="Renta"> Renta </option> <option value="Alimenty"> Alimenty </option> <option value="Stypendia"> Stypendia </option> <option value="Zwrot podatku"> Zwrot podatku </option> <option value="Inne"> Inne </option> </select> </div> </div> <div class="form-group "> … -
Django rest framework AttributeError: can't find field on Serializer
Background context I'm using django rest framework and django-rest-auth to build an API. My authentication scheme doesn't use the default authentication of just the email/username and password and requires other data present on the Profile model. For this reason, I'm using a custom registration serializer and overriding the REGISTER_SERIALIZER class in the settings. This is the serializer as follows: class UserRegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=get_username_max_length(), min_length=allauth_settings.USERNAME_MIN_LENGTH, required=allauth_settings.USERNAME_REQUIRED ) email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) profile = UserProfileSerializer() .............. Validation methods .............. def custom_signup(self, request, user): pass def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) profile_data = self.validated_data.pop('profile', {}) user_repo.create_object(user=user, **profile_data) return user The problem The serializer and the corresponding endpoint works in that it is creating the user and the associated profile, but in the serializing step when returning the response, I get the following error: KeyError: "Got KeyError when attempting to get a value for field `profile` on serializer `UserRegisterSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `OrderedDict` instance. Original exception … -
Deploying django - what can I run with gunicorn?
This is how I deploy a django (version 1.11.1) project with gunicorn (version 19.6.0), nginx and systemd: $ sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=teelou Group=www-data WorkingDirectory=/var/www/html/django-project/helloapp ExecStart=/var/www/html/django-project/helloapp/env/bin/gunicorn --workers 3 --bind unix:/var/www/html/django-project/helloapp/helloapp.sock helloapp.wsgi:application [Install] WantedBy=multi-user.target And I can get this sample project working at http://127.0.1.1:8000/. It shows the django default welcome screen. But I am taking over this legacy project which is on Django >= 1.5 and gunicorn == 18.0. And I cannot get it running with gunicorn and nginx. This is what I am provided with a ~/services/gunicorn.template: #!/bin/bash SCRIPT=$(readlink -f $0) SCRIPTPATH=`dirname $SCRIPT` # go one dir up PROJECT_ROOT=`dirname $SCRIPTPATH` cd $PROJECT_ROOT source .env/bin/activate exec \ setuidgid %(USER)s \ python manage.py run_gunicorn \ 127.0.0.1:%(PORT)s \ --workers=4 \ --timeout=180 \ --log-file=$PROJECT_ROOT/logs/gunicorn.log \ --graceful-timeout=10 \ --log-level=DEBUG \ --worker-class=eventlet \ --debug So what can I run this with gunicorn and nginx? -
Deserializing a model with an additional field
I'll be as straightforward as possible: I have a Challenge model, which holds information about a certain challenge and the amount of scores it gives. Any User can have multiple Submissions for a given challenge. When querying for a specific Challenge, I want to return JSON with the Challenge's information along with the maximum score that the current request.user has scored. Is there a way to somehow ducktype (attach) the value to the model instance and serialize it with a given Serializer class? What I've found is that ModelSerializer requires the model to have that field itself, where in my case I add it dynamically. What's a good approach to this problem and has anybody had any similar problems? -
Use this new application in Django
I install Django developer panel, but I don't really know how to use this new application (https://github.com/loftylabs/djdevpanel-devtools). Could anyone have time to explain to me how it works? DEBUG = True MIDDLEWARE_CLASSES = [ 'djdev_panel.middleware.DebugMiddleware', <-- Here!!! 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'loanwolf.middlewares.LocaleMiddleware', ] and I install correctly the extension Django Developer Panel.