Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data is not validating in formset django. Error "The NameOfModel could not be created because the data didn't validate."
I'm building a formset but when I try to save the data appears the erros "The Fields could not be created because the data didn't validate." My forms.py class Formulario(ModelForm): class Meta: model = Fields fields = ['name','type'] FieldsFormSet = formset_factory(Formulario) My views.py class BuildForm(CreateView): template_name = 'formulario.html' model = Fields form_class = Formulario success_url = 'success/' def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) fields_form = FieldsFormSet(self.request.POST,self.request.FILES) if fields_form.is_valid(): return self.form_valid(form, fields_form) else: return self.form_invalid(form, fields_form) def form_valid(self, form, fields_form): self.object = form.save() fields_form.instance = self.object fields_form.save() template.html <form action="." method="POST">{% csrf_token %} <div class="section"> </div> <h2>Todo Items</h2> {{ fields_form.management_form }} {% for form in fields_form.forms %} <div class="item"> {{ form.as_p }} <p style=""><a class="delete" href="#">Delete</a></p> </div> {% endfor %} <p><a id="add" href="#">Add another item</a></p> <input type="submit" value=" Submit " /> </form> Weird is, it does validate until form_valid() -
Undefined name 'arg'
@python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, null=True) phone = PhoneField(_('Phone'), max_length=50, blank=True, null=True) phone_extension = models.CharField(_('Extension'), max_length=10, blank=True, null=True) job_title = models.CharField(_('Job title'), max_length=50, blank=True, null=True) date_hired = models.DateField(_('Date hired'), blank=True, null=True) supervisor_name = models.CharField(_('Supervisor name'), max_length=50, ... blank=True, null=True) has_missing_fields = models.BooleanField(_('Has missing informations'), default=True) manual_validation = GenericRelation(ManualFieldValidation) Here is a function I would like to modify in using a metaclass def clean_fields(self): if income_source != 'Employed': to_empty = [ "company_name", "job_title", "date_hired", "supervisor_name", "phone", "phone_extension", "civic_number", "street", "address_line_2", "city", "state", "zip_code", ... ] for field_name in to_empty: setattr(self, field_name, None) super(EmployerProfile, self).save(*args, **kwargs) Could anyone be able to tell why I have this type of error for the line super(EmployerProfile, self).save(*args, **kwargs)? I took few time to figure out what was the problem, but without success. -
'UserManager' object has no attribute 'login_user'
So the error is in line 28 of my views.py file. However I can't seem to find where the issue lies. my views and my models.py file look fine. It happens when you click the login button on the login page. 'UserManager' object has no attribute 'login_user' the traceback is as follows: Environment: Request Method: POST Request URL: http://localhost:8000/users/login Django Version: 1.10.6 Python Version: 2.7.10 Installed Applications: ['apps.logReg', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\django2\loginReg\loginReg\apps\logReg\views.py" in login 28. viewsResponse = User.objects.login_user(request.POST) Exception Type: AttributeError at /users/login Exception Value: 'UserManager' object has no attribute 'login_user' Index html <!DOCTYPE html> <html> <head> <title>Login and Registration</title> </head> <body> {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} <div class="register"> <h1>Register</h1> <form class="" action="{% url 'users:register' %}" method="post"> {% csrf_token %} <p>First Name: <input type="text" name="first_name" value=""></p> <p>Last Name: <input type="text" name="last_name" value=""></p> <p>Email: <input type="text" name="email" value=""></p> <p>Password: <input type="Password" name="password" value=""></p> <p>Confirm Password: <input … -
Undefined name 'income_source'
@python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, null=True) phone = PhoneField(_('Phone'), max_length=50, blank=True, null=True) phone_extension = models.CharField(_('Extension'), max_length=10, blank=True, null=True) job_title = models.CharField(_('Job title'), max_length=50, blank=True, null=True) date_hired = models.DateField(_('Date hired'), blank=True, null=True) supervisor_name = models.CharField(_('Supervisor name'), max_length=50, ... blank=True, null=True) has_missing_fields = models.BooleanField(_('Has missing informations'), default=True) manual_validation = GenericRelation(ManualFieldValidation) Here is a function I would like to modify in using a metaclass def clean_fields(self): if income_source != 'Employed': to_empty = [ "company_name", "job_title", "date_hired", "supervisor_name", "phone", "phone_extension", "civic_number", "street", "address_line_2", "city", "state", "zip_code", ... ] for field_name in to_empty: setattr(self, field_name, None) super(EmployerProfile, self).save(*args, kwargs) Maybe it is a silly question, but I've done many research, but I didn't find a satisfying answer. I have an error where income_source is located in the function. Do I have to write income_source, customer.income_source, customer(income_source=income_source) or ...? In fact, I am confusing because income_source come from CustomerProfile, but I don't know how to use it from a OneToOneField. -
How to append to an array content from text files?
Can you explain me ,why this code: from django.http import JsonResponse from django.core import serializers def getData(request): arr = [] with open('test1.txt') as test1: arr.append( test1.read() ) with open('test2.txt') as test2: arr.append( test2.read() ) serializedData = serializers.serialize('json', arr) return JsonResponse(serializedData) Return this warning message ? : 'str' object has no attribute '_meta' I just wanna append to an array content from two text files. That's all -
Way to write in a function
@python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, null=True) phone = PhoneField(_('Phone'), max_length=50, blank=True, null=True) phone_extension = models.CharField(_('Extension'), max_length=10, blank=True, null=True) job_title = models.CharField(_('Job title'), max_length=50, blank=True, null=True) date_hired = models.DateField(_('Date hired'), blank=True, null=True) supervisor_name = models.CharField(_('Supervisor name'), max_length=50, ... blank=True, null=True) has_missing_fields = models.BooleanField(_('Has missing informations'), default=True) manual_validation = GenericRelation(ManualFieldValidation) Here is a function I would like to modify in using a metaclass def clean_fields(self): if income_source != 'Employed': to_empty = [ "company_name", "job_title", "date_hired", "supervisor_name", "phone", "phone_extension", "civic_number", "street", "address_line_2", "city", "state", "zip_code", ... ] for field_name in to_empty: setattr(self, field_name, None) super(EmployerProfile, self).save(*args, kwargs) Maybe it is a silly question, but I've done many research, but I didn't find a satisfying answer. I have an error where income_source is located in the function. Do I have to write income_source, customer.income_source, customer(income_source=income_source) or ...? -
Python.exe crashes when on runserver
Before the problem occurred I was learning how to create projects and apps in Django. After I decided to remove the project folder and create a new project I have stacked on runserver. Before asking this question I have been trying to figure out the problem for few days. The only solution is to unistall+ install Python 3.6 and it works once only: PS C:\WINDOWS\system32> cd d:\py\piglatin PS D:\py\piglatin> python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly unti auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 19, 2017 - 01:44:42 Django version 1.10.6, using settings 'piglatin.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [19/Mar/2017 01:50:52] "GET / HTTP/1.1" 200 1767 PS D:\py\piglatin> python manage.py runserver PS D:\py\piglatin> python manage.py runserver PS D:\py\piglatin> python manage.py runserver I have done all migrations but still Python crashes. -
Page not found 404 when clicking login button
OK so I have the registration working fine. I have an error somewhere that is trowing the error of the following Request Method: POST Request URL: http://localhost:8000/users/%7Burl%20'users:login'%20%25%7D Using the URLconf defined in loginReg.urls, Django tried these URL patterns, in this order: ^users/ ^$ [name='index'] ^users/ ^register$ [name='register'] ^users/ ^success$ [name='success'] ^users/ ^login$ [name='login'] ^users/ ^logout$ [name='logout'] The current URL, users/{url 'users:login' %}, didn't match any of these. The rest of the form works when i take out the login section so I tend to lean that way.I have included the models.py urls.py and parts of the two html I am hoping someone can see the error im missing. Index html <!DOCTYPE html> <html> <head> <title>Login and Registration</title> </head> <body> {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} <div class="register"> <h1>Register</h1> <form class="" action="{% url 'users:register' %}" method="post"> {% csrf_token %} <p>First Name: <input type="text" name="first_name" value=""></p> <p>Last Name: <input type="text" name="last_name" value=""></p> <p>Email: <input type="text" name="email" value=""></p> <p>Password: <input type="Password" name="password" value=""></p> <p>Confirm Password: <input type="password" name="confirm_password" value=""></p> <input type="submit" name="" value="Register"> </form> </div> <div class="login"> <h1>Login</h1> {% csrf_token %} <form class="" action="{url 'users:login' %}" method="post"> <p>Email: <input type="text" … -
How to show entire existing postgres database in Django admin view
I have an existing PostgreSQL database and I'd like to browse it within Django's admin view. How do you make all the existing tables in a database browsable in Django's admin view? I tried following the steps here but I was only able to view Groups and Users. I also read that maybe I have to edit admin.py but I'm not sure where that file would be located and what I'd have to put in it. -
Django - Displaying model data on html
I displayed for my index but couldn't display for my detail here are my codes. I can see the data on index but cant see on detail. index codes are on the below. {% for total_amount in receipt_list %} <tr class="active"> <td>{{ total_amount.id }}</td> <td>{{ total_amount.amount }}</td> <td>{{ total_amount.vat }}</td> <td>{{ total_amount.total_amount }}</td> <td><a href="{% url 'detail' total_amount.id %}">Click for the details...</td> </tr> {% endfor %} and my detail.html code is ... {% for receipt in object_list %} <tr class="active"> <td>{{ receipt.id }}</td> <td>{{ receipt.name }}</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td> </tr> {% endfor %} how can I do it ? , didn't understand the logic I guess... for receipt in object_list doesn't work ? -
NoReverseMatch at / error
I know that there are many solutions to this problem in the Internet, but what I would do is receive such a error - Reverse for 'get_category' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['category/(?P[^/]+)']. template <a href="{% url 'get_category' category.alias %}"> views def products(request, alias): try: product = Items.objects.get(alias=alias) title = product.name except: raise Http404("Объект не найден") context = { } return render(request, 'product/product.html', context) def get_category(request, alias): try: category = Category.objects.get(alias=alias) products = Items.objects.filter(category=category) except: raise Http404('Объекты не найден') context = { 'products': products, 'category': category, } return render(request, 'popular/popular.html', context) urls url(r'^$', views.popular, name='popular'), url(r'^products/(?P<alias>[^/]+)', views.products, name='product'), url(r'^category/(?P<alias>[^/]+)', views.get_category, name='get_category'), -
Getting the "facebook code" to obtain long-lived-access-token from server side. Django
I'm trying to follow this doc to get a long-lived user token. (see "Generating Long-Lived User Tokens from Server-Side Long-Lived Tokens") The diagram is quite explicit, and I thought it should be easy. But the problem comes when I try to get the "code." As you can see, this should be the request: https://graph.facebook.com/oauth/client_code?access_token=...&amp;client_secret=...&amp;redirect_uri=...&amp;client_id=... But the problem is that since I'm on the Server side, I'm not able to redirect the user since that's a client work. (Isn't it?) So, since I got this error: { "error": { "message": "Missing redirect_uri parameter.", "type": "OAuthException", "code": 191, "fbtrace_id": "EqPakhHX9i6" } } I tried this: &amp;redirect_uri=https://www.google.com/&amp; (to see if it eats that URI) But no chance. I was looking for similar questions, but people use to use the client side, and I don't have any access to the Client. Actually, the client is waiting for this code from me, as the diagram shows. So, I don't have any idea how I can do it. Maybe someone here had the same problem. -
celery not getting tasks from Django Admin Periodic Tasks
Using celery 3.1.25 with Django 1.10 I can get celery to run tasks by manually getting into the shell and manually launching the tasks. However when I set a task from the django/admin/PeriodicTasks (run every minute), these tasks are not picked up by celery. I'm using flower to check the status but I don't see any failing task. The broker node is called celery@USER-vm instead of default, so I don't know if that is affecting this. my command to run celery is python manage.py celery -A proj worker --loglevel=INFO -B Any insight of where to look? MY best guess is that djcelery is not connected to rabbitmq, but not sure where to make those changes. Thanks! -
Django model with only foreign keys
I have an existing database, which cannot be changed. It contains three tables: A: a_id [primary key] B: b_id [primary key] A_B: a_id [foreign key] b_id [foreign key] I want to create django models for these tables. Since django requires each model to have one primary key, model for the A_B table will have autogenerated primary key, eg. A_B_id. This is a problem, because the database schema cannot be changed. Is it possible in django to use tables which have only foreign keys? How could this problem be solved? -
Index lists of lists using forloop.counter in template
I have list of lists like the following one : altcrit = [ [something1,something2] , [somethingelse1,somethingelse2] ,,,, ] I pass the list as context in my template . My template follows : <form method='POST'> {% csrf_token %} {{ criterion_value_formset.management_form }} {% for form in criterion_value_formset %} {% with index=forloop.counter0 %} {{ altcrit.index.1 }} {%for field in form %} {{ field }} {% endfor %} {% endwith %} {% endfor %} </form> Im expecting the {{ altcrit.index.1 }} to properly show the second variable of the list in the position 'index' of the outer list . Instead nothing shows up . But when I replace the 'index' in {{ altcrit.index.1 }} with 1 the expected value of the list of lists shows up . Meaning : {{ altcrit.1.1 }} Show the question is why is this happening ? -
django-coupons cannot import name 'patterns' in a dockerized django web app
Im trying docker for the first time and its going fine. I know that 'patterns' was deprecated in Django 1.8 and have made necessary changes to the package (django-coupons) because it triggers an error saying the same, however i would like to use this package in a docker image and i am unable to make the same changes as i have on the local env. Could anyone advise on the best way to go about this? Here is my Dockerfile. It is same as the one i found on the Docker tutorial for Django .Here is my Dockerfile. FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ It is same as the one i found on the Docker tutorial for django here. Thanks in advance. -
Django - not getting the value from database to show in dropdown list
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar and need to fill the form. Association-dropdown-list won't show any data from database. I only want it to show association name of the current admins-association. Is there something i'm missing? Still a newbie so appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': res = {'success': False} if paramMissing(request.POST, 'name', res) \ ... or paramMissing(request.POST, 'association', res) \ or paramMissing(request.POST, 'synced', res): return JsonResponse(res) ... association = Association.objects.filter(asoc_name=request.user.association) asoc = request.POST[association] if action == 'add': Event.objects.create( ... association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] = eid res['data'] = Event.objects.values().get(id=eid) calendar.js ... $addEventAsoc: $("#add-event-asoc") showAddForm: function () { cal.$addEventAction.val("add"); cal.$addEventSynced.val("false"); ... var association = $(this).val("association"); alert (association); $.ajax ({ type: "GET", url: '/calendar/', data: association, success: function(data) { cal.$addEventAsoc.val(data); }, error: function (error_data) { console.log("error"); console.log(error_data) } }); calendar.html ... <li class="form-li"> <label for="add-event-asoc" class="input-name"> Association</label> {% for asoc in Association %} <select id="add-event-asoc" name="association"><option value="{{ association.id }}">{{ association.asoc_name }} </option> … -
Validating field input agianst field in different model
I have two separate models and want to validate the input on one Model Form based on data that already exists in the other model. In the simplified example below, I would like to validate that "nest_egg" in the Retirement model is larger (bigger value) than "current_savings" in the Bank model. class Bank(models.Model): current_savings = models.DecimalField(max_digits=20, decimal_places=2) class Retirement(models.Model): nest_egg = models.DecimalField(max_digits=20, decimal_places=2) nest_egg must be larger than current_savings Ideally this would happen on the Retirement model form when the user tries to enter a lower amount for "nest_egg" than the value of "current_savings". When the user is shown the Retirement Model Form, the Bank Model would already have a value for "current_savings". I am able to do the validation using a clean_nest_egg Method on the Model Form as long as I code a hard value. However, I need this to be dynamically set based on the value in the first model. Should this be done in the view as part of form_valid? Or is there a way to do validation on the model form using a value from a different model inside the Model Form? Thanks for reading. Any help would be greatly appreciated. -
Differentiating 2 identical forms with one button in Django
I have a form where the user selects the number of guests. On submission, a new page is rendered with another form for each guest. I feel like the way I did it is kind of hacky so I'm open to suggestions, but it needs to be completely in Django w/o jquery or js. In views.py I'm querying the db for the number of guests the person is bringing, then creating a loop range to pass to the template in context, because from what i understand Django/Jinja doesn't truly support numeric range in for loops: def rsvp_user(request): invitee = Invitee.objects.get(code=request.POST['code']) count = invitee.guests_count context = { 'invitee': invitee, 'loop': range(1, count+1), } return render(request, 'wedding/rsvp_detail.html', context) My template then loops over that range and renders my form that many times: {% for i in loop %} <div class='col-sm-9'> <form action="{% url 'wedding:rsvp_process' %}" method="POST"> {% csrf_token %} <h3>Guest # {{i}}</h3> <div class="form-group"> <label>Name as you'd like it on your place card</label> <input name="name" type="text" class="form-control" input"> </div> <div class="form-group"> <label>Dietary restrictions</label> <textarea name="restrictions" rows="5", cols="50"></textarea> </div> <div class="form-group"> <label>Dinner Selection</label> <select name="dinner"> <option value="chicken">Chicken Parm Parm</option> <option value="beef">Beef Wellington</option> <option value="fish">Salmon Limon</option> </select> </div> <button class=".btn btn-primary pull-right">Save guest details</button> … -
GET form <Button> not redirecting, <a> not passing kwarg
If I use a button in the get form it doesn't redirect to the search page using the kwarg, if I use a it redirects but passes an empty object. Trying to write a function that filters my model objects based on a parameter set through a form. User selects a project engineer and only sees projects that they're assigned to. I'm somewhat new to django. Just trying to make a user controlled filter... I'm not getting any error messages. This is my template {% extends 'projects/base.html' %} {% block content %} <div> <form method="GET"> <button href="{% url 'project_search' project_engineer=project_engineer %}" class="save btn btn-default">Search by Project Engineer</button> <select name="project_engineer"> {% for pe in pe_list %} <option value="{{ pe }}">{{ pe }}</option> {% endfor %} </select> </form> </div> {% for post in posts %} <div> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.name }}</a></h1> <p>{{ post.description|linebreaksbr }}</p> <p>Project Engineer: {{ post.project_engineer|linebreaksbr }}</p> <p>Last Modified: {{ post.published_date }}</p> </div> {% endfor %} {% endblock %} This is my views def project_list(request): posts = Project.objects.filter(published_date__lte=timezone.now()).order_by('published_date') pe_list=["all"] for x in range(0, len(posts)): if posts[x].project_engineer not in pe_list: pe_list.append(posts[x].project_engineer) return render(request, 'projects/project_list.html', {'posts': posts, 'pe_list': pe_list}) def project_search(request, project_engineer): variable_column = 'project_engineer' search_type = 'contains' filter … -
Django Rest Framework join 2 tables on non- foreign key fields
I am using Django for my website, and hence decided to use Django Rest Framework for building my REST APIs. However there is a common issue that i am facing when joining tables. If the join is defined on direct foreign keys, everything works fine. However when the joins are defined on non-direct foreign key fields, things go haywire. Eg, i store stats for players in one table. (Stats table has 1 fk -> player) i store participants in competitions in another table (This table has 2 fk -> player, competition) If i retrieve stats information with player metadata, everything works fine. But i want to retrieve stats for all player in a given competition. In SQL, i can join participant table with stats table on player id (common fk, but no direct link between the two tables as far as Django is concerned ie nothing is defined on the individual models of the 2 tables) and then filter on competition. select a.* from Stats a inner join Participants b on a.player = b.player where competition = '%s' How to replicate this using Django objects syntax? What i want to convert it to: something on the lines of, Stats.objects.filter(stats__competition = … -
Setting inital form data
Below I paste snippet of user's profile edition view, I think it isn't necessary to paste all view here. I want to set initial data, when user want to edit his profile he should see data which is actually stored in database. form = UserProfileForm(initial={'first_name': user.userprofile.first_name, 'last_name': user.userprofile.last_name, 'nickname': user.userprofile.nickname, 'bio': user.userprofile.bio, 'location': user.userprofile.location, 'gender': user.userprofile.gender, 'birth_date': user.userprofile.birth_date}) I've created above code and it works fine, but I think it isn't pythonic at all, so my request is about how can I write it better? -
How to avoid duplication in Model Manager by using ValueError in model method
I worked through documentation / examples to get to the code below. It works, but I'd like to receive some help from an experienced developer as this is not the most efficient code: Checking_account.objects.get(user=request.user) is used 2 times (in the model manager and the view) ‘Not enough cash’ check is performed 2 times (in the model manager and the view) Question: is it possible to use the “ValueError” raised in the model method as trigger to display a message in the template + the link towards the "deposit_checkin_account_page" (and in this way avoid duplication in the Model Manager & view) or should this be solved in a complete different way? All suggestions are welcome! Thanks! Models.py: class Checking_accountManager(models.Manager): def check_balance(self, user, value): if Checking_account.objects.filter(user=user).exists(): checking_account = Checking_account.objects.get(user=user) if value <= checking_account.current_balance: return True else: return False class Checking_account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) current_balance = models.DecimalField(_('Balans'), max_digits=18, decimal_places=8, default=0) objects = Checking_accountManager() def deposit(self, value): self.current_balance += value self.save() def withdraw(self, value): if value > self.current_balance: raise ValueError('not enough cash') self.current_balance -= value self.save() Views.py: view buy (request, item): item = item.objects.get(item=item) cost = item.cost if Checking_account.objects.check_balance(user=request.user, value=quote_cost): checking_account = Checking_account.objects.get(user=request.user) checking_account.withdraw(cost) messages.success(request, _('Succes.')) else: messages.error(request, _('no checking account yet or … -
Running Migrations with Django to a Remote Database
I am attempting to run migrations from an app Server to a remote db server with Django and Postgresql 9.5. These are separate Ubuntu 16.04 EC2 instances. Django lives in a conda environment on the app server, while Postgresql is globally installed on the db server. I've installed psycopg2 in the conda environment of the app server, not on the db server. Django db settings: DATABASES: { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "mysite", "USER": "postgres", "PASSWORD": "", "HOST": "10.0.XX.XXX", "PORT": "5432" }, } Added entry to Postgresql pg_hba_conf file (ip address of app server): host all all 10.0.XX.XX trust I get the following error: Is the server running on host "10.0.XX.XXX" and accepting TCP/IP connections on port 5432? Both EC2 instances are on the private subnet of a custom VPC. The security group settings for each machine allow any form of incoming traffic within the private subnet. This is a test site so there's no password because there's no public ip or users (but me). What am I missing here? -
Creating Tutorial upon first login
I am currently using python social auth to login users into my Django app and show a tutorial upon first user creation. I've tried this so far but request does not work in pre_save signals. Is there another way to do this? @receiver(pre_save, sender=User) def show_tutorial(sender, instance=None, **kwargs): # For first time creation of user display tutorial if instance._state.adding: print ('USER CREATED') request.session['first_login'] = True