Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Createsuperuser django.db.utils.IntegrityError: NOT NULL constraint failed
I have recently change my model which is a personified model adding fields. After having done so I remove the file: 'db.sqlite3' And launch: python manage.py migrate --run-syncdb The user creation via my application is fine but when I want to create a super user python manage.py createsuperuser I get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: website_dater.latitude -
Static files not found in Mezzanine
I am trying to install a new template on my Mezzanine website. My Mezzanine is on version 4.2.2 and Django on 1.9.7 . Here is what I did: With DEBUG = true I created a new app call "template_app" and loaded in settings.py: INSTALLED_APPS = ( "template_app", ... ) I created the directory structure, and copied over the default mezzanine files (base, index...) like: template_app static css img js templates base.html index.html includes footer_scripts.html I downloaded a bootstrap template and replaced the above css js img folder and index.html with the ones found in the template. (The template I used: https://startbootstrap.com/template-overviews/business-casual/ ) Then link the css and javascript in base.html: (All css) {% compress css %} <link rel="stylesheet" href="{% static "css/bootstrap.css" %}"> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/business-casual.css" %}"> <link rel="stylesheet" href="{% static "css/mezzanine.css" %}"> <link rel="stylesheet" href="{% static "css/bootstrap-theme.css" %}"> (All js) {% compress js %} <script src="{% static "mezzanine/js/"|add:settings.JQUERY_FILENAME %}"></script> <script src="{% static "js/bootstrap.js" %}"></script> <script src="{% static "js/bootstrap.min.js" %}"></script> <script src="{% static "js/jquery.js" %}"></script> <script src="{% static "js/bootstrap-extras.js" %}"></script> I'm not sure where I did wrong, or what I am missing. My website can't find the css and javascript file in the … -
TemplateDoesNotExist at /core/
Django TemplateDoesNotExist? Running the server i get such exception: TemplateDoesNotExist enter image description here models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): GENDER_CHOICES = (("M","MALE"),("F","FEMALE")) user = models.OneToOneField(User) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default="M") Age = models.IntegerField() class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTim``eField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect # Create your views here. def index(request): return HttpResponse("Hello, You are in the core index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) from .models import Question from django.template import loader # def index(request): # latest_question_list = Question.objects.order_by('-pub_date') [:5] #output = '<br>'.join([q.question_text for q in latest_question_list]) # return HttpResponse(output) def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('core/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) Running the server i get such Django TemplateDoesNotExist? exception: TemplateDoesNotExist -
Problems with Newlines using django on a Windows Server in France
Problem: My django app is introducing a CR before each CRLF when writing to a file a string which has been read in via render_to_string. In my template files, I used CRLFs, and the django processing app writes a file which adds a CR before each CRLF. See below for code details. However: this only happens with my app which is on my clients' Windows Server 12R2 VM which is located in France. My physical Windows 10 laptop, my ubuntu instances and my AWS Windows Server 12 instance (which I use for testing before installing on my client's machine) do not add the CRs. Caveat: For security reasons, I can only access my client's VM via remote desktop, so I need to set an appointment with the IT group in order to explore and debug the problem. And, that is a 9 hour time difference and takes his valuable time. Thus, I need to re-create this problem on my AWS instance so that I can try to debug my code. And, when I say it introduces a CR instead of CRLF, then I might be remembering it wrong -- it could be that my code introduces a LF instead of … -
How to make a script to insert data in my default sqlite3 database django
I have defined my model and all in Django and if a user is registering via my application the user is well register in the database. The problem is I have a file containing a JSON with plenty of users. I want to do a job that allow me to read this file and insert all the user in my database. What is the best way to do it? How to connect to the Database without using Django? -
Django 1.10 and httpd.conf
According to Django 1.10 docs "Once you’ve got mod_wsgi installed and activated, edit your Apache server’s httpd.conf file", but httpd.conf is deprecated in Apache 2.4+. What is to edit? -
Can't get stylesheet to link properly with Django Framework (using localhost)
I'm trying to link it in the header of html file in the following path: main/home/templates/home/index.html And the style.css lives in main/main/stylesheet/style.css And this is my link in the index.html: <link rel="stylesheet" type="text/css" href="/main/stylesheet/style.css"> Is something wrong? -
Import error across entire Django project
I am getting strange error in Django when trying to run tests: [homebrewpython3] cchilders:~/projects/homebrew_app (CKC/finish-db-update-script) $ python manage.py test Creating test database for alias 'default'... EEEE ====================================================================== ERROR: homebrew_app.api (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: homebrew_app.api Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'homebrew_app.api' ====================================================================== ERROR: homebrew_app.calculations (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: homebrew_app.calculations Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'homebrew_app.calculations' ====================================================================== ERROR: homebrew_app.homebrew_app (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: homebrew_app.homebrew_app Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'homebrew_app.homebrew_app' ====================================================================== ERROR: homebrew_app.main (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: homebrew_app.main Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'homebrew_app.main' ---------------------------------------------------------------------- Ran 4 tests in 0.000s FAILED (errors=4) This is strange, because I'm able to run the server in python2 or 3: … -
How to use AWS Elastic Beanstalk Python with Nodejs?
These are the component used in my project Django, Angular and WebPack. So the problem is when deploying to Elastic Beanstalk I would like EB to able to compile Angular and SASS by using WebPack, but WebPack required NodeJS. Is there anyway I could use both Python and NodeJS in one EB Instance? Of course I could compile it on my local machine and deploy those to Live server, but I don't want to do that since I doesn't feel like the best practice. Thank for answering. -
Deployment error in OpenShift v3
I have successfully completed the Building of Django-OpenShift-v3 , but, the Deployment got some errors. --> Scaling django-psql-persistent-1 to 1 --> Waiting up to 10m0s for pods in deployment django-psql-persistent-1 to become ready error: update acceptor rejected django-psql-persistent-1: pods for deployment "django-psql-persistent-1" took longer than 600 seconds to become ready -
Django with Jquery Ajax
I'm trying to implement ajax method in django application. Here is the model what I've made class Blog(models.Model): name = models.CharField(max_length = 100) description = models.TextField() def __str__(self): return self.name Here is my view with data serialization def blogsdata(request): data = serializers.serialize("json", Blog.objects.all()) return HttpResponse(data) It works perfectly with this result [{"model": "blogs.blog", "pk": 1, "fields": {"name": "Hello", "description": "This is a text"}}, {"model": "blogs.blog", "pk": 2, "fields": {"name": "Django", "description": "Hello django"}}] But I do not disclose which model I'm working just want to show the fields data. How can I do that. -
How to put live video from web camera to Django website?
I have developed a face recognition software.It detects and identify human faces infront of the connected web camera.Now I need to deploy it in a website.so that,Anyone with a computer should be able to access this service through this website and should be able to perform face detection and identification using the camera in his premises. Is it possible to integrate python application with website? Is Django framework is suitable for my work? Can anybody recommed any tutorials in this direction? -
Django Multiple file uploader inline
So I'm developing an app with Django and I want to take the single file upload on my page to take multiple files, however I am vastly unaware of how to accomplish this task, I cant even find the form.html in the project and I am unfamiliar with python My current single file upload set up is VIEWS.py def job_document_log(request, job_id): job = get_object_or_404(Job, pk=job_id) if request.method == 'POST': form = SendDocLogForm(request.POST) if form.is_valid(): cd = form.cleaned_data subject = request.user.username + " has sent you an HTCPortal document log." msg = request.user.username + " has sent you an HTCPortal document log." if cd["message"]: msg += "\n\nThey said \""+cd["message"]+"\"." msg += "\n\nHere is a list of all files for the job \"" + job.name + "\":\n\n" for note in job.jobnotes_set.all(): pictures = note.additionalpicture_set.all() """ if note.notes: msg += "\n\nNote: "+note.notes+" by "+str(note.author)+"\n" elif pictures.exists(): msg += "\n\nNo note was given for the following files:\n" """ for f in pictures: msg += " * File uploaded on "+str(note.created.date())+": "+str(f.image)+"\n" print subject print msg print cd["email"] send_mail(subject, msg, 'noreply@htcflooring.com', [cd["email"]], fail_silently=False) messages.success(request, 'The document log for job "'+job.name+'" has successfully been sent to '+cd["email"]+'.') form = SendDocLogForm() else: form = SendDocLogForm() return render_to_response("job_document_log.html", … -
Why is the Response like this? what is wrong with my program ?
I am trying to create a login page and i am using the django as backend. authentication used is token-based. i have tried to POST the username and password which gives me a 405 http code error which is not the case i expected. and also it says that it is not expecting GET method which i dint do. it works the right way in https://www.hurl.it/ .i have posted the images and code here. Please help ! LoginPresenter.java subscription = RxUtil.io(restProvider.authenticate(userId, password)) .subscribe(new Subscriber<JsonObject>() { @Override public void onCompleted() { getMvpView().showProgress(false); } @Override public void onError(Throwable e) { Timber.e(e); getMvpView().showProgress(false); } @Override public void onNext(JsonObject jsonObject) { Timber.d(jsonObject.toString()); } }); RestProvider.java public interface RestProvider { @FormUrlEncoded @POST("/api-token-auth") Observable<JsonObject> authenticate(@Field("username") String user, @Field("password") String pass); } The interceptor log is POST http://mylink.com/mypath http/1.1 Content-Type: application/x-www-form-urlencoded Content-Length: 52 username=myusername&password=mypassword --> END POST (52-byte body) <-- 405 Method Not Allowed http://mylink.com/mypath (84ms) Date: Sat, 07 Jan 2017 04:36:48 GMT Server: Apache/2.4.18 (Ubuntu) Vary: Cookie X-Frame-Options: SAMEORIGIN Allow: POST, OPTIONS Keep-Alive: timeout=5, max=99 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/json {"detail":"Method \"GET\" not allowed."} <-- END HTTP (40-byte body) The backend is Django and i am using Token based authentication. It works in hurl.it perfectly. … -
nltk stemmer: string index out of range
I have a set of pickled text documents which I would like to stem using nltk's PorterStemmer. For reasons specific to my project, I would like to do the stemming inside of a django app view. However, when stemming the documents inside the django view, I receive an IndexError: string index out of range exception from PorterStemmer().stem() for the string 'oed'. As a result, running the following: # xkcd_project/search/views.py from nltk.stem.porter import PorterStemmer def get_results(request): s = PorterStemmer() s.stem('oed') return render(request, 'list.html') raises the mentioned error: Traceback (most recent call last): File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jkarimi91/Projects/xkcd_search/xkcd_project/search/views.py", line 15, in get_results s.stem('oed') File "//anaconda/envs/xkcd/lib/python2.7/site-packages/nltk/stem/porter.py", line 665, in stem stem = self._step1b(stem) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/nltk/stem/porter.py", line 376, in _step1b lambda stem: (self._measure(stem) == 1 and File "//anaconda/envs/xkcd/lib/python2.7/site-packages/nltk/stem/porter.py", line 258, in _apply_rule_list if suffix == '*d' and self._ends_double_consonant(word): File "//anaconda/envs/xkcd/lib/python2.7/site-packages/nltk/stem/porter.py", line 214, in _ends_double_consonant word[-1] == word[-2] and IndexError: string index out of range Now what is really odd is running the same stemmer on the same string outside django (be it a seperate python file or … -
How to filter a property in Django
I am currently having trouble with filtering data. This is my model class Member(models.Model): """Models for Member """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) team_id = models.UUIDField(null=True) username = models.CharField('', max_length=30) is_active = models.BooleanField(default=False) @property def organization_id(self): """This is to get the organization Id """ team = Team.objects.get(pk=self.team_id) return team.organization_id and now I am planning to filter all the members with the organation_id of 1 This is what I need memberList = Member.objects.filter(organization_id='1') So I got this error Cannot resolve keyword 'organization_id' into field. Choices are: id, is_active, team_id, username How can I filter the members using organization_id? -
Django Cache Issue During Production
I'm serving media files locally for production in a django application. I'm serving media files to a folder called media and nesting any uploaded images in a subfolder within media. This seems to be working fine. However, the cache that is in the same directory (media) as the subfolder does not receive images after they are uploaded. When I try to display images using their url, I'm given the cache url but there is no picture at the location. Any ideas as to why this is occurring? -
oDjango settings.py HOST databse section?
If I know the my IP address what should be the value for HOST in my Django settings.py database section? I am setting django in vps. -
Using Paginator() class in function-based view versus pagination in class-based listview (Django project)
Is using Django's Paginator() class in a function slower than implementing pagination via a class-based listview (i.e. including paginate_by in the class definition), given similar-sized dataset to be paginated? I think both are the same under the hood, but I asked because I recently shifted over from a listview to a function-based view (which renders the same template), and my server response time doubled. The only thing I really changed was using the Paginator() class to handle pagination in the function-based view. I find it highly confusing. Can anyone shed light on this? -
Django - value of form field as default value of another form field
I would like to fill my form field (url) and use that url as default value in my next form field (in another view). I am not able to switch views and take that form value. Any advices? Here are my files: views.py def subcategory(request, category_name_slug, subcategory_name_slug): context = {} form = SiteAddForm() context['form'] = form try: category = Category.objects.get(slug=category_name_slug) subcategory = SubCategory.objects.filter(category=category ).get(slug=subcategory_name_slug) sites = Site.objects.filter(subcategory=subcategory) context['subcategory'] = subcategory context['sites'] = sites except (SubCategory.DoesNotExist, Category.DoesNotExist): raise Http404("Nie ma takiej strony") if request.method == 'POST': form = SiteAddForm(request.POST) if form.is_valid(): siteurl = form.cleaned_data['url'] context['siteurl'] = siteurl return render(request, 'mainapp/add_site.html', context) return render(request, 'mainapp/subcategory.html', context) def add_site(request, category_name_slug, subcategory_name_slug): context = {} forms = SiteAddFormA() context['form'] = forms return render(request, 'mainapp/add_site.html', context) forms.py: from django import forms from mainapp.models import Site class SiteAddForm(forms.Form): url = forms.URLField(label='Url') class SiteAddFormA(forms.ModelForm): url = forms.URLField(max_length=200, help_text='Please enter the URL of the page.') class Meta: model = Site fields = ('url', 'name', 'description',) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'), url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/$', views.subcategory, name='subcategory'), url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/(?P<id>[\w\-]+)/$', views.site, name='site'), url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/add_site/$', views.add_site, name='add_site'), ] models.py: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'Subcategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=30) description = models.TextField() keywords = MyTextField() … -
Where is the django CMS history tab?
While editing pages in django CMS there is no history tab in the toolbar. Even on the django CMS official demo page there is no history tab in the toolbar. If this feature needs to be activated with some special setting, that setting is not in any documentation I could find. -
Dictionary In Django Model
I'm struggling with how to structure my models to allow me to capture some raw information that, once the instance is saved, I will no longer care about programmatically but will still want to save for posterity. Specifically, I need to capture a variety of data-points tied to specific days of the week, but really those are only useful in calculating the information I do care about (such as total hours, overtime, etc). While I could do this all in the Form/View I do want to save the raw data as I'll want to display it later (but wont need it for calculating anything). I could create a Day model and use a many-to-one relationship, but I'd like to not have to call query to db 7+ times every time I display or process a timesheet. Any thoughts would be greatly appreciated. class Timesheet(models.Model): #Begin Stuff I Care About employee = models.CharField() company = models.CharField() week_ending = models.DateField() total_hours = models.DecimalField() regular_hours = models.DecimalField() overtime_hours = models.DecimalField() doubletime_hours = models.DecimalField() #End stuff I care about #For Each Day of Week - Stuff I Will Not Care About time_in_monday = models.TimeField() lunch_out_monday = models.TimeField() lunch_in_monday = models.TimeField() time_out_monday = models.TimeField() total_monday … -
How to see app and geodata in django-admin pag and which tool use for see map(polygon) in django page?
any one tell me which tool I have to use to show my polygonfield data in django-admin page ? and how to see app in django-admin ? -
Why is my private user to user chat showing in other user's chat profile?
I'm creating a private user to user chat, I'm facing an issue where when a user send messages with another user, this same chat appear on the chat of other users. Let's say user A contacted user B, user C can not see the messages sent between users A & B, but users A & B can see their discussion on user C's chat profile who have nothing to do with them. Question : How can I make it so it only shows the chat when it has to do with the sender and the recipient ? The chat profile is shown at the url page like so : /c/<recipient username>/ As you can see the image below, everything is correct because the url username match the sender or recipient username. As you can see on this other image, the url username has nothing to do with the send or recipient username. Here is my template file : {% for user in users %} {% if user.client == request.user %} <li style="text-align:left; background:yellow;"> <p>from {{ user.client }} to <strong>{{ user.worker }} </strong> | {{ user.sent_at }}</p> <p>{{ user.comment }}</p> </li> {% else %} <li style="text-align:right; background:#eaeaea;"> <p>from {{ user.client }} … -
python manage.py collectstatic --noinput error when deploying Django project to Heroku
I've recently encountered a static files error when deploying my Django project again to Heroku. I've deployed the project to Heroku once already previously (without static files) and it worked. But recently, I altered the front-end and included some images and css files, and now I'm updating this project. My Project files are as follows: site1 - mynotes - settings.py - wsgi.py - mynotess - migrations - static - templates - users - migrations - templates - .gitignore.txt - manage.py - db.sqlite3 - Procfile - requirements.txt Just to clarify, mynotes is the main project directory. 'users' and 'mynotess' (double s) are apps. This is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w2!3r+pgqz6yhwi_+aw_!-yra7#h69z-n3-ni$gs2v+!!k^2$b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'mynotess', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mynotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': …