Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - when best to calculate statistics on large amounts of data
I'm working on a Django application that consists of a scraper that scrapes thousands of store items (price, description, seller info) per day and a django-template frontend that allows the user to access the data and view various statistics. For example: the user is able to click on 'Item A', and gets a detail view that lists various statistics about 'Item A' (Like linegraphs about price over time, a price distribution, etc) The user is also able to click on reports of the individual 'scrapes' and get details about the number of items scraped, average price. Etc. All of these statistics are currently calculated in the view itself. This all works well when working locally, on a small development database with +/100 items. However, when in production this database will eventually consist of 1.000.000+ lines. Which leads me to wonder if calculating the statistics in the view wont lead to massive lag in the future. (Especially as I plan to extend the statistics with more complicated regression-analysis, and perhaps some nearest neighbour ML classification) The advantage of the view based approach is that the graphs are always up to date. I could offcourse also schedule a CRONJOB to make the … -
Celery / Heroku - delay() does nothing when ran in the background using Heroku run python
I am attempting to add background workers using Celery to automatically run scripts each day to update the information my website provides. I've integrated Celery with Django and Heroku, and I can import the module and use the function, but it freezes when I use the add.delay()command until I press Ctrl+C to cancel the command. I am using celery 4.1 Here is how I run the commands: heroku ps:scale worker=1 heroku run python >>>from Buylist.tasks import * >>>add(2,3) >>>5 >>>add.delay(2,3) #-- Freezes until I press Control+C If you could help me figure out where my settings are misconfigured, that would be great. I'm testing atm. the tasks.py is the sample code to get a working example, and then I'll move on to figuring out CELERY_BEAT settings project/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) # Load task modules from all registered Django app … -
pytest - make multiple tests operate on the same db
I am trying to avoid multiple creation of the same django object for multiple tests using @pytest.fixture(scope='module') syntax. from bots.models import Bot @pytest.fixture(scope='module') def forwarding_bot(): (bot, created) = Bot.objects.get_or_create( name="test_bot", user=get_user_model().objects.create_user(username='test_user'), forward_http_requests_to='https://httpbin.org/post' ) return bot def test_get_bot_by_pk(forwarding_bot): print(f'test_get_bot_by_pk: bot count: {Bot.objects.count()}') def test_get_bot_by_uuid(forwarding_bot): print(f'test_get_bot_by_uuid: bot count: {Bot.objects.count()}') When I run pytest I get this output: test_get_bot_by_pk: bot count: 1 test_get_bot_by_uuid: bot count: 0 I understand the reason for this. The fixture function indeed gets fired once per module, but since its code creates a db object - only the first test finds it in DB. The question is - how do I make several tests operate on the same db and the same fixture? I am new to pytest so this is a challenge to me. -
How to use "django-autocomplete-light" in inline form
I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well. This is a picture of my form. At first glance, it works as desired: Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures). This is my form template where I suspect the error, because the first field works correctly as desired. <div class="container"> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <!-- Medication Table --> <table class="table"> {{ medication.management_form }} {% for form in medication.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle "row1" "row2" %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Submit Form"/> <script type="text/javascript" src="{% static '/js/core/jquery.3.2.1.min.js' %}"></script> {{ form.media }} <!-- script for add, delete, update --> … -
How to apply CSS to the email in django
How to apply CSS to HTML email in Django -
getting NoReverseMatch for a correct url and correct arguments
I have looked thoroughly my code and yet I am still stuck at this point where I get the NoReverseMatch error for correct url and correct parameters. Here is my URLConfig url(r'profile/$', views.agent_profile, name='agent_profile'), url(r'profile/(?P<pk>[A-Za-z0-9]+)/$', views.change_profile, name='change_profile'), url(r'assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$', views.assign_profile, name='assign_profile'), the view handling that request is : def assign_profile(request, pk, profile): agent = Agent.objects.get(pk=pk) # profile = Profile.objects.filter(designation=profile) # profile.agents = agent return render(request, 'portfolio/change_profile.html', {'agent': agent}) and the url in the template is called as follow: <li><a href={% url 'portfolio:assign_profile' pk=agent.code_agent profile="super_agent" %}>Super Agent</a></li> and the error is as follow: NoReverseMatch at /portfolio/profile/1/ Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$'] Request Method: GET Request URL: http://localhost:8000/portfolio/profile/1/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$'] Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\admin\\PycharmProjects\\trial', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Wed, 3 Jan 2018 14:35:49 +0000 -
django.core.exceptions.ImproperlyConfigured Should I replace to use reverse_lazy() instead of reverse()?
I got an error,django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. When I searched this error messages,django reverse causes circular import was found and read it.Should I replace to use reverse_lazy() instead of reverse()?Or should I fix another point of the codes?Traceback says Unhandled exception in thread started by .wrapper at 0x102e9e378> Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/urls/resolvers.py", line 312, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/urls/resolvers.py", line 319, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The … -
If statement gives wrong output in query set
I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database. However, after I define selectedaccesslevel as: selectedaccesslevel = request.POST.get('accesslevelid') with a print statement it's displayed correctly as 3,4,5,6, or 7 depending on the option the user selects in the form. My issue seems to be with my nested if statement that always hits the else: when i use just selectedaccesslevel == '#'. I'm looking for my output for datareducecode to be 'S00009' and not . How can I accomplish this? Below is my view... def submitted(request): owner = User.objects.get (formattedusername=request.user.formattedusername) checkedlist = request.POST.getlist('report_id') print (f"checkedlist on submitted:{checkedlist}") access_request_date = timezone.now() coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername) datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid) # facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) # divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) # print(facilitycfo) # print(divisioncfo) selectedaccesslevel = request.POST.get('accesslevelid') print (f"accesslevel:{selectedaccesslevel}") selectedphi = request.POST.get('phi') print (f"phi:{selectedphi}") print (owner.coid.coid) if request.method == 'POST' and selectedaccesslevel == '3': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True) print (datareducecode) if selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', … -
How to use django-tagit-label outside admin panel?
I am currently working on a django project where one form is used outside the admin panel that requires tagging. I found django-tagit-labels Tagit Github but it only works for admin panel forms, any idea on how to use it outside the admin panel in custom pages ? -
How to read and open gal file from a selected path in my pc?
I used python code to analysis my data. But when I wanted to read the gal file I got error. w = pd.read_gal("C:\Users\Yousif\Downloads\PythonSpatial\statess7.gal") AttributeError Traceback (most recent call last) in () 1 ----> 2 w = pd.read("C:\Users\Yousif\Downloads\PythonSpatial\statess7.gal") 3 AttributeError: module 'pandas' has no attribute 'read' Also once I used this function w = pysal.open(pysal.examples.get_path("statess7.gal")).read() I got this error KeyError Traceback (most recent call last) in () 1 ----> 2 w = pysal.open(pysal.examples.get_path("statess7.gal")).read() ~\Anaconda3\lib\site-packages\pysal\examples__init__.py in get_path(example_name) 33 return os.path.join(base, 'examples', example_name) 34 else: ---> 35 raise KeyError(example_name + ' not found in PySAL built-in examples.') 36 37 KeyError: 'statess7.gal not found in PySAL built-in examples.' Ihope to help me how can I read and open gal file from path in my laptop. -
add limit for list in for loop django template
I want to print only 10 elements from list in Django template here is my code <ul> <h3>Positive Tweets :</h3> {% for tweet in positiveTweet %} <li>{{ tweet.0 }}</li> {% endfor %} </ul> How can I print first 10 elements if positiveTweet list having length of 100 something. -
Celery daemon doesnt start with sysmted on CentOS 7
Some time ago I encountered problem with starting celery on my CentOS 7 server. I am not systemd expert but tried to follow celery docs and did my best on it. I found one related problem on stackoverflow but it doesnt appeal to my case. I used Celery Daemonization docs to create my systemd unit, which is as follows (root user is there only to launch script, for production I am going to use diffrent one): [Unit] Description=Celery Service After=network.target [Service] Type=forking User=root Group=root EnvironmentFile=/etc/celery/celery.conf WorkingDirectory=/path/to/my/django/project ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target And EnviromentFile as follows: #C_FAKEFORK=1 # Name of nodes to start # here we have a single node CELERYD_NODES="w1" # or we could have three nodes: DJANGO_SETTINGS_MODULE=fk.settings # Absolute or relative path to the 'celery' command: CELERY_BIN="/var/bin/path/to/celery/in/venv" # App instance to use # comment out this line if you don't use an app CELERY_APP="myapp" # or fully qualified: #CELERY_APP="proj.tasks:app" # How to call manage.py CELERYD_MULTI="multi" CELERYD_PID_FILE="/var/log/celery_%n.pid" CELERYD_LOG_FILE="/var/log/%n%I.log" CELERYD_LOG_LEVEL="DEBUG" journalctl logs are as follows: Jan 03 14:24:06 … -
Inner classes - Inheritance and overriding their attributes
I'm trying to understand how Django uses python's metaclasses for it's database models (options) and came up with the following stripped down code snippet that should roughly mimic Django's logic. class DatabaseOptions(object): def __init__(self, opts): if opts: for key, val in opts.__dict__.items(): if not key.startswith('__') and not callable(val): setattr(self, key, val) class MetaModel(type): def __new__(cls, name, bases, classdict): result = super().__new__(cls, name, bases, dict(classdict)) opts = classdict.pop('DbMeta', None) if opts: setattr(result, '_db_meta', DatabaseOptions(opts)) return result class Model(object, metaclass=MetaModel): class DbMeta: database = 'default' migrate = True class User(Model): class DbMeta(Model.DbMeta): database = 'user' class GroupUser(User): class DbMeta(User.DbMeta): database = 'group_user' Using the above code, I would expect the following output: print(Model._db_meta.database) # default print(Model._db_meta.migrate) # True print(User._db_meta.database) # user print(User._db_meta.migrate) # True print(GroupUser._db_meta.database) # group_user print(GroupUser._db_meta.migrate) # True Instead I get the following exception >>> python3 test.py default True user Traceback (most recent call last): File "test.py", line 48, in <module> print(User._db_meta.migrate) # True AttributeError: 'DatabaseOptions' object has no attribute 'migrate' My question would be why User.DbMeta does not inherit the migrate attribute from Model.DbMeta? Is there any solution for this kind of problem? -
ImportError: No module django_nose
I following this pluralsight course and running into this error everytime I run the command: python manage.py test --settings=todobackend.settings.test I'm new to the Django framework; any idea why I'm getting that error, also see folder structure in pic below: python --version Python 2.7.13 Click on pic to see larger, clearer image. -
Use Django User permission layout for other manytomany field
When in a User object in the Django Admin, there is a really nice way to add permissions to the user. For a completely different model, I would like to use the same system. This model has a manytomany field to another model. Is there a way to copy the layout of the user admin, to this model's admin? -
Django website loads slow after using requests to check broken links
My website gives deatails about different servers. I have used requests to check which server ILO IP is not working through http and which is not. AFter using requests.. the page loads super slow! My server checks ILO Ips of many servers and if the server is broken it shows the IP as a text and if not it shows a link(THE IP) to the ILO. Do you know how to make the server load much faster? Thanks.. models.py - from django.db import models import requests class serverlist(models.Model): ServerName = models.CharField(max_length = 30,blank=True) Owner = models.CharField(max_length = 50,blank=True) Project = models.CharField(max_length = 30,blank=True) Description = models.CharField(max_length = 255,blank=True) IP = models.CharField(max_length = 30,blank=True) ILO = models.CharField(max_length = 30,blank=True) Rack = models.CharField(max_length = 30,blank=True) Status = models.CharField(max_length = 30,blank=True) def checkUrlAvailable(self): ip_check = 'https://' + self.ILO resp = requests.head(ip_check,allow_redirects=False) if resp.status_code == 303: return True else: return False index.html - {% if server.checkUrlAvailable is True %} <a href="//{{ server.ILO }}"> {{ server.ILO }} </a> {% else %} {{ server.ILO }} {% endif %} -
Javascript code for Bootstrap Sidebar menu not working
I have a Sidebar / Menu that I am working with. It has been created with Bootstrap, DJango, and Javascript. Basically, I am trying to write Javascript so that when on clicks on a menu-item, the background changes color (dark blue), the icon change color (light green / turquoise) and it gets a type of "wedge" Below is an example of a menu-item that has been chosen (Dashboard) along with menu-items that have not been chosen (Security and Messages). The "wedge" has a red arrow pointing to it. Here is the HTML code that is being used: [... snip ...] <div class="page-container"> <div class="page-sidebar-wrapper"> <div class="page-sidebar navbar-collapse collapse"> <ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <li class="nav-item start active open"> <a href="{% url 'mainadmin:dashboard' %}" class="nav-link nav-toggle"> <i class="fa fa-tachometer"></i> <span class="title">Dashboard</span> <span class="selected"></span> <span class="arrow open"></span> </a> </li> <li class="nav-item "> <a href="{% url 'mainadmin:security' %}" class="nav-link nav-toggle"> <i class="fa fa-users"></i> <span class="title">Security</span> <span class="arrow"></span> </a> </li> <li class="nav-item "> <a href="{% url 'mainadmin:in_progress' %}" class="nav-link nav-toggle"> <i class="fa fa-comment"></i> <span class="title">Messages</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="{% url 'mainadmin:in_progress' %}" class="nav-link "> <span class="title">List All Messages</span> </a> </li> <li class="nav-item "> <a href="{% … -
Django - DATE_FORMAT not work properly, i can't force Django to use a Date format
(First of all sorry for my bad English) I'm having a problem with the Date Formats, I'm from Argentina and here we use the Date Format dd/mm/yyyy. Well when I use a computer configured in spanish language the I see the dates and the date inputs perfect!for example in a detail view I see this in a date dd/mm/yyy but in any computer like my own one I see this mm/dd/yyyy And this generate a problem with my forms, in an especific case on my app when I go to save in the database a date input 03/01/2017 (Jan. 3. 2017) saves March 1 2017 ...... This is the configuration on the settings file USE_L10N = False DATE_FORMAT = 'd/m/Y' DATE_INPUT_FORMATS = ('d/m/Y') USE_TZ = True I use only DATE_FORMAT too, TZ False... I really don't know if is any way to force Django to use the format dd/mm/yyyy for all the cases. -
Django AllAuth - Google - choose username
We are using Django-allauth to allow users to signup and login using Google. The problem is that it automatically chooses first name from Google account as a username. Is it possible to make users to fill the username manually? I didn't find such settings in Allauth-google docs. These are ACCOUNT_ settings from settings.py ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_SUBJECT_PREFIX = EMAIL_SUBJECT_PREFIX ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 1 ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_PRESERVE_USERNAME_CASING = False ACCOUNT_USERNAME_MIN_LENGTH = 4 ACCOUNT_USERNAME_REQUIRED = True There is no such setting starting SOCIALACCOUNT_ in Docs. -
Django dynamic responsive forms
I have been learning django and wanted to create dynamic forms.So far, I have only created a dropdown menu. I wanted to create additional form fields for user input once a choice is made. I'm using ModelForm for the creation of dropdown menu as menu items will be decided during the runtime. My dropdown menu My views.py file from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import ChoiceForm def hello(request): if request.method == 'POST': print 'in post' form = ChoiceForm(request.POST) if form.is_valid(): return HttpResponse(str(form.cleaned_data)) else: return HttpResponse('Invalid data') else: form = ChoiceForm() return render(request, 'choices.html', {'form': form}) My Models.py file from django.db import models from google.cloud import storage # Create your models here. class QueryInfo(models.Model): client = storage.Client() bucket_list = client.list_buckets() #Choice fields for user to select #choices must be in a iterable of length 2 BUCKET_CHOICES = ( (str(bucket_name.name), str(bucket_name.name)) for bucket_name in bucket_list ) selected_bucket = models.CharField(max_length=256,choices=BUCKET_CHOICES) My form file: from django import forms from gui.models import QueryInfo class ChoiceForm(forms.ModelForm): class Meta: model = QueryInfo fields = ['selected_bucket'] -
raw SQL in django views show error
For some special reasons we had to perform raw query in view.py file. (There is some page that user types an SQL query and sends it so our system and we should perform it and show the result of tat query) def query(request): result = None if request.method == "POST": form = forms.QueryForm(request.POST) if form.is_valid(): query_text = form.cleaned_data['query'] with connection.cursor() as cursor: try: cursor.execute(query_text) result = cursor.fetchall() except: result = cursor.statusmessage else: form = forms.QueryForm() return render(request, "portal/query.html", { 'form': form, 'result': result }) if we run something like SELECT * FROM table1, the try part would successfully run and if some queries that do not return some rows like UPDATE, the except part works. My question is that if we perform some meaningless queries like sakufhskghks, we want to see the error from DB, or any type of error from DB. Is that possible? tnx -
JSON formatting to a list in python
In python I get "n" number of json objects on request to an api. I need to convert this to a list and display it in django. What is the easiest way to do it. I did use json.dumps(data) it just dumps the entire data. -
AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed
I'm using a custom user model, extended with AbstractUser. Here's my models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.forms import UserCreationForm from django import forms # Create your models here. class User(AbstractUser): pass class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) enter code here So when I try to run the development server, or migrate the database, it returns this error: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/shivbhatia/Desktop/WishList/accounts/models.py", line 6, in <module> from django.contrib.auth.forms import UserCreationForm File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 22, in <module> UserModel = get_user_model() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 198, in get_user_model "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that … -
Connect 3 models in Django to access other model data
I have 3 models and in the 3rd model called Bookauth contains Foreign key for other two models Books, Authors. I want to get all the fields from 'Books' of a particular author(considering he wrote more then one book). I used manager in models but failed. Models class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.TextField( blank=True, null=True) def __str__(self): return self.aname class Books(models.Model): bid = models.BigIntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.TextField(blank=True, null=True) def __str__(self): return self.bname class Bookauth(models.Model): bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True) Views Don't think this is relevent def getObject(request): all_books = Books.objects.all() html = serializers.serialize('json', all_books) return HttpResponse(html) #data = serializers.serialize("json", Books.objects.all()) #return HttpResponse(data, mimetype='application/json') def getAuth(request): all_auth = Authors.objects.all() htm = serializers.serialize('json', all_auth) return HttpResponse(htm) def bookAuth(request): all_keys = Bookauth.objects.all() key_serial = serializers.serialize('json', all_keys) return HttpResponse(key_serial) def book_search(request): b = request.GET.get('book', '') book = Books.objects.filter(pk = b) return HttpResponse(book) def author_search(request): x = request.GET.get('author', '') auth = Authors.objects.filter(pk= x) return HttpResponse(auth) Any suggestions on what I can do? -
How to pass Django server variable into React jsx?
I have a Django view that passes a model queryset and a string variable (order) class RestaurantListView(generic.ListView): model = Restaurant context_object_name = 'restaurants' template_name = 'routeyourfood/restodetails.html' paginate_by = 4 @method_decorator(require_GET) def dispatch(self, request, *args, **kwargs): return super(RestaurantListView, self).dispatch(request, *args, **kwargs) def get_queryset(self, **kwargs): self.pids = self.request.session['place_ids'] self.order = self.kwargs['order'] self.ordering_dict = { 'rating-asc': 'rating', 'rating-desc': '-rating', 'name-asc': 'name', 'name-desc': '-name', 'distance-asc': 'distance_from_route', 'distance-desc': '-distance_from_route' } if self.order == 'default': return Restaurant.objects.filter(place_id__in=self.pids) return Restaurant.objects.filter(place_id__in=self.pids).order_by(self.ordering_dict[self.order]) def get_context_data(self, **kwargs): context = super(RestaurantListView, self).get_context_data(**kwargs) context['order'] = self.kwargs['order'] return context I am trying to implement ReactJS into my front end. Currently, my template, restodetails.html has only a few CSS tags and no JS tag. I construct the entire page using just the template variables I have passed. But I can't see how I can integrate React into this. One way I got was to put React into a <script> tag in the head section, like here. But I'm keeping my React code in separate JSX files in the Django static folder, which I'm bundling using Webpack. I also don't like the idea of putting JavaScript into the template. Is there a way to pass those context variables into the JSX files?