Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override objects.get() method?
How to override Django's objects.get() method like this: def get(?): try: return super().get(?) except ObjectDoesNotExist: return None I will accept custom get method too (e.g. get_or_none()). -
view that adds object to m2m
I want to create a view that says "Are you sure you would like to [add object to m2m]" and when the user clicks OK, the view adds the object to the m2m and the user is redirected to the detailview from whence they originally came. A simple myobject.mym2m.add(user). the pk of myobject will ideally be in the url. I was originally going to make this an ajax api call and just redirect with javascript because I didn't know any other way, but that seems hacky, so I thought I'd ask here. How can I do this? Thanks in advance. -
How to convert SQL states below to Django ORM
Having difficult time to convert the SQL statements below to Django ORM. Any help is much appreciated. SELECT a.state, a.city, a.postcode, b.rate_authority, b.rate, b.rate_descr FROM fileload_taxratemodel AS a INNER JOIN fileload_taxrateresponsemodel AS b ON b.jurs_id_id = a.id ORDER BY state ASC Django Models: Trying to pull fields from both model based on the foreign key. class TaxRateModel(models.Model): company_code = models.CharField(max_length = 10) document_date = models.DateTimeField() country = models.CharField(max_length = 30, default = "US") province = models.CharField(max_length = 100, null= True,blank= True) state = models.CharField(max_length = 100) county = models.CharField(max_length = 100,blank=True, null=True) city = models.CharField(max_length = 100,blank=True, null=True) district = models.CharField(max_length = 100, blank=True, null=True) postcode = models.CharField(max_length = 5, blank=True, null=True) rate_code = models.CharField(max_length = 30,default = "ST") Django 2nd Model : class TaxRateResponseModel(models.Model): jurs_id = models.ForeignKey(TaxRateModel,on_delete=models.CASCADE,related_name='rates') rate_authority = models.CharField(max_length = 100, blank=True, null=True, default='') rate_descr = models.CharField(max_length = 100, blank=True, null=True, default ='') rate = models.DecimalField(max_digits= 10, decimal_places=5) -
Can I use Telethon with Django and how do I do it?
Can I use Telethon with Django and how do I do it? Some info will be really appreciated. How to pass the scrap results from Telethon on the template i know, but how do i write the script in views.py to can be able to get a channel info by example ? I know to connect it to API. Thanks ! -
Django-Jet "Page Not Found"
I am attempting to install the Django Jet dashboard, but I'm unable to get anywhere with it. I've followed the installation instructions, but no matter what I'm getting "Page Not Found" despite the URLs for Jet being listed. There are a handful of Issues opened on this, but none offer a solution outside that it was resolved in newer versions, and I am using the recommended commit (latest). Issues: https://github.com/geex-arts/django-jet/issues/289 https://github.com/geex-arts/django-jet/issues/62 Urls.py: from django.contrib import admin from django.urls import path, include, re_path from depot import views urlpatterns = [ path('', include('depot.urls')), path('', include('stores.urls')), path('admin/', admin.site.urls), re_path(r'^jet/', include(('jet.urls', 'jet'))), re_path(r'^jet/dashboard/', include(('jet.dashboard.urls', 'jet-dashboard'))), ] I have no custom overriding admin templates. I have tried just visiting /admin/, but my admin looks like the default Django Admin (someone mentioned its supposed to take over the original admin templates). Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'depot', 'stores', 'jet', 'jet.dashboard', ] I have also verified I have django.template.context_processors.request under Templates in my settings.py as well. -
Django API throwing a 403 error when called from Azure Functions
I have an instance of Azure Functions which is calling a particular endpoint of a Django API. The Django API doesn't need any authentication and I have used the @csrf_exempt annotator in the views.py file. It's a POST request which takes request parameters from the URL. When I call the end-point from Postman, it works fine but when the Azure Functions is making a HTTP Post call, the API throws a 403 Forbidden error. There is no explicit 403 error that is coded in the Django API. Logs on AppInsights suggest that log.py line 228 is throwing the error. From what I understand, the relevant log.py file is present in django/utils/log.py I am not able to figure out why there is a 403 error from the API. Any suggestions? -
Using Django, how can I avoid the duplicity of code when showing the details of a row inside a bootstrap modal?
I have a table where I show some item fields. When the user clics a button it opens a modal with all the item information. I'm using a "for loop" to get the rows but I noticed that it also creates a modal for each row. This is the line that includes the modal template: {% include 'item_detail.html' with pin=item.pin %} If I place the modal out of the "for loop" it loses context and doesn't show the item information. This is my for loop: <tbody class="items-table-body"> {% for item in items %} <tr scope="row"> <td>{{item.client_name}}</td> <td>{{item.title}}</td> <td>{{item.amount}}</td> <td>{{item.creation_date}}</td> <td>{{item.get_status_display}}</td> <td><button type="button" class="btn btn-sm btn-primary" name="button" data-toggle="modal" data-target="#itemDetailModal"> <span class="fa fa-eye"></span> </button> {% include 'item_detail.html' with pin=item.pin %} </td> </tr> {% empty %} <p>No items created</p> {% endfor %} This is a short version of my modal: <div class="modal fade" id="itemDetailModal" tabindex="-1" role="dialog" aria-labelledby="itemDetailModalTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> ... </div> <div class="modal-body"> ... </div> </div> </div> </div> -
(admin.E012) There are duplicate field(s) in 'fieldsets[0][1]' when using ManyToManyField
I upgraded from Django 1.10 to 1.11 and now two of my models which previously worked are causing errors. They are the only two models that have a ManyToManyField that includes a related_name attribute. I have another ManyToManyField without a related_name and it works fine. The error that gets thrown is misleading: <class 'hadotcom.admin.CaseStudyAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[0][1]' I've found other SO posts that reference that error and confirmed that none of them match my issue. If I comment out the entire line it passes the check. I tried adding a through attribute and that didn't help. Sample code (using Mezzanine): class CaseStudyPage(Page): industries = models.ManyToManyField("IndustryPage", blank=True, related_name="industry_set", through="CaseStudyIndustries") class CaseStudyAdmin(HaPageAdmin): inlines = (Foo, Bar,) Happy to fill in any blanks, and thanks in advance. -
How do I install the yaml package for my PyCharm Python project?
I'm using PyCharm 2018.2.4 with Python 3.7. I want to run some seed data so in the Python management console, I tried running my yaml file, which ended in this error manage.py@mainpage_project > loaddata seed_data bash -cl "/Users/davea/Documents/workspace/mainpage_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py loaddata seed_data /Users/davea/Documents/workspace/mainpage_project" Tracking file by folder pattern: migrations /Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/davea/Documents/workspace/mainpage_project/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 165, in load_label ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore, File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 140, in deserialize return d(stream_or_string, … -
Django Signal pre_save methode
i have tree table ( User , Company , Role ) class Company_Model ( models.Model ): company_Owner = models.ForeignKey ( User,on_delete = models.CASCADE) company_name = models.CharField ( max_length = 100,) class Roles_Model ( models.Model ): roles_user = models.ForeignKey ( User,on_delete = models.CASCADE ) roles_company = models.ForeignKey ( Company_Model,on_delete = models.CASCADE,null = True ) ============================================================================= so what i need is : whene the user is created i need to catch the id of user and create in Company table [ company_owner = user_id ] and in role table [ roles_user = user_id , roles_company = user_id ] -
django-sorcery isn't autogenerating migrations
I'm playing around with the django-sorcery library, and I've been trying to generate some migrations: django-admin sorcery revision -m "Second revision" --autogenerate -v 1 my_app When I first ran the command, I saw an error message: FileNotFoundError: [Errno 2] No such file or directory: [... snip ...]python3.7/site-packages/django_sorcery/db/alembic/script.py.mako Not sure why the template is missing from the pip package, I added it back in by hand. Now, the command just generates empty migration files, even though I specify the --autogenerate flag. Should I be throwing an env.py file somewhere? is this command actually supposed to work yet? Help appreciated. -
Django TestCase on form validation fails even tough input is valid
As in the title described I've got a form which validates correctly when I am using the FormView. However as I started writting tests today the same input fails in the TestCase and I get the following error: {'programming_language': ['Select a valid choice. That choice is not one of the available choices.']} These are the models, forms, views and the test I am using # models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=40, unique=True) class ProgrammingLanguage(models.Model): name = models.CharField(max_length=40, unique=True) class Snippet(models.Model): title = models.CharField(max_length=40) programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) explanation = models.TextField() code = models.TextField() tags = models.ManyToManyField(Tag) # forms.py from django import forms from django.utils.translation import gettext_lazy as _ from .models import Snippet class SnippetForm(forms.ModelForm): class Meta: model = Snippet exclude = ["creation_date"] # views.py from django.urls import reverse_lazy from django.views import generic from .models import Snippet from .forms import SnippetForm class SnippetFormView(generic.FormView): template_name = "snippets/snippet_form.html" form_class = SnippetForm success_url = reverse_lazy("snippets") def form_valid(self, form): # for testing purposes print(form.cleaned_data) form.save() return super().form_valid(form) # test_forms.py from django.test import TestCase from snippets.forms import SnippetForm from snippets.models import ProgrammingLanguage, Tag, Snippet class SnippetFormTestCase(TestCase): @classmethod def setUpTestData(cls): ProgrammingLanguage.objects.create(name="Javascript") Tag.objects.create(name="website") def test_forms(self): form = SnippetForm({ 'title': 'Test snippet … -
Django - Users inconsistently registered to Admin
This is the default User model, nothing custom, no modifications to Auth in any way. Depot/Admin.py import depot.models as models from django.contrib import admin from django.db.models.base import ModelBase from django.contrib.auth.models import User admin.site.site_header = "DSG IT Database" for model_name in dir(models): model = getattr(models, model_name) if isinstance(model, ModelBase): if model in admin.site._registry: admin.site.unregister(model) else: admin.site.register(model) Stores/Admin.py import stores.models as models from django.contrib import admin from django.db.models.base import ModelBase from django.contrib.auth.models import User admin.site.site_header = "DSG IT Database" for model_name in dir(models): model = getattr(models, model_name) if isinstance(model, ModelBase): if model in admin.site._registry: admin.site.unregister(model) else: admin.site.register(model) I do understand these are sort of redundant, but that isn't the problem because this was an issue when this was a single application project as well. What is happening is that Users is just completely missing from the admin site. I can register it again with admin.site.register(User), but then later down the road (seemingly randomly) I'll get an error that User is already registered. Then I unregister the model, and it'll work for a while then at some point Users will just disappear again and the only way to make it work again is by registering it again. I can't find where I need … -
PhantomJS bot and Django: cannot send a cookie
I am trying to implement a stored XSS CTF challenge. I have the instructions from this blog How to add an XSSable bot to your CTF However, I cannot send any cookie data with the phantom.addcookie(). I use the Django framework to develop the web application. This is my bot.js which uses the PhantomJS -based on the instructions from the blog I have already referred to: var page = require('webpage').create(); var host = "127.0.0.1:8000"; var url = "http://"+host+"/posts/; var timeout = 2000; phantom.addCookie({ 'name': 'Flag', 'value': 'CTF{44dc13922a2f0f7a59c5058703fae0b9}', 'domain': host, 'path': '/', 'httponly': false }); page.onNavigationRequested = function(url, type, willNavigate, main) { console.log("[URL] URL="+url); }; page.settings.resourceTimeout = timeout; page.onResourceTimeout = function(e) { setTimeout(function(){ console.log("[INFO] Timeout") phantom.exit(); }, 1); }; page.open(url, function(status) { console.log("[INFO] rendered page"); setTimeout(function(){ phantom.exit(); }, 1); }); My templates in connection visited by the bot are the following: post_list.html: {% extends "posts/post_base.html" %} {% load humanize %} {% block pre_post_content %} <div class="col-md-4"> {% if request.user.is_authenticated %} <div class="card card-with-shadow"> <div class="content"> <h5 class="title">Your Groups</h5> <ul class="list-unstyled"> {% for member_group in get_user_groups %} <li class="group li-with-bullet"> <a href="{% url 'groups:single' slug=member_group.group.slug %}"> {{ member_group.group.name }}</a> </li> {% endfor %} </ul> </div> </div> {% endif %} <div class="card card-with-shadow"> … -
How does the python module system work in django/salt
I am trying to understand certain aspects of the Python module system, but there are certain aspects I just can't seem to grasp. I'll use saltstack as an example. When you look at the file https://github.com/saltstack/salt/blob/develop/salt/minion.py#L30 they'll have this: from salt.utils.zeromq import zmq, ZMQDefaultLoop, install_zmq, ZMQ_VERSION_INFO This absolute import is part of the salt folder; I just don't understand why this works. When I try something like this locally, I'll get a ModuleNotFoundError. Can someone perhaps push me into the right path? Thank you very much! -
What are some Django best practice for creating objects to test on
The way I've been testing on code that requires a temporary Object to be created seems messy. I am hoping there is a cleaner and more intuitive way of doing it. On setup, I run a function setUpTestData that is in charge of creating temporary Objects that my tests may use later on. This has become a bit cluttered with the nested Objects I am having to create within it due to ForeignKey relationships. Here's an example of what I am working with: class Test_query_alarm(TestCase): @classmethod def setUpTestData(cls): Device.objects.create( site=Site.objects.create( group=Group.objects.create( name='TestGroup' ), name='TestSiteName', address='TestAddress', gps_coordinates='TestGpsCoordinates', contact=Contact.objects.create( first_name='TestFirstName', last_name='TestLastName', phone='TestPhoneNumber', email='test@gmail.com' ) ), ip_address='ip-here', snmp_port_number='port-here', http_port_number='port-here', location='Houston', snmp_version='SNMPV2', type='Modem', manufacturer='Commscope' ) As you can see, I am generating the Device object. But it's also requiring three other objects to be created alongside it. Is there any advice someone can give me here, whether it be database design, test design, or something else. -
Annotate Django queryset with a datetime
So, I have a queryset that I need to annotate with some additional fields, including integers, booleans, and datetimes. Something like this: def get_appointments_with_overrides(override_price, override_start_time, override_advance_booking_needed): return (Appointments.objects.annotate(override_price=Value(override_price, IntegerField())). annotate(override_start_time=Value(override_start_time, DateTimeField())). annotate(override_advance_booking_needed=Value(override_advance_booking_needed, BooleanField()))) Where override_price etc. are all properties (but not Django fields) in the Appointments model. When I try to use this (specifically, when I call first() or last() on the annotated queryset), I get the following error. AttributeError: 'DateTimeField' object has no attribute 'model' If I remove the datetime annotation, I don’t get any errors and the other two annotations work exactly as I expect them to. So what, if anything, am I doing wrong with this datetime annotation? -
Django, Nginx random 403/404 errors and redirect spam with HTTPS
I recently set up a Django web app using uWSGI, Nginx and Celery. All seemed to go well until I installed a Let's Encrypt certificate. My app SafeSpreadsheets will randomly throw a 403 error on the home page, and when I manually type in the login page location, will give a 404 error. On different systems (sometimes different browsers on the same system) the website might not load all the static files. Other times it will work 100% without an issue. I also tested whether the https redirect works on all my URLs (my Django and Nginx settings should force the redirect)but when I do, I can see the browser redirecting to iyfipun.com which is a known spam URL. The 403/404 errors don't show up in my logs (weirdly) and I don't get any admin/manager notifications from Django. My Nginx site configuration is as follows: server { server_name safespreadsheets.com www.safespreadsheets.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/xxx/yyy; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/yyy.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/safespreadsheets.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/safespreadsheets.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; … -
Django custom page based CMS
I am searching for django CMS that allows me to create something like custom pages build from predefined components. Every page should be builded from custom "inpage" components like: carousel with images gallery with images richtext field plain text field So as a developer I will build a template for every page of a website from this components and assing a CSS file for the given page. For example one page can look like: plain text field (heading) plain text field (some kind of page abstract) richtext field (part of the text) gallery with images (few specified images with some style) richtext field (another part of the text) Another page could be build in a different way. The key idea is, that every page will have predefined unique layout (template) that is not breakable by users in CMS. The CMS I would like to use, should allow the user to change content of the particular componets for particular page. So the CMS should create form to change the content of the particular components for a given page (heading, text, images in carousel). The changable content of the page (form fields) can be stored in database of files, it does not … -
Dynamically replace all urls to full absolute url in template
I have a template which I am going to send as an email. Thus I need to have absolute full urls (along with protocol and domain name) instead of relative ones. The content in the email is going to come dynamically from database (entered using ckeditor, so I CAN NOT do something like {{ protocol }}{{ domain_name }}{% static '' %}. This would work only for static files. However the media content uploaded via ckeditor will recide in media files and I have absolutely no control over it. Also i cant use javascript as it is an email template. Currently I have built a python function which scans the entire template after rendering and prepends the protocol and domain name to every src attribute in img tag and all href attributes. I would like to know if any better way exists -
I have a select list and I need to remake it on button group
I need to remake a select form to button group without loss of functionality. I surf all Net but I can't find solution. I can't do this without loss of functionality. <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <select name="language"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> From: To: -
Django model method vs custom manager
I am having trouble deciding between using a custom manager or a model method. I have a model User and have a query to find other users within a specific user's radius. So my two options are: class UserManager(models.Manager): def find_users_in_radius(self, user): return super().get_queryset().filter( location__distance_lt=( user.location, Distance(mi=user.search_radius))).exclude( pk=user.pk) class User(AbstractUser): ..... users_in_radius = UserManager() or a method on the User model: class User(AbstractUser): ..... def users_in_search_radius(self): return User.objects.filter( location__distance_lt=( self.location, Distance(mi=self.search_radius))).exclude( pk=self.pk) In my view I would then get query results using either the first method: User.users_in_radius.find_users_in_radius(request.user) or the second method: request.user.users_in_radius(). I like the second option better but I am wondering if this is bad practice. I haven't seen any examples of people calling User.objects in a model method. Is there another way to do this or is the custom manager a better approach? -
Django Redirect Issue: 'SessionStore' object is not callable
I am building an application in which a user enters an Elasticsearch query in a form, the query is passed along to a Python script that queries Elasticsearch and builds a document, then passes a downloadable doc back to the user. I have it working perfectly, when I have the downloadable doc appear on the same page where the user enters in the form. However, my client wants to redirect the page after successful submission of the form and spit out the doc there. That's where everything starts to fall apart. From what I can tell, it is redirecting but it's having trouble pulling the query defined in the previous view (from which it redirects). views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import QueryForm from .models import * from django.shortcuts import redirect # new @login_required def get_query(request): global query # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = QueryForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required query = form.cleaned_data["query"] request.session["query"] = query request.session.modified = … -
Django app with mysql support not working when deployed to GCP
I am trying to create sample Django app with mysql as database, its working fine in local when same app I try to deploy on GCP gives 500 error. I have created sql server in GCP and sued same settings its fail to find gunicorn but I have specified all this in requirments.txt 2019-01-19 07:06:13 default[20190119t122132] Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 104, in init_process super(ThreadWorker, self).init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app import(module) ModuleNotFoundError: No module named 'main' 2019-01-19 07:06:13 default[20190119t122132] [2019-01-19 07:06:13 +0000] [24] [INFO] Worker exiting (pid: 24) 2019-01-19 07:06:13 default[20190119t122132] [2019-01-19 07:06:13 +0000] [8] [INFO] Shutting down: Master 2019-01-19 07:06:13 default[20190119t122132] [2019-01-19 07:06:13 +0000] [8] [INFO] Reason: Worker failed to boot. 2019-01-19 07:06:14 default[20190119t122132] "GET /favicon.ico HTTP/1.1" 500 2019-01-19 07:32:08 default[20190119t125739] "GET / HTTP/1.1" 500 2019-01-19 07:32:09 default[20190119t125739] /bin/sh: 1: exec: gunicorn: not found 2019-01-19 07:32:20 default[20190119t125739] "GET /admin HTTP/1.1" 500 2019-01-19 07:32:21 default[20190119t125739] /bin/sh: 1: … -
Django Profile not saving other columns
I am trying to have a school system that have different profiles for students, lecturer and others, which i was able to achieve by creating a custom userModel, however, i was unable to save other information (avatar, semester etc) from the form to the student profile when creating them. its only the user_id that is getting saved in the studentProfile model. I am using django signal to post this data as well as generic createView to render to the screen. I have tried different means to solve this but i keep getting AttributeError my models.py class StudentProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) semester = models.ForeignKey(SemesterData, on_delete=models.SET_NULL, null=True) dept_name = models.ForeignKey(DepartmentData, on_delete=models.SET_NULL, null=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.admin: pass else: data = StudentProfile.semester HttpResponse(data) StudentProfile.objects.create(user=instance) Here is my form.py class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) user_type = forms.ChoiceField(choices=User.USER_TYPE_CHOICES,widget=forms.Select) # user_type = forms.Select(attrs={'class': 'form-control'}) class Meta: model = User fields = ('user_id', 'first_name','last_name','user_type',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") …