Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
class ShopAccountMixin(LoginRequiredMixin, object):
i am making a shops dashboard view .in that view i have used a mixin as mentioned below....my issue is i want to get products related to a specific account or user . i have products m2m in shop model and also have user f.k in Shop model. In get_shopproducts() function in ShopAccountMixin()..i am unable to filter products of a requested account..... please reply... shops/models.py class Shop(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) product = models.ManyToManyField(Product) ...... def __unicode__(self): return str(self.user.username) products/models.py class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, ... def __unicode__(self): #def __str__(self): return self.title shops/mixins.py class ShopAccountMixin(LoginRequiredMixin, object): def get_shopaccount(self): user = self.request.user shopaccount = Shop.objects.filter(user=user) if shopaccount.exists(): return shopaccount else: return None def get_shopproducts(self): account = self.get_shopaccount() ## this is the problem area.. here i want to filter like products = Product.objects.all(account....???)??? return products class shopsDashBoard(ShopAccountMixin, FormMixin, View): model = Shop form_class = SellerForm template_name = "shops/seller.html" def get(self, request, *args, **kwargs): apply_form = self.get_form() account = self.get_shopaccount() exists = account active = None context = {} if exists: active = account.active context["active"] = active if not exists and not active: context["title"] = "Apply for Account" context["apply_form"] = apply_form elif … -
Python - Inner Class Not Found
(Sorry I'm new to Python) I'm running a python django script as follows: python3 manage.py test class Command(NoArgsCommand): help = 'Help Test' def handle(self, **options): gs = self.create_goalscorer(1,"Headed") class GoalScorerX(object): id = 0 goal_type = "" #Constructor def __init__(self, id, goal_type): self.id= id self.goal_type = goal_type def create_goalscorer(self,id,goal_type): gs = GoalScorerX(id, goal_type) return gs But I get the error that it can't be found? gs = GoalScorerX(id, goal_type) NameError: name 'GoalScorerX' is not defined -
AttributeError on Django
I'm stuck with (I think) a dummy error on Django that I can't find where it's the fault. On "catalog/models.py" I have (it connects to a MySQL database): from django.db import models class Application(models.Model): nameApp = models.CharField(max_length=50) tarification = models.ForeignKey(Tarification) Then, I'm using django-tables2 (Doc to fill tables) to make tables on Django, so on my tables.py I have: import django_tables2 as tables from catalog.models import AppCost, Application, Tarification class BillTable(tables.Table): class Meta: appName = Application.nameApp userApp = AppCost.userApp tarifName = Tarification.nameTarif tarifCost = Tarification.cost startTime = AppCost.startTime finishTime = AppCost.finishTime totalCost = AppCost.totalCost # add class="paleblue" to <table> tag attrs = {'class': 'paleblue'} And I get an error when I render my website: type object 'Application' has no attribute 'nameApp' On the line appName = Application.nameApp from BillTable But, looking at "Database" window on Pycharm I see the table schema and it's: catalog_application id tarification_id nameApp other stuff And looking with MySQL Workbench the schema looks the same. So, why I'm getting this error? Regards. -
Possible to incorporate select tag in django form?
I have a django form being rendered on an html page, and I have a select dropdown menu which performs a filtering function. I was wondering if it was possible to incorporate this select tag as part of my form? I'd like the select tag to be part of routestep_form. <center> <form class ="subtitle" method = 'POST' action="{% url 'buildpage:partrequestinfo' %}" enctype="multipart/form-data">{% csrf_token %} {{routestep_form.as_p}} <select name = "myselect" id="id_step" onchange="getOptions(this.value)"> <option value="-----">-----</option> {% for step in steps %} <option value="{{ step }}">{{ step }}</option> {% endfor %} </select> <br/><br/> <select id="id_step_option"> <option value="-----">-----</option> </select> <input type='submit' value='Next'/> </form> </center> -
Django 1.10 - App models in a subdirectory not working as expected
Following the tutorial for Django 1.10 with a few small deviations: The polls app exists in mysite/apps/polls and is accessed in the project via apps.polls. The default models.py file has been removed and a new module has been added: mysite/ | |- apps/ | |- polls/ | | |- __init__.py | | |- Question.py | | |- Choice.py apps/polls/__init__.py is importing both Question and Choice, and both models are extending from django.db.models.Model. The issue Running makemigrations throws an exception: Traceback (most recent call last): File "/mysite/lib/python3.5/site-packages/django/db/models/fields/related.py", line 742, in __init__ to._meta.model_name AttributeError: module 'apps.polls.models.Question' has no attribute '_meta' However, the Question model clearly does have a _meta attribute, as it is extending from django.db.models.Model. It is my understanding that as of Django 1.7, defining _meta.app_label is not necessary (in any case, defining app_label doesn't work). Any idea what I need to do to be able to use models from a subdirectory without causing additional refactoring throughout my project? -
How to avoid being crawled/penalized by google
OVERVIEW I'd like to test some django websites using random data on a production server using real domain names but these websites will be simple tests with possible duplicated data (quite probable not following google rules). I know usually for this you use a dev/staging/virtual box for such a task but I do want to use directly the production box with the real dns. Now, I'm kind of new on website development & seo and I wouldn't like to mess with SEO & google. QUESTION What'd be the right way to proceed here? Should I try to avoid being indexed/crawled by google somehow? Any other advices? -
Terminating Django Channels function
I currently have a website, where when the user clicks a button, it sends a socket which then runs a web scraping program and returns the results to the user as it goes along. For the sake of simplicity, lets say that upon receiving a socket, it gets routed to consumers.py which has the following code: def ws_message(message): while True: print("5") time.sleep(5) However, I also want to add a "terminate" button to stop this function from running but am not sure how to go about doing so. I've thought about doing the following: cont = True def ws_message(message): text = message.content['text'] if text == 'terminate': cont = False if text == 'restart': cont = True while cont: print("5") time.sleep(5) However at the same time this code doesn't seem particularly elegant, and so I was wondering if there is a simpler way to do so. -
python manage.py migrate error
I am learning Django and was trying to migrate manage.py using the command python manage.py migrate. But what happened is (venv) Kaustubhs-MacBook-Pro-2:crmeasy kaustubhmundra$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/core/management/init.py", line 385, in execute_from_command_line utility.execute() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/core/management/init.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.dict) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 63, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in init self.loader = MigrationLoader(self.connection) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in init self.build_graph() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 179, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()): File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/init.py", line 165, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/init.py", line 138, in _cursor self.ensure_connection() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/init.py", line 133, in ensure_connection self.connect() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/init.py", line 133, in ensure_connection self.connect() File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/init.py", line 122, in connect self.connection = self.get_new_connection(conn_params) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 134, in get_new_connection return Database.connect(**conn_params) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/venv/lib/python2.7/site-packages/psycopg2/init.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" -
No module named 'endless_pagination'
I'm trying to setup endless_pagination, I've followed the documentation but getting an error: Traceback (most recent call last): File "/bin/user_wsgi_wrapper.py", line 154, in __call__ app_iterator = self.app(environ, start_response) File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application raise e File "/bin/user_wsgi_wrapper.py", line 154, in __call__ app_iterator = self.app(environ, start_response) File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application raise e File "/bin/user_wsgi_wrapper.py", line 179, in <module> application = load_wsgi_application() File "/bin/user_wsgi_wrapper.py", line 175, in load_wsgi_application return __import__(os.environ['WSGI_MODULE'], globals(), locals(), ['application']).application File "/var/www/khalid_pythonanywhere_com_wsgi.py", line 25, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No module named 'endless_pagination' I installed it using easy_install -Z django-endless-pagination, and added 'django.core.context_processors.request' in the Settings.py context_processors (under TEMPLATES). I added 'endless_pagination' in the installed apps section of the Settings.py. These are the steps from the documentation, when I reload the server, I get ImportError: No module named 'endless_pagination'. What seems to be the problem here? Any help/direction would be appreciated, Thanks -
Django admin expiring session all the time
I have a Django project that works perfectly locally, but I can't use the admin page in the server because the page is reloaded every time I click in the links and the user credentials are re-requested. I cleaned cache, cookies and the session data in db, but the problem persists. How to solve this? These are my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'website' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] -
Unable to use dict sent from Django to template
I have the following dict in python which I send to the template: mydict = { "ABC": { "target_weight": 1, "target_ra_weight": 2 }, "XYZ": { "target_weight": 3, "target_ra_weight": 4 }, "JKL": { "target_weight": 5, "target_ra_weight": 6 } } return render(request, 'template.html', {'mydict': mydict}) I can't seem to assign this to a javascript variable and access the content. I have tried all of the following in the javascript section of my template: var mydict = {{ mydict }}; > Uncaught SyntaxError: unexpected token { var mydict = {{ mydict|safe }}; > Uncaught SyntaxError: unexpected token { var mydict = {{ mydict|escapejs }}; > Uncaught SyntaxError: unexpected token { The following allows me to create the variable, but when I try to access it (eg: console.log(mydict)), then I an error: var mydict = JSON.parse('{{ mydict }}'); console.log(mydict); > Uncaught SyntaxError: unexpected token { in JSON at position 1 // same thing happens when using |safe or |escapejs -
Getting error on redirect django
What am I trying to do is if a user comes with a slug Case 1 'new' I am either creating a new box for him or fetching his existing empty box and redirecting him based on the slug of the box Case 2 anything else works fine URL pattern is url(r'^box/manage/(?P<slug>.*)/$', login_required(views.ManageBoxView.as_view()), name='manage_box'), I am getting an error dict' object has no attribute 'has_header' class ManageBoxView(TemplateView): template_name = "art/manage_box.html" def get(self, request, **kwargs): if kwargs['slug'] == 'new': box = Box.get_or_create_empty_box(self.request.user) return redirect('manage_box', slug= box.slug) else: box = Box.objects.get(slug=kwargs['slug']) return {'box': box, 'drafts': box.drafts} Stack Trace Environment: Request Method: GET Request URL: http://localhost:8000/box/manage/10-untitled-admin/ Django Version: 1.7.4 Python Version: 2.7.11 Installed Applications: ('django_admin_bootstrapped', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.humanize', 'django.contrib.staticfiles', 'gunicorn', 'rest_framework', 'imagekit', 'utils', 'users', 'arts', 'notification', 'connect', 'payment', 'products', 'orders', 'social') Installed Middleware: ('sslify.middleware.SSLifyMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'raygun4py.middleware.django.Provider') Traceback: File "/home/cj/.vrtualenvs/canvs/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 204. response = middleware_method(request, response) File "/home/cj/.vrtualenvs/canvs/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py" in process_response 30. patch_vary_headers(response, ('Cookie',)) File "/home/cj/.vrtualenvs/canvs/local/lib/python2.7/site-packages/django/utils/cache.py" in patch_vary_headers 148. if response.has_header('Vary'): Exception Type: AttributeError at /box/manage/10-untitled-admin/ Exception Value: 'dict' object has no attribute 'has_header' -
Get checkout user details and shipping address from the twotap api
I'm working on an eCommerce site which uses twotap api for product purchase. I want to get the user details and shipping address provided by the user in the product checkout form in twotap api. -
Want to make my field to be dynamic using Add another field option
I want user to upload as many as more photos and for that i need to make photo uploading field dynamic. I got the answer how to make models dynamic using "extra" field in admin.py but i only want to make a single filed repeat with our choice and store data in database. Is it possible? How? -
MongoDBForm error "ValueError:A document class must be provided"
Hi i am creating a simple Sign Up form with django framework and mongodb. Following is my view: class SignUpView(FormView): template_name='MnCApp/signup.html' form_class=EmployeeForm succes_url='/success/' Following is my model: class Employee(Document): designation=StringField() department=StringField() emp_name=StringField(max_length=50) password=StringField(max_length=10) Following is my forms.py class EmployeeForm(DocumentForm): class meta: desigs=( ('D','Director'), ('GM','General Manager'), ('AM','Assistant Manager'), ('A','Associates') ) deptts=( ('HR','Human Resources'), ('IT','IT Support'), ('TT','Technical Team'), ('SM','Sales and Marketting'), ('SS','Support Staff') ) document=Employee fields='__all__' widgets={ 'designation':Select(choices=desigs), 'department':Select(choices=deptts) } Following is the traceback ValueError recieved on loading SignUpview Traceback: File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files\Python35\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get 174. return self.render_to_response(self.get_context_data()) File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get_context_data 93. kwargs['form'] = self.get_form() File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get_form 45. return form_class(**self.get_form_kwargs()) File "C:\Program Files\Python35\lib\site-packages\mongodbforms\documents.py" in init 353. raise ValueError('A document class must be provided.') Exception Type: ValueError at /signup/ Exception Value: A document class must be provided. I am not able to find root of this problem. I am new to django and this is my first project. … -
ImportError: No module named ShownameConfigcrispy_forms
I did pip install as asked: pip install --upgrade django-crispy-forms and there is my installed appes when doind pip freeze: django==1.10 django-crispy-forms==1.6.0 freeze==1.0.10 PIL==1.1.7 PyAudio==0.2.9 six==1.10.0 But for some reason, when im trying to run the server, i get: Unhandled exception in thread started by <function wrapper at 0x00000000040CBF28> Traceback (most recent call last): File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\python27\lib\site-packages\django-1.10-py2.7.egg\django\apps\config.py", line 123, in create import_module(entry) File "C:\python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named ShownameConfigcrispy_forms I searched in the internet to find out an answer. but no one got hellped. Somebody know why its happening? -
Loading all data at once in template (costly?)
Present all [member] names to the user, When user clicks a [member], the history of that [member] is displayed. My approach is to select all the members, load their names in the template, and load each member's history in collapsed divs. (member's history is recorded in related models) I'm testing this with 3 users, what if there are 20,000 users? and each user has hundreds of historical records? Would this approach be costly? Should I stay the course or is there an alternative approach I should take? Any help/direction would be appreciated, Thanks -
How to work with Django inline forms?
I have two models (Receipt and Ingredient) and want to create ingredients when creating receipt. forms.py from django import forms from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import Receipt, Ingredient, CookingStep class ReceiptForm(forms.ModelForm): class Meta: model = Receipt fields = ('name', 'description', 'hour', 'minute', 'multivarka',) ReceiptFormSet = inlineformset_factory(Receipt, Ingredient, fields=('name', 'count', 'value')) models.py from django.db import models class Receipt(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=1024) hour = models.IntegerField(default=0) minute = models.IntegerField(default=1) multivarka = models.BooleanField(default=False) def __str__(self): return "%s" % (self.name) class Ingredient(models.Model): name = models.CharField(max_length=255) count = models.IntegerField(default=0) #200gr, 1kg etc value = models.CharField(max_length=255) #gramm, kg etc receipts = models.ForeignKey(Receipt) def __str__(self): return "%s" % (self.name) views.py def receipt_new(request): if request.method == "POST": formset = ReceiptForm(request.POST) if formset.is_valid(): created_receipt = formset.save(commit=False) new_formset = ReceiptFormSet(request.POST, instance=created_receipt) if new_formset.is_valid(): created_receipt.save() new_formset.save() return redirect('/receipts') else: formset = ReceiptForm() inline_form = ReceiptFormSet() return render(request, 'admin_site/receipt_edit.html', {'formset': formset}) receipt_edit.html {% block content %} <h1>New receipt</h1> <form method="POST" class="post-form">{% csrf_token %} {{ formset.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} Now only form for creating receipt is displayed. I want to have two forms on edit page: firstly form for receipt and then form for creating ingredient for this receipt … -
how to measure performance of third party app
Now, I'm fairly new to django Before installing a third party app I want to measure performance of it! what is the best way to do this or is there any way to do this except experimental way ? Now I have a problem to boost performance of my search results and I searched, I found haystack related apps like saved_search and .. etc I have a task to make searches request or queries to grib data from Solr not from my PostgreSQL database and I'm confused to use any third party or it is embedded in solr or using django cache What is the best way to do this? Thanks -
Django-Leaflet - set dynamic layers
I want to set DynamicMapLayer to my django-leaflet template. Maybe anyone knows how can I do it? I prefer this like L.esri.dynamicMapLayer, maybe L.esri.featureLayer from esri-leaflet.js plugin. -
Django Admin showing Object - not working with __unicode__ OR __str__
my Django admin panel is showing object instead of self.name of the object. I went through several similar questions here yet couldn't seem to resolve this issue. unicode and str bear the same results, both for books and for authors. I've changed those lines and added new authors/books in every change but no change. MODELS.PY from django.db import models from django.contrib.auth.models import User # Create your models here. class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): auto_increment_id = models.AutoField(primary_key=True) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=False, null=False) contents = models.TextField('Contents', blank=False, null=False) def __unicode__(self): return self.name I used both unicode & str interchangeably, same result. Here are the screenshots of the admin panel by menu/action. 1st screen Author List Single Author -
Run Django test case raise errror
I have read TestCase module from Django Docs.And I tried to use this in my django project. Howerer,I got a Error like this: ** Error Traceback (most recent call last): File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/test/testcases.py", line 1026, in setUpClass if not connections_support_transactions(): File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/test/testcases.py", line 991, in connections_support_transactions for conn in connections.all()) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/test/testcases.py", line 991, in <genexpr> for conn in connections.all()) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/backends/base/features.py", line 226, in supports_transactions cursor.execute('CREATE TABLE ROLLBACK_TEST (X INT)') File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/home/hp/.virtualenvs/shouchela/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1142, "CREATE command denied to user 'xxxx'@'xxx' for table 'ROLLBACK_TEST'") ** And Here is my code: import os import socket import sys hostname = socket.gethostname() SETTINGS_DICT = { 'slave': "shouchela.settings.chewantest", 'master': "shouchela.settings.dev", } SETTINGS = SETTINGS_DICT.get(hostname, "shouchela.settings.dev") os.environ.setdefault("DJANGO_SETTINGS_MODULE", SETTINGS) parent = lambda path, count: parent(os.path.dirname(path), count - 1) if count > 0 else path sys.path.insert(0, … -
Unable to init Form in ModelFormset (unexpected keyword arg)
With the following model (where fk_survey is defined), I try to create a formset using a ModelForm. The trouble is, when I try to pass fk_survey as form_kwargs to the Form of the ModelFormset, I get the unexpected keyword arg error when the interpreter calls __init__(). However, fk_survey is a kwarg to the ModelForm! What did I do wrong? models.py class Question(models.Model): fk_survey = models.ForeignKey(Survey, on_delete=models.SET_NULL, null=True, related_name="questions") text = models.CharField(max_length=128) forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['fk_survey','text',] def __init__(self, *args, **kwargs): self.fk_survey = kwargs.pop('fk_survey', None) views.py class QuestionsCreate(CreateView): """ Use a ModelFormset to associate several questions to a Survey """ def get(self, request, *args, **kwargs): #get the Survey from url regex group survey = get_object_or_404(Survey, pk=self.kwargs['pk']) #define the Formset QuestionModelFormset = modelformset_factory(Question, form=QuestionForm, extra=1, can_delete=True, can_order=True) form_kwargs = {'fk_survey': survey} context['question_formset'] = QuestionModelFormset( form_kwargs=form_kwargs, queryset=Question.objects.filter(fk_survey=survey)) -
ProgrammingError (Error during template rendering)
I am getting this Exception in my browser, I have seen upto 20 posts related to this error but I could not have found any solution.I am using Postgre database (pgAdmin 4). I am new to Django, Please help me, Thanks in advance. projectname/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('blog.urls')), ] My views.py def blog_list(request): posts = Blog.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/blog_list.html', {'posts': posts}) blog_list.html {% for post in posts %} <div class="post"> <div class="date"> {{ post.published_date }} </div> <h1><a href="{% url 'blog_detail' pk=post.pk %}">{{ post.title }}</a></h1> <p>{{ post.short_description|linebreaksbr }}</p> </div> {% endfor %} my models.py class Blog(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) sub_title = models.CharField(max_length=100, null = True) short_description = models.CharField(max_length=100, null = True) long_description = models.TextField(null = True) #text = models.TextField() published_date = models.DateTimeField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class DeletedPost(models.Model): post_title = models.CharField(max_length=200, null=True) deleted = models.DateTimeField(default = timezone.now) my appname/urls.py urlpatterns = [ url(r'^$', views.blog_list, name='blog_list'), url(r'^blog/(?P<pk>\d+)/$', views.blog_detail, name='blog_detail'), url(r'^blog/new/$', views.blog_new, name='blog_new'), url(r'^blog/(?P<pk>\d+)/edit/$', views.blog_edit, name='blog_edit'), url(r'^blog/(?P<pk>\d+)/delete/$', views.post_delete, name='post_delete'), ] Error in Browser : Traceback: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
react: how to pass in URLs for REST APIs
Starting to learn react and couldn't find the answer to this on the internet. Maybe I don't know what terms to use. My backend is django and I want to be able to pass in URLs for REST APIs to my React front end. I don't want to hard code them in react as they are already defined in django. It makes sense to me that I would want to render a script tag on my html template that contains an object containing the URL values. e.g. the django template would have something like <script type="text/javascript"> var CONFIG = { some_url : '{% url "my-api" %}' } </script> (for those not familiar with django, that {% url %} tag renders a url like /path/to/myapi) Then in my React Stores/Actions I would just refer to CONFIG.some_url. Is this the right way to do it? Or is there a better way to make this information available to my react components.