Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Null value in column "periodictask_id" violates not-null constraint
How do I get rid of the "null value in column "periodictask_id" violates not-null constraint" Schedule table in PostGres 1d, email_id, name, email_contact_name_id, message, start_date, time_recurrences, periodictask_id When I submit forms, I get the following: Errors Exception Type: IntegrityError Exception Value: null value in column "periodictask_id" violates not-null constraint DETAIL: Failing row contains (23, 1, ghty, 1, help too, 2017-06-30, 06:00:00, RRULE:FREQ=WEEKLY;UNTIL=20180630T050000Z;BYDAY=WE,TH,FR, null). Exception Location: /usr/local/lib/python3.4/site-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /usr/local/bin/python3.4 model.py class Schedule(models.Model): email = models.ForeignKey(MyCustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=30, default='Example') email_contact_name = models.ForeignKey(Upload) # default='Empty') message = models.CharField(max_length=918) start_date = models.DateField() time = models.TimeField() recurrences = RecurrenceField() # for PeriodicTask under "djcelery" model.py periodictask = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('msgapps.views.CreateEMAIL_Sch', args=[str(self.id)]) signal.py @receiver(pre_save, sender=Schedule) def create_crontab_schedule(sender, instance, created=False, **kwargs): if created is None: ................... ................... # Create the schedule object in database. schedule, _ = CrontabSchedule.objects.get_or_create( minute=time_minute, hour=time_hour, day_of_week=d_of_w, day_of_month=d_of_m, month_of_year='*', ) PeriodicTask.objects.create( crontab=schedule, name=instance.name, task='malak.task.send_email', #args=json.dumps(['arg1', 'arg2']), #kwargs=json.dumps({ # 'be_careful': True, # }), #enabled=True, #crontab_id=schedule.id, ) instance.periodictask = PeriodicTask.id forms.py class ScheduleEMAIL(forms.ModelForm): class Meta: model = Schedule fields = ('name', 'phone_contact_name', 'message', 'start_date', 'time', 'recurrences') widgets = { 'message': Textarea(attrs={'cols': 15, 'rows': 3}), 'start_date': AdminDateWidget(), 'time': AdminTimeWidget(), } labels = … -
Django - Redirect user to "next" parameter after successful login
In my code, I am currently using the @login_required decorator. As far as I know (and can see in the URL), this passes to my login view a next parameter holding the original page the user was on. After checking the user's credentials, I'm trying to redirect him to the original page, but I can't figure out how to do it. I'm sure this must be really straightforward, but I've been stuck on it for quite some time and I had to ask for help before throwing away my keyboard. My view code is as follows: from django.contrib.auth import login as auth_login, authenticate def login(request): form_class = LoginForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) return redirect(?????????) else: #Error message return render(request, 'login.html', {'form':form_class}) -
Django does not create ImageField on Postgres
I added a new ImageField in my models.py: class User(AbstractUser): [more_fields_here] profile_picture = models.ImageField(upload_to='profile_pictures', null=True) I ran python manage.py makemigrations and then python manage.py migrate without any errors. But when I run my application I am getting: ProgrammingError at column authentication_user.profile_picture does not exist I checked in the Postgres database and the column profile_picture does not exist. I deleted the migrations and tried again, but I am still getting the same error. In the migrations/0001_initial.py there is the line: ('profile_picture', models.ImageField(null=True, upload_to='profile_pictures')), But why does the column not exist in the table? -
How to use React with Django when i have json connection
This is my project structure and i want to use React to show sorted data from elasticsearch database in my browser. Should i use Rest DJango to get json from elastic and then make user view with react? Maybe u know better option, but still with returning json data because i will need it in future python scripts. |---------| |---------| |DJANGOAPP| ---JSon(Elasticsearch().search() object)--->|BROWSER | (Here i wanna | | | | | to use React) |---------| | |---------| | | (-------------) ---> |-------------| (Elasticsearch) (Elasticsearch-dsl |Future python| ( ) in django app) | scripts | (-------------) |-------------| -
How do i allow users to test codes in my site and get result just like fiddle
I want users to be able to test code live on the site and see result just like fiddle and codepen. How do i get this done in django or php. -
Positioning of a HTML checkbox in Django Admin Form
I created a HTML checkbox which looks like a button. I use it in a Django Admin Form in order to select all BooleanField. It works very well but I don't know how to put the checkbox above the Booleans. The checkbox is in change_form.html which is specific to this form and I can put this one on top or bottom of the form but not in specific field. How can I put my checkbox on the field I want ? Maybe with forms.css but I do not succeed to custom this file. The path "{% static "admin/css/forms.css" %}" must confuse me. I put forms.css file in myproject/myapp/static/admin/css/forms.css and that doesn't work. Any idea ? -
how to solve ValueError in Django
I want to save the values from the form into Database, but I got Value Error when i run it. I have created the form in timesheet.html. The error is like this : ValueError at /hrfinance/timesheet/ The view hrfinance.views.timesheet didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/hrfinance/timesheet/ Django Version: 1.11.1 Exception Type: ValueError Exception Value: The view hrfinance.views.timesheet didn't return an HttpResponse object. It returned None instead. timesheet.html <form method="POST" onsubmit="return validation()"> {% csrf_token %} <div class="content-wrapper"> <div class="sub-content"> <div> <p>Student ID: {{timesheet.studentID}}</p> <input id="sid" type="field" name="studentid"> </div> </div> <div class="sub-content"> <div> <p>Student Name: {{timesheet.studentName}}</p> <input id="sname" type="field" name="studentname"> </div> </div> <div class="sub-content"> <div> <p>Start Date: {{timesheet.startDate}}</p> <input id="sdate" type="date" name="startdate"> </div> </div> <div class="sub-content"> <div> <p>End Date: {{timesheet.endDate}}</p> <input id="edate" type="date" name="enddate"> </div> </div> </div> <div class="end-content"> <div class="center-align"> <div class="checklist"> <p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship allowance.</p> <input id="agree" type="checkbox" name="checkbox" class="tick-att"> </div> <br> <div class="align-right"> <input type="submit" class="button" name="submit" value="submit" > </div> </div> </div> </form> models.py class Timesheet(models.Model): studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="") studentName = models.CharField("Student Name", max_length=500, default="") startDate = models.DateField("Start Date", max_length=8) endDate = models.DateField("End … -
virtualenv: cannot access lib: No such virtualenv or site directory
I am using Google Cloud Platform to create a Django based http API, which uses Google's cloud SQL API and Machine Learning API. I made a django-mysql app on my pc and is able to test it successfully on localhost. I want to deploy this app to Google Cloud. Following are my relevant files: app.yaml:- runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /static static_dir: static/ - url: .* script: mysite.wsgi.application libraries: - name: MySQLdb version: 1.2.5 - name: numpy version: "1.6.1" skip_files: - ^(.*/)?- ^(.*/)?.*~$ - ^(.*/)?.*\.py[co]$ - ^(.*/)?.*/RCS/.*$ - ^(.*/)?\..*$ - ^env/.*$ appengine_config.py:- from google.appengine.ext import vendor import os vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) I am getting a 500 error on api home. here. I am getting the following error report on my dashboard:- Traceback (most recent call last): File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 351, in __getattr__ self._update_configs() File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 287, in _update_configs self._registry.initialize() File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/lib_config.py", line 160, in initialize import_func(self._modname) File "/base/data/home/apps/b~neuralnet-171308/20170628t204601.402294282540056750/appengine_config.py", line 18, in <module> vendor.add('lib') File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/vendor/__init__.py", line 44, in add 'No such virtualenv or site directory' % path) ValueError: virtualenv: cannot access lib: No such virtualenv or site directory Originally the appengine_config.py contained:- from google.appengine.ext import vendor vendor.add('lib') … -
Django Autocomplete Light in admin area is not getting result
I am facing some issue with Django Autocomplete Light in admin area, I doubled checked all configuration and code but I am not sure where is the problem to solve it. It seems that in the Admin page is not getting the Autocomplete Integration. It looks like: Here are part of the code that was developed: views.py from dal import autocomplete from ocup.models import Ocup class OcupAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Ocup.objects.none() qs = Ocup.objects.all() if self.q: qs = qs.filter(titulo__istartswith=self.q) return qs (Ocup.objects.all() brings a lot of objects when used in the terminal, the database is populated) forms.py: from ocup.models import Ocup from dal import autocomplete from django import forms class OcupForm(forms.ModelForm): ocup = forms.ModelChoiceField( queryset=Ocup.objects.all(), widget=autocomplete.ModelSelect2(url='ocup-autocomplete') class Meta: model = Ocup fields = ('__all__') admin.py class OporAdmin(admin.ModelAdmin): form = OcupForm (.......) model.py class Ocup(models.Model): familia = models.ForeignKey(Familia) codigo = models.CharField(max_length=10) titulo = models.CharField(max_length=200) def __str__(self): return self.titulo.encode('utf-8') settings.py INSTALLED_APPS = ( 'dal', 'dal_select2', 'django.contrib.admin', (.....) The javascript files are being loading: I think that I added all pertinent information, with something is missing just let me know. -
Django CSRF Failure After Upgrade 1.9 > 1.11
I've just upgraded an app I'm developing from 1.9 to 1.11 and am getting constant errors on all form posts: CSRF token missing or incorrect. All CSRF tokens were working fine in 1.9. Here is the view: def contact(request): subject = request.GET.get('subject', '') contact_form = forms.ContactForm(subject=subject) if request.POST: contact_form = forms.ContactForm(request.POST) if contact_form.is_valid(): new_contact = contact_form.save() logic.send_contact_message(new_contact, request) messages.add_message(request, messages.SUCCESS, 'Your message has been sent.') return redirect(reverse('contact')) template = 'journal/contact.html' context = { 'contact_form': contact_form, 'contacts': core_models.Contacts.objects.filter(content_type=request.content_type, object_id=request.site_type.pk) } return render(request, template, context) Here is the template: <h4>{% trans "Contact" %}</h4> <form method="POST"> {% include "elements/forms/errors.html" with form=contact_form %} {% csrf_token %} <label for="id_recipient">{% trans "Who would you like to contact?" %}</label> <select id="id_recipient" name="recipient"> {% for contact in contacts %}<option value="{{ contact.email }}">{{ contact.name }}, {{ contact.role }}</option>{% endfor %} </select> {{ contact_form.sender|foundation }} {{ contact_form.subject|foundation }} {{ contact_form.body|foundation }} {{ contact_form.are_you_a_robot|foundation }} <button type="submit" class="success button">{% trans "Send Message" %}</button> </form> -
Pass variables between different python process and ajax
Lately i have been trying to create XHR and i found out that Ajax is the only smooth way for achieving it. Apologies about my lack of understanding in Ajax, I just started it and i may not be doing everything properly. Let's say there is a specific form like this: <div style="margin: 0;float: left;width: 60px;height: 60px;cursor: pointer;text-decoration:none;display: block;padding: 0;"> <form id="item_selection1" action="{% url 'Home:AccountPage' %}" method="post"> {% csrf_token %} <input class="sendtrade" name="sendtrade1" type="submit" value="Send Offer"> </form> This is views.py: ... if request.POST.get('sendtrade1'): ... openbox = "true" ... And this is how i render response ( I know this is not Ajax compatible yet, assume that dict is already converted to json): res = render(request, 'Home/account.html', {'other_keys': 'other_values', 'openbox': openbox}) return HttpResponse(res) And i just normally open the div if openbox is "true": if ("{{ openbox }}" == "true" ) { $("#someDiv").css("display", "block") } else if ( "{{ openbox }}" == "false" ) { $("#someDiv").css("display", "none") } But, Let's what if i execute certain nested function on the other process once post request is received: from multiprocessing import Process ... if request.POST.get('sendtrade1'): ... openbox = "true" ... def func(): time.sleep(10) openbox = "false" proc = Process(target=func) proc.start() ... ... How … -
Django: call standard command from a custom command
In my app, i am using a custom system for managing localization strings. In that connection, I have written a custom command that generates *.po files. However, after running that command, I have to manually call the compilemessages command. What I would like to do is to call the compilemessages command from my custom one. Is there a way to do that? -
Django REST API - FilterView
im currently building a fresh new API for an elarning project with django REST framework. I've build up a few requests but currently stuck on smoething i call "FielterView" or "FilterRequest". First things first; what do I want to achieve with these "Filterviews". I want to send a bit of data, formated in JSON, to this url (for example test-project.de/api/model1_filter ) and let it filter my model1 according to this data. Here my code (views.py): class ListFilterAPIView(generics.ListAPIView): """ A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data.""" varchar_fields = () # Tupel containing all modelfileds which are varcharfields int_fields = () # Tupel containing all modelfileds which are integerfields model_fields = () # Tupel containing all modelfileds which are Model relation fields those are also ints def get_filters(self): """ Method which creates the filters dict. Matches the given Parameters from the request with the allowed lookup_fields, and only maps non-empty fields. """ filters = {} for field in self.lookup_field: # goes on for every field we defined as lookup_field if self.request.GET.get(field, None): if field in self.varchar_fields: # we do not want the filter to contain "empty" fields … -
I need to cache a TemplateView with a querystring - how?
Basically, I'm trying to cache a simple search results page (generated with a TemplateView view) with a URL pattern of: /search/?q=foo I've tried: @cache_page - doesn't work with querystrings (why? the stated reason "querystrings usually do not affect the results" completely depends on 'usually' meaning 'always' which is demonstrably false); django-fancy-cache - doesn't work with CBVs (but in principle appears to do exactly what I want); Adjusting the action on my form with an onSubmit() to change the url pattern (so that there's no querystring) - for SOME reason this messes up every other page on the site even though the test form doesn't exist on any of those pages. I can't be the first person in the universe who needs this :-) ... Pointers to something I've missed in the Django docs or to a package that has eluded my search for it GREATLY appreciated. -
django postgresql opposite list search
Good afternoon I am using django with postgresql for an application. I have a model that contains a field which is a charfield and stores none/one/many references to external databases. If none it is empty If one it is the reference itself ("CCCC") If many it is each reference separated by semicolons ("AAAA;BBBB;CCCC;DDDD;EEEE;"). This can be seen below: An example of the python file of the model can be found below: Models.py file: class Data(models.Model): ... external_database_id = models.CharField(max_length=255) ... The reason for using a charfield was that, at the beggining, all this information was only to display it to the user, and no other option was applied on it. Now I need to implement/apply a lookup filter with django. I have an array containing some references: For example: [AAAA,BBBB,EEEE] I need to know if the any entry on the database matches to any of the entries of this list So far I have tried the "external_database_id__in" lookup filter "https://docs.djangoproject.com/en/1.11/ref/models/querysets/#in". It works in the case of the "none" and "one" but not in the "many", since there is no match for the whole string to the list... none: "" in [AAAA,BBBB,EEEE] --> FALSE (as expected) one: "CCCC" in [AAAA,BBBB,EEEE] --> … -
Django Command Override Required Arguments
I have a django command below where I can pass in a car model as an argument and it works. However, I want to add functionality to list models without needing to first pass in a model. For instance, calling python manage.py car_models --list_models would not work, as it requires something to satisfy the model arg, whereas something like python manage.py car_models Cruze --list_models would work, even though from a UX standpoint, knowing a model of car before you list it is impossible. tl;dr, I want to have the model argument required unless the --list_models tag is in use. Anybody know a solution to this? class Command(BaseCommand): help = 'Car models' def add_arguments(self, parser): parser.add_argument('model', help='model of car') # I want to make it so that if a user says `python manage.py car_models --list_models`, # the user doesn't get yelled at for not passing in a model arg parser.add_argument( '--list_models', '-lm', dest='list_models', action='store_true', help='List available car models', ) def handle(self, *args, **options): if options['list_models']: print(['Cruze', 'Tahoe', 'Impala']) return print("Your car is {}".format(options['model'])) -
Django Model Method or Calculation as Field in Database
Using Django ~=1.11 and Python 3.6 I need to store 'calculated' variables as fields in the Django model database. Here's a model: from django.db import models from datetime import date class Person(model.Model) "Last Name" last_name = models.CharField(max_length=25) "Birthday" birth_date = models.DateField() "City of birth" city_of_birth = models.CharField(max_length=25) I am creating a Unique ID using these fields. Specifically, I'm conjoining parts of each field into one string variable (details below). I was able to get this to work as a Property but I don't know how to store a calculated field in the database. "Unique ID" def get_id(self): a = self.last_name[:2].upper() #First 2 letters of last name b = self.birth_date.strftime('%d') #Day of the month as string c = self.city_of_birth[:2].upper() #First 2 letters of city return a + b + c unique_id = property(get_id) I want to do a similar thing with Age. Here's what I have as a calculation: "Age calculated from Birth Date" def get_age(self): return int((datetime.date.now() - self.birth_date.days) / 365.25) age = property(get_age) So I'd like to store the UniqueID and Age variables in the database, as fields in the Person model. What is the best practice when doing these? Do I need to initialize the fields first, then … -
'NoneType' object has no attribute 'name'
I am trying to build a recommendation system for wine.In reviews/view.py page I got this error 'NoneType' object has no attribute 'name' in the code below During handling of the above exception ('NoneType' object has no attribute 'name'), another exception occurred:* This was the line where I got these error User.objects.get(username=request.user.username).cluster_set.first().name Here is the complete code `from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.models import User from .models import Review, Wine, Cluster from .forms import ReviewForm from .suggestions import update_clusters import datetime from django.contrib.auth.decorators import login_required def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] context = {'latest_review_list': latest_review_list} return render(request, 'reviews/review_list.html', context) def review_detail(request, review_id): review = get_object_or_404(Review, pk=review_id) return render(request, 'reviews/review_detail.html', {'review': review}) def wine_list(request): wine_list = Wine.objects.order_by('-name') context = {'wine_list': wine_list} return render(request, 'reviews/wine_list.html', context) def wine_detail(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm() return render(request, 'reviews/wine_detail.html', {'wine': wine, 'form': form}) @login_required def add_review(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name = request.user.username review = Review() review.wine = wine review.user_name = user_name review.rating = rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() update_clusters() # Always return an HttpResponseRedirect after successfully dealing # with … -
How to use multiple HAYSTACK_CONNECTIONS and get results in all the indexes usning drf-haystack management commands?
I can use only one connection at a time during rebuild_index manage command. I need these two results simultaneously. It would be of great help If I could the solution to my problem. Thanks everyone. HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', 'EXCLUDED_INDEXES': ['services.search_indexes.ViewServiceIndex'], }, 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, -
Deploy Django/React application heroku
I have deployed django app on heroku, and everything is fine, no errors, etc. I'm using react on frontend, and I want to do npm install, gulp build so I can configurate my app properly. I can not run heroku run npm install, all I have is bash: npm: command not found, and I suppose that is ok because I need to trigger it somehow when he is building the app on the server, so I've modify my package.json like this: { "name": "Test app", "version": "1.0.0", "description": "Testing", "main": "bundle.js", "scripts": { "postinstall": "npm install" }, "dependencies": { "bootstrap": "^3.3.7", "babel-preset-es2015": "^6.1.2", "babel-preset-react": "^6.1.2", "babelify": "^7.2.0", "browser-sync": "^2.10.0", "browserify": "^12.0.1", "browserify-shim": "^3.8.11", "classnames": "^2.2.0", "core-util-is": "^1.0.1", "del": "^2.1.0", "flux": "^2.1.1", "gulp-autoprefixer": "^3.1.0", "gulp-bless": "^3.0.1", "gulp-connect": "^2.2.0", "gulp-html-replace": "^1.5.4", "gulp-if": "^2.0.0", "gulp-insert": "^0.5.0", "gulp-livereload": "^3.8.1", "gulp-load-plugins": "^1.1.0", "gulp-minify-css": "^1.2.1", "gulp-rename": "^1.2.2", "gulp-sass": "^2.1.0", "gulp-sourcemaps": "^1.6.0", "gulp-sync": "^0.1.4", "gulp-uglify": "^1.4.2", "history": "^1.13.0", "keymirror": "^0.1.1", "lodash": "^3.10.1", "react": "^0.14.2", "react-addons": "^0.9.0", "react-bootstrap": "^0.27.3", "react-dom": "^0.14.2", "react-mixin": "^3.0.3", "react-router": "^1.0.0", "react-style": "^0.5.5", "reqwest": "^2.0.5", "rimraf": "^2.4.3", "run-sequence": "^1.1.4", "vinyl-buffer": "^1.0.0", "vinyl-source-stream": "^1.1.0", "watchify": "^3.6.0", "when": "^3.7.4" }, "devDependencies": { "babel-preset-es2015": "^6.1.2", "babel-preset-react": "^6.1.2", "babelify": "^7.2.0", "browser-sync": "^2.10.0", "browserify": "^12.0.1", "browserify-shim": "^3.8.11", "classnames": "^2.2.0", … -
How to get each value from query set using Django and Python
I need to get all different value from queryset using Django and python. Here I am doing something but getting the blank data while printing. I am explaining my code below. def loginsave(request): if request.method == 'POST': uname = request.POST.get('uname') password = request.POST.get('pass') per = User.objects.all().filter(Q(password__icontains=password) & Q(uname__icontains=uname)).count() if per > 0: return render(request, 'plant/home.html', {'count': per}) else: user_count = User.objects.all().filter(Q(password__icontains=password) | Q(uname__icontains=uname)).count(); if user_count > 0: user = User.objects.all().filter(Q(password__icontains=password) | Q(uname__icontains=uname)) print (user) else: return render(request, 'plant/login.html', {'message' : "You are not a registered user ."}) Here my requirement is when user will get data by matching password or username it need to access all column value. Here I am getting the print value like <QuerySet [<User: User object>, <User: User object>]> this. Please help me. -
Trouble with signals when inheriting from an abstract class
My app has different sort of users (parents, teachers, students) and I created a Profile abstract class to inherit from. I'm trying to use a receiver function so that whenever a user is created, a profile is also created. In the admin page, when I try to create a Teacher Object, I need to create a User object first, but when I create a user object, I run into an error "AttributeError: type object 'Profile' has no attribute 'objects'". I suspect this is because Profile is an abstract class, so if a User is created, it causes an error to create a Profile? If so, what's the better way to do this? I'm just trying to manually create a Teacher object in the admin page. #models.py class Profile(TimeStampedModel): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=1, choices=SEX) user_type = models.CharField(max_length=100, choices=USER_TYPE) class Meta: abstract = True class Teacher(Profile): user_type = 'teacher' @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) -
Derived variables in Django Models
I am building a Django app that has a central Projects model: class Project(models.Model): fundamental_attrib1=models.IntegerField() fundamental_attrib2=models.DecimalField(max_digits=10, decimal_places=2) derived_attrib1=models.DecimalField(null=True, max_digits=10, decimal_places=2) derived_attrib1_start=models.DateField(null=True) derived_attrib1_end=models.DateField(null=True) derived_attrib2=models.DecimalField(null=True, max_digits=10, decimal_places=2) derived_attrib2_start=models.DateField(null=True) derived_attrib2_end=models.DateField(null=True) derived_attrib3=models.IntegerField(null=True) derived_attrib3_start=models.DateField(null=True) derived_attrib3_end=models.DateField(null=True) The goal is to allow users to instantiate new projects where they can only see (and only need to) the 'fundamental' variables in the form to create/update a Project. Once they have submitted the form, I want to be calculate all the optional parameters before saving the project to the database. In addition, most of my derived variables come in groups of three as above (value, start date, end date). Is there a better way (that makes sense) to store them in the database? Naive string example: {'derived_attrib1':[1000,date(2017,1,1),date(2017,2,2)]} {'derived_attrib2':[2000,date(2017,2,1),date(2017,3,2)]} {'derived_attrib3':[ 500,date(2017,3,1),date(2017,4,2)]} My eventual 'end goal' is, for each group: create numpy arrays (or bring into one DataFrame?) to interpolate days between the start and end dates linearly distribute the value across the days plot each group as a timeseries (probably with D3.js/Bokeh or similar) -
Using singletons in Python (Django)
I was suggested to define a singleton in Python in the following way: class Controller: pass # ... controller = Controller() However, this way, controller cannot be replaced with a derived class. What are other sensible ways to define singletons in Python Django? Maybe, when defining a reusable app, I should not define the singleton instance right in the app, but define it in the program which uses it? What are advantages and disadvantages of doing this? -
ValueError: "needs to have a value for field "id" before this many-to-many relationship can be used"
I have created an extended user model that I use on my sign-up page. The two custom models are "Cristin" and a many-to-many field named "Rolle" (the person's role in the organization). After I added the many-to-many field, I get the following error message: ValueError at /accounts/signup/ –"Userextended: username_that_I_registered_with" needs to have a value for field "id" before this many-to-many relationship can be used. I have googled for three hours now, and it seems that the solution is to use commit=False on the User ID before saving the model. However, I'm new to Django and Python and have trouble pinpointing where I should write the code and my attempts has so far been unsuccessful. If you can help me solving this problem, please provide the solution through code as well. My models.py file: class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Personrolle(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') persrolle = models.CharField(max_length = 30, verbose_name="Role") def __str__(self): return self.persrolle class Userextended(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') user = models.OneToOneField(User, on_delete=models.CASCADE) cristin = models.IntegerField(blank=True, null=True) rolle = models.ManyToManyField(Personrolle) def __str__(self): return self.user.username ... My forms.py file: ... from django import forms from django.contrib.auth.models import User from accounts.models import Userextended from accounts.models import …