Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App Fails with Gunicorn, Fine With Runserver
I am trying to debug an application that works locally, but I am running into issues deploying to Heroku. Using heroku local, I am able to see this stack trace 10:43:00 AM web.1 | Traceback (most recent call last): 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 507, in spawn_worker 10:43:00 AM web.1 | worker.init_process() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 118, in init_process 10:43:00 AM web.1 | self.wsgi = self.app.wsgi() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 10:43:00 AM web.1 | self.callable = self.load() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 10:43:00 AM web.1 | return self.load_wsgiapp() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 10:43:00 AM web.1 | return util.import_app(self.app_uri) 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/gunicorn/util.py", line 355, in import_app 10:43:00 AM web.1 | __import__(module) 10:43:00 AM web.1 | File "/Users/cbuddeke/Dropbox/DC-Development/ThreePoints Website/tp/threepoints/wsgi.py", line 19, in <module> 10:43:00 AM web.1 | application = get_wsgi_application() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application 10:43:00 AM web.1 | django.setup() 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup 10:43:00 AM web.1 | apps.populate(settings.INSTALLED_APPS) 10:43:00 AM web.1 | File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate 10:43:00 AM web.1 | app_config = AppConfig.create(entry) … -
Django how to get password after registration form is submitted?
I'm trying to edit django-registration's RegistrationFormUniqueEmail form, which currently looks like the following: class RegistrationFormUniqueEmail(RegistrationForm): """ Subclass of ``RegistrationForm`` which enforces uniqueness of email addresses. """ def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError(validators.DUPLICATE_EMAIL) return self.cleaned_data['email'] I want to implement a form that checks if the password has a number and a special character, but I'm failing to get the password? I'm not sure if it's even possible, but here is what I tried to get the password: self.cleaned_data['id_password2'] self.cleaned_data['password2'] self.cleaned_data['password'] self.cleaned_data.get('id_password2') self.cleaned_data.get('password2') self.cleaned_data.get('password') all of these return a NoneType object. I also tried to define a clean_password2 function, but no help. Is this doable? And how so? Thanks for any help, -
Django template tag content missing when extending admin app base template
So I am creating a page in my Django project that essentially just uses the Django admin app header and footer. I have a template folder in the root of my project where I have my base.html. /templates/admin/base.html {% load i18n static %}<!DOCTYPE html> {% load static %} {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'js-stack/assets/css/spark-styles.css' %}" /> <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}" /> {% block extrastyle %}{% endblock %} {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}" />{% endif %} {% block extrahead %}{% endblock %} {% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %} </head> {% load i18n %} <body class="{% if is_popup %}popup {% endif %}{% block bodyclass %}{% endblock %}" data-admin-utc-offset="{% now "Z" %}"> <!-- Container --> <div id="container"> {% if not is_popup %} <!-- Header --> <div id="header"> <div id="branding"> {% block branding %}{% endblock %} </div> {% block usertools %} {% if has_permission %} <div id="user-tools"> {% block welcome-msg %} {% … -
Generic ListView with filter pk
I am using django 1.10 and developing a shopping site which has lots of products under each category. I am trying to use generic.ListView on my view page for category page to display all the products under that category. Here is my code urls.py from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^(?P<pk>[0-9]+)$', views.CategoryView.as_view(), name='category'), url(r'^product/$', views.product, name='product'), ] my views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Category, Product def index(request): all_category = Category.objects.all() context = {'all_category': all_category} return render(request, 'shopping/index.html', context) class CategoryView(generic.ListView): template_name = 'shopping/category.html' def get_queryset(self): self.category_id = get_object_or_404(Category, pk=self.kwargs['pk']) return Category.objects.filter(pk=self.category_id) def product(request): return render(request, 'shopping/product.html') my models.py from django.db import models class Category(models.Model): category_name = models.CharField(max_length=250) category_image = models.CharField(max_length=1000) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_description = models.TextField(max_length=5000) product_mrp = models.CharField(max_length=100, default='mrp') product_price = models.CharField(max_length=100) product_image = models.CharField(max_length=1000) product_image1 = models.CharField(max_length=1000) product_image2 = models.CharField(max_length=1000) product_brand = models.CharField(max_length=1000, default='brand') and my category.html {% for products in object_list.product_set.all() %} <li>{{ products.product_name}}</li> <li>{{ products.product_price}}</li> {% endfor %) Please let me know what i am doing wrong. -
Django: Bootstrap Accordion not working on Regroup content
Django with Bootstrap 3 I am working on a dashboard view for an FAQ system. I have set up the articles to be grouped by section. The section names are the headers in a list-group that when clicked will expand another list-group containing all the articles related to that group. The issue that I am having is that I would like to set up the collapse to work like an accordion. I have followed bootstrap 3’s guide to accomplish this but when I click a new section open none of the prior open sections collapse close. I have exhausted other guides but the code looks correct yet the accordion functionality is not working. My code: {% block content %} <div class="iron-faq"> <div class="container"> <div class="col-md-6"> <h3>Sections</h3> <div class="list-group" id="accordion" aria-multiselectable="true"> {% regroup articles by section as section_list %} {% for section in section_list %} <a href="#section-{{ section.grouper.id }}" class="list-group-item list-header" data-toggle="collapse" data-parent="#accordion" data-target="#section-{{ section.grouper.id }}" aria-controls="section-{{ section.grouper.id }}"> <i class="fa fa-bars"></i> {{ section.grouper }} <span class="badge pull-right">{{ section.grouper.article_count }}</span> </a> <div class="panel-collapse collapse" id="section-{{ section.grouper.id }}"> {% for article in section.list %} <a href="{{ article.get_absolute_url }}" class="list-group-item"> {{ article.title }} </a> {% endfor %} </div> {% endfor %} </div> </div> … -
Passing argmuents through error handling
I'm using custom error handling following Django's Documentation in a project I'm contributing to with a template displaying some random quotes along with the error code and the message. But, knowing that a same template is supposed to render for every handlers (404, 403, 400 & 500), I thinked of building only one view getting the error code (and the error message as well casted by raise Http404("some error message")) as a parameter to keep on the DRY principle. Being a beginner, the solution I thought of would have been: handler404 = views.error_view(404) in the urls.py file, and here's the views.py: def error_view(request, error_code): quote = Quote.objects.filter_by('?').first() render(request, 'error.html', { 'error_code': error_code, 'quote': quote, }, status=error_code) Is this solution even correct and is there a better (and cleaner way) of doing it ? -
Inheritance between classes in python
I have 3 classes A , B and C. and both B and C inherit some variables from A class Each of B and C classes have the same methods with the same logic but with a little bit difference in variable names . this the example: class A(FilteredListView): model = book template_name = 'book.html' class B(A, PatientObject): def get_queryset(self): instance = self.get_patient_instance_by_credential(**self.get_patient_details(self.kwargs.copy())) if instance: patient = Patient.objects.get(id=instance.id) content_type_id = ContentType.objects.filter(model="patient").values('id') logs = LogEntry.objects.filter(content_type_id=content_type_id, object_id=patient.id) users = set([get_user_model().objects.get(id=log.user_id) for log in logs]) return {'log_entry': logs, 'user': users} return [] def get_context_data(self, *args, **kwargs): context = super(B, self).get_context_data(*args, **kwargs) context['log_entry'] = self.kwargs.copy() return context class C(A, PatientObject): def get_queryset(self): instance = self.get_patient_instance_by_credential(**self.get_patient_details(self.kwargs.copy())) episode_id = self.kwargs['pk'] # get the id of the pathway from the url if instance: episode = Episode.objects.get(patient=instance.id, id=episode_id) content_type_id = ContentType.objects.filter(model="episode").values('id') logs = LogEntry.objects.filter(content_type_id=content_type_id, object_id=episode.id) users = set([get_user_model().objects.get(id=log.user_id) for log in logs]) return {'log_entry': logs, 'user': users, 'episode': episode} return [] def get_context_data(self, *args, **kwargs): context = super(C, self).get_context_data(*args, **kwargs) context['log_entry'] = self.kwargs.copy() return context Is there a way to put the methods get_queryset() and get_context_data() in the parent class A with global variables? And how to define variables for each child class ?? -
Django using fields from two different models in another model
My models looks like following: class City(models.Model): name = models.CharField(max_length=20, blank=False) pin = models.IntegerField(null=False, ) def __str__(self): return u"%s" % (self.name) class Localities(models.Model): name = models.CharField(max_length=50, blank=False,) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return u"%s, %s" % (self.name, self.city) class Hall(models.Model): name = models.CharField(max_length=30, blank=False, verbose_name="Name of the Marriage Hall", ) city = models.ForeignKey(City, on_delete=models.CASCADE, ) landmarks = models.CharField(max_length=50, blank=False, verbose_name="Landmarks of the Marriage Hall", ) seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Marriage Hall",) ac = models.BooleanField(null=False, verbose_name="Is the Marriage Hall AC?",) garden_lounge = models.BooleanField(null=False, verbose_name="Is the Marriage Hall garden_lounge?",) avg_user_rating = models.DecimalField(max_digits=10, null=False, decimal_places=5, verbose_name="Average user rating of the Marriage Hall",) comments = models.CharField(max_length=50, blank=False, verbose_name="Customer comments for this Marriage Hall", ) rent = models.DecimalField(max_digits=10, decimal_places=5, blank=True, ) def __str__(self): return u"%s, %s" % (self.name, self.city) This gives me browsable API as follows: What I would like to have is also localities in my hall model, but when I select a specific city, localities related to that city should be populated. How can I achieve this? How can I modify my models? -
Create a new custom user or upate existing one
I have created a Custom user model: class CUserManager(BaseUserManager): def _create_user(self, email, first_name, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given email and password. """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, first_name = first_name, is_staff=is_staff, is_active=False, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, first_name, password=None, **extra_fields): return self._create_user(email, first_name, password, False, False, **extra_fields) def create_superuser(self, email, first_name, password, **extra_fields): return self._create_user(email, first_name, password, True, True, **extra_fields) class CUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=False, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) last_updated = models.DateTimeField(_('last updated'), default=timezone.now) image = ProcessedImageField(upload_to= generate_random_filename, processors=[ResizeToFill(640, 640)], format='JPEG', options={'quality': 60}) objects = CUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def save(self, *args, **kwargs): try: this = CUser.objects.get(id=self.id) if this.image != self.image: this.image.delete() except: pass super(CUser, self).save(*args, **kwargs) My regisration serializer: class UserRegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, … -
DRF: What is the proper way to handle instances creation with nested serializers?
I have 2 models related by a FK: class Recipe(models.Model) title = models.Charfield(max_length=128) class RecipeEntry(models.Model): index = models.IntegerField() recipe = models.ForeignKey(Recipe) Using Django Rest Framework, I want to allow creation of 1 Recipe and N RecipeEntryobjects at once. The POST data of the endpoint would contain something like: { "title": "Poulet à l'ananas", "recipe_entries": [ {"index": 1}, {"index": 2} ] } Then, I created 2 model serializers for each model: class CreateRecipeSerializer(serializers.ModelSerializer): recipe_entries = CreateRecipeEntrySerializer(many=True, write_only=True) class Meta: model = Recipe fields = ('title', 'recipe_entries') def create(self, validated_data): _ = validated_data.pop('recipe_entries') # I want to manage this in the appropriate serializer recipe = Recipe.objects.create(**validated_data) return recipe class CreateRecipeEntrySerializer(serializers.ModelSerializer): index = serializers.IntegerField() class Meta: model = RecipeEntry fields = ('index',) def create(self, validated_data): # What to do here? recipe_entry = RecipeEntry.objects.create(index=validated_data.get('index'), recipe=????) return recipe_entry The purpose is: each serializer must handle their object creation (to avoid handling all data creation in the root serializer). However, I don't know how to write create() method for CreateRecipeEntrySerializer. I don't understand how to specify the recipe because I suppose the instance does not exist yet. NOTE: I simplified the code for the SO question, removing lots of fields, and I have actually more that … -
Django session data sharing between apps on the same domain
We are integrating two applications running at the same domain (with cookies visible to both of them). Django application is handling all user account data, say it runs on subdomain www.. The second application, running at subdomain app. is PHP based (CakePHP) and needs a way to fetch user information based on the session cookie it is able to see from the main Django app. Each of the applications will be living on separate resources and will not have access to one another's database records. As such, I am thinking that I would need to build an API for the PHP server to query to get login information but my question is - is something similar already out there? If not, are they any specific best-practise guidelines to follow when implementing this? -
Minimum supported python version of boto-2.38.0
Does any one know what is the minimum supported python version of boto-2.38.0? -
Django cross-app models
How do you access a model from across apps? For instance: app:customers -view:customerdetail model:customers table:tblCustomers app:reports -view:reportdetail model:customers table:tblReports The reason for this is because the original DB was set up with every table contained within the same DB. Would it be better to just create one app for the many things I need to do within the one database? I know I can't just duplicate the model. I need to reference many things within the model I've integrated into my customers app. -
Difference between celery called through manage.py and celery called itself
I'm deploying a Django project on DigitalOcean and I use $ celery worker -A project -l info & and $ celery beat -A project -l info & to run the Celery and Celerybeat. Recently, I've read that I can do python manage.py celery worker and the same with beat. Is there some difference or is it the same? If there is a difference, which commands should I use? -
The best django course
Can you tell me the best course teaching django? -
TypeError("Cannot convert %r to Decimal" % value) TypeError: Cannot convert <LenderInvestment: 20000.00> to Decimal
class LenderInvestment(models.Model): user = models.ForeignKey(User) investment = models.DecimalField(max_digits=15, decimal_places=2, default=1000000) initial_capital = models.DecimalField(max_digits=12, decimal_places=2, **optional) def __unicode__(self): return str(self.initial_capital) class LoanDisbursement(models.Model): user = models.ForeignKey(User) initial_capital = models.OneToOneField(LenderInvestment) loan_applicant = models.ForeignKey(LoanApplication) money_disbursed = models.DecimalField(max_digits=10, decimal_places=2) def __unicode__(self): return str(self.user) def loan_disbursement_receiver(sender, instance, *args, **kwargs): initial_capital = instance.initial_capital money_disbursed = instance.money_disbursed initial_capital = Decimal(initial_capital) - Decimal(money_disbursed) instance.initial_capital = initial_capital pre_save.connect(loan_disbursement_receiver, sender=LoanDisbursement) I have two models as shown above inorder to calculate the value from one model instance to another model instance I need help, when I connected as above it gives type error. Looking forward for some positive reply. -
Using Django Timezones in settings.py and views.py and postgresql
I set and use the following codes: In my views.py or python codes timezone.now() What I get in database table: "2016-10-27 04:14:35.972280+00:00" What's in settings.py: LANGUAGE_CODE = 'en-us'TIME_ZONE = 'Asia/Manila' USE_I18N = True USE_L10N = True USE_TZ = True And how I query and use it in views.py: today = timezone.now() today = current_event.objects.filter(regDate__year=today.year, regDate__month=today.month, regDate__day=today.day, reg=True, ) In Django templates, the local timezone is displayed. My question is when I use the code above, I get a result that's consistent of +0 00 timezone or the timezone parameter in the DB entry. I would like to know if there's a way so that the code above will use my timezone instead of the on in DB. Thank you. -
Django one click action, generate and open multiple PDFs in individual tabs
I want to generate multiple (more than one) PDFs and open each PDF in an individual tab for review and follow-up actions. At the moment I don't want to save PDFs before review, so I use GET method. I use a form to gather configs for PDF generation, and with submit button I open a new tab with a parametrized URL used to generate a PDF. Please find critical elements below. urls.py url( r'^tags_list/$', view=views.tags_list, name="tags_list" ), url( r'^tags/$', view=views.generate_pdfs, name='report'), tags_list.html <form action="/tags/" method="get"> {{ form } ... <input type="submit" value="Submit" formtarget="_blank"/> </form> views.py def generate_pdfs(request, **kwargs): # get kwargs tags = request.GET.get('tags') ... response = reports.pdf1(context) #response = reports.pdf2(context) #response = reports.pdf3(context) return response reports.py def pdf1(context): html = render_to_string('pdf1.html', context) #generate PDF response, I use weasyprint for that return response pdf1.html <html>...</html> I however failed to find examples on how to open multiple tabs from views (Django), may be because of the lack of knowledge (which is well present, the lack of) or that this is impossible (or very hard in Django), or this is a very unorthodox request. A JS solution to open multiple tabs with slightly different urls wouldn't work for me because of randomized … -
crlibm.h no such file while installing pyinterval
Hi iam trying to install pyinterval but is running into the issue.I am trying to install to my own virtual env. Also including the log below Running setup.py install for pyinterval Running command /home/jibin/Desktop/chef/env/bin/python -c "import setuptools, tokenize;__file__='/home/jibin/Desktop/chef/env/build/pyinterval/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-hJmNF8-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/jibin/Desktop/chef/env/include/site/python2.7 running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/interval copying interval/__init__.py -> build/lib.linux-x86_64-2.7/interval copying interval/imath.py -> build/lib.linux-x86_64-2.7/interval copying interval/fpu.py -> build/lib.linux-x86_64-2.7/interval copying ./LICENSE -> build/lib.linux-x86_64-2.7/interval running build_ext building 'crlibm' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/ext x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/opt/crlibm/include -I/usr/include/python2.7 -c ext/crlibmmodule.c -o build/temp.linux-x86_64-2.7/ext/crlibmmodule.o ext/crlibmmodule.c:7:20: fatal error: crlibm.h: No such file or directory #include "crlibm.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Complete output from command /home/jibin/Desktop/chef/env/bin/python -c "import setuptools, tokenize;__file__='/home/jibin/Desktop/chef/env/build/pyinterval/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-hJmNF8-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/jibin/Desktop/chef/env/include/site/python2.7: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/interval copying interval/__init__.py -> build/lib.linux-x86_64-2.7/interval copying interval/imath.py -> build/lib.linux-x86_64-2.7/interval copying interval/fpu.py -> build/lib.linux-x86_64-2.7/interval copying ./LICENSE -> build/lib.linux-x86_64-2.7/interval running build_ext building 'crlibm' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/ext x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/opt/crlibm/include -I/usr/include/python2.7 -c ext/crlibmmodule.c -o build/temp.linux-x86_64-2.7/ext/crlibmmodule.o ext/crlibmmodule.c:7:20: … -
Create solution for category attributes
I have a goal to create some feature. What I need. There are two models Products and Category. Products has Foreign key to Category. In the same time different Categories should have different Attributes. For example: Category "Cats" has attribute "breed" and Category "Cars" has attributes "model", "mark", "Color" etc.. Attributes should contains list of values. How the best way to create it in Django? I really haven't any ideas how to make the models design to achieve my goal. @As a result, I need to create a form in which, depending on the selected category will change the list of available attributes. -
Python Error AttributeError: 'User' object has no attribute 'set_passsword'
Here is my code from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] That is where i am extending the in built user model but when i try to use it later in the form it creates an error Here is the error source # Prosses form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned (Normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_passsword(password) # Error source user.save() thanks -
Django admin manytomany
Good day,I try in admin customize forms model with many to many fields class CasinoForm(forms.ModelForm): class Meta(): model = Casino country = forms.MultipleChoiceField(choices=CasinoCountries.objects.all().values_list('id', 'name_ru').order_by('name_ru')) When i try save it, it saved but not returned selected, how return selected items -
Why URLconf is working locally but failing in production
I am just setting up an empty django project to test a new server. I have my django project working locally, showing the "Hello World!" for for the base URL and also and data/ app domain. main_project urls.py ----- from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^data/', include('data.urls'), name="data"), url(r'^', include('mainsite.urls'), name="mainsite"), ] ##################### main_project mainsite urls.py ----- from django.conf.urls import url from . import views app_name = 'mainsite' urlpatterns = [ url(r'^$', views.index, name='index'), ] ##################### main_project data urls.py ----- from django.conf.urls import url from . import views app_name = 'data' urlpatterns = [ url(r'^$', views.index, name='index'), ] Its a very basic setup, and locally, using python manage.py runserver everything works. One production the base url (http://www.mondonect.com/) works but the data url (http://www.mondonect.com/data) fails with the following error: Strange that it works locally but not in production. Its apache 2 server with wsgi, ubuntu 14.04. Django version 1.10.2. -
Unable to see scope variable using django angular
i am to use django with angular js here is the controller myHeader.js var myHeader = angular.module('myHeader', []); myHeader.controller('HeaderController' , ['$scope', function($scope){ $scope.PasswordReset = function(){ $scope.message = "done"; }; }]); then i have included this controller in the header.html <script type="text/javascript" src="{% static 'js/libs/angular.min.js' %}"></script> <!-- Angular Includes --> <script type="text/javascript" src="{% static 'js/controllers/myHeader.js' %}"></script> <body ng-app="myHeader"> <div id="forgotPass" ng-controller="HeaderController"> <h4 class="modal-title text-center" style="font-size:18px; margin-bottom:10px; margin-top:10px;"><strong>Change Password</strong> </h4> <div id="div_id_email" class="form-group required"> <div class="controls "> <form id="password_reset" action="{% url 'account_reset_password' %}" method="POST" novalidate ng-submit="PasswordReset()"> {% csrf_token %} <input class="emailinput form-control" id="id_email" name="email" type="email" placeholder="E-mail" style="margin-bottom:10px" ng-model="user.email" ng-required="true"/> {{message}} <div> <input class='btn btn-block btn-primary pull-left' id="pass-btn" type="submit" value="SUBMIT" style="width: 63%" /> <input class='btn btn-block btn-primary pull-right' style="width:34%; margin-top: 0px; background-color: #757575; border: 1px solid #616161;" value="Cancel" id="canPass"/> </div> <div class="error-box"> <div class="err2"></div> <div class="ajax-sign"><img src="/static/images/ajax1.gif" height="30px"></div> </div> </form> </div> </div> </div> </body> the above header.html file is being included in base.html {% load staticfiles %} {% include 'products/header.html' %} {% block content %} {% endblock %} With the Above i am unable to see the scope variable message value when i submit the form. How can i get rid of the above problem ? -
count visitors on your site
I want to import countviews app and embed it into my project. Im using django 1.10, python 2.7 I used pip install django-hitcount and add 'hitcount' into installed apps(myapp/settings.py). When i want run server i got an error: "myapphitcount" module not found. In directory MYAPP i dont have folder hitcount. should i run python manage.py startapp hitcount?