Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manifest.in file unable to load templates and staticfiles
my manifest file:- include LICENSE include README.rst recursive-include static * recursive-include Templates * recursive-include docs * after installing the app when i run the server it shows templates doesn't exists. -
How to show field from another table using django orm?
i have a problem to show fields from another table,where two tables have relationsips this is my first models class DataPribadiSiswa(models.Model): SiswaID = models.AutoField(primary_key=True) WaliKelasID = models.CharField(max_length=11, blank=True, null=True) my second models class transaksi_kas(models.Model): id_kas = models.AutoField(primary_key=True) siswaID_trans = models.ForeignKey(DataPribadiSiswa, null=True, blank=True) kelas = models.CharField(max_length=1, null=True, blank=True) and this is my views.py def transaksi_index(request): transaksi = {} transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans') return render(request, 'kastransaksi/transaksi_index.html', transaksi) this is my template <table id="simple-table" class="table table-striped table-bordered table-hover"> <tr> <th>No.</th> <th>Nama</th> <th>Wali Murid</th> <th>Kelas</th> </tr> {% for kas in transaksikas%} <tr> <td>{{ forloop.counter }}</td> <th>{{ kas.siswaID_trans }}</th> <td>{{ kas.WaliKelasID }}</td> <td>{{ kas.kelas }}</td> </tr> {% endfor %} </table> I want to show {{ kas.WaliKelasID }} from DataPribadiSiswa, but it can't, how to resolve it? -
Django manytomany querying showing none and/or unsucessful
I am having trouble querying a list of items in a many to many relationship. The model I am trying to query is below. This is a model that will indicate a worker selecting an "opening" and many workers can select the same "opening". I am trying to select the list of workers that have selected an "opening" but I am not successful. class FavOpening(models.Model): opening = models.OneToOneField(Openings, blank=True, default=None) worker = models.ManyToManyField(Worker, blank=True, default=None) def __unicode__(self): return str(self.opening) It is very strange because I tried this below for the type of opening based on a chosen worker(id-31) and it works, the opening that the worker has selected will print. employee = get_object_or_404(Worker, id=31) print employee.favopening_set.all() But when I do it the other way round to get the worker inside the manytomany using the below, it does not work. Says it does not have attribute "favopening_set" openingobj = get_object_or_404(Openings, id=1) print openingobj.favopening_set.all() I also tried to do the below to get the list of workers based on the opening(id=1) but I am getting no result - showing Workers.Worker.None, which is not true because I have at least one worker the have selected this opening.(I checked in admin) openingobj = get_object_or_404(Openings, … -
pre-populating partial Initial data in a Django formset
I’m having difficulty implementing initial data in my django formset. For context, I’m building an attendance app where a list of students exist and need to be assessed for attendance every day. What I’m trying to do is have an administrator click on a link which has a date listed on it. They will then be taken to data grid where each row represents the number of students in the system along with 4 columns (student name, date, present/absent drop down, a notes field). The goal is to have the student name field be pre-populated with the the list of students in the Student model, the date field be pre-populated with the date on the link the user clicked and the attendance and notes fields be user inputs. Any help would be much appreciated Thanks! — Student model class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) GENDER_CHOICES = ( ('male', 'male'), ('female', 'female'), ) gender = models.CharField(max_length=12, choices=GENDER_CHOICES, null=False, blank=False) date_of_birth = models.DateField(auto_now=False, auto_now_add=False) @property def full_name(self): return ''.join([self.first_name, '_', self.last_name]) def __unicode__(self): return self.full_name Attendance model class Attendance(models.Model): student = models.ForeignKey('students.Student') attendance_date = models.DateField(auto_now=False, auto_now_add=False) STATUS_CHOICES = ( ('present', ‘1’), ('absent', ‘0’), ) status = models.CharField(max_length=12, choices=STATUS_CHOICES, null=False, blank=False) … -
Django form instance error
I'm trying to build a simple form in Django. I have on my forms.py file: from django import forms class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required=False) messgae = forms.CharField() When I try to create an instance of the form on the shell f = ContactForm() I get an error message: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Heirarchy Trees from Objects.all() with Generic Views in Django
I'm working on a blog using Django. I'm using Generic Views ie. from django.views.generic import dates from django.views.generic.list import ListView These are working fine but I also wanted to implement a searchable, collapsable tree in the blog which covers all entries as another navigable tool. ie. 2016 Dec 01 - Entry 1 03 - Entry 2 Mar 23 - Entry 3 2015 Nov 01 - Entry 4 etc. I'm currently doing this by using regroup and CSS inside an HTML template that I'm including into each HTML template used by each generic view: {% block sidebar %} {% include '../blog_archive_tree.html' %} {% endblock %} My problem is that now I need to sub-class each generic view so that I can pass the queryset Objects.all() to the template to create the tree, which feels like I'm losing out on the benefits of using Generic classes. From this in urls.py: from django.views.generic.list import ListView from coltrane.models import Category urlpatterns = [ url(r'^$', ListView.as_view(model=Category), ] to this: from coltrane.models import Category from coltrane.models import Entry class ArticleCategoryListView(ListView): model = Category def get_context_data(self, **kwargs): context = super(ArticleCategoryListView, self).get_context_data(**kwargs) context['for_tree_view'] = Entry.objects.all() return context urlpatterns = [ url( r'^$', ArticleCategoryListView.as_view(), name='coltrane_category_list'), ) I've got about … -
I am trying to write python code in my template html file on a django project, but PyCharm does not recognize it?
I am making a template file in my web django project but PyCharm does not recognize the python code in my template html file. I am using PyCharm community with the latest update. Could this be an issue of the fact that the community version does not support Django directly? Or maybe some other problem. The syntax I am using for the python in the html is {% %} {% if all_albums %} <ul> {% for album in all_albums %} <li> <a href="/music/{{ album.id }}/">{{ album.album_title }}</a> </li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} but the ide is not recognizing it as python code and it stays gray. -
how to get the next random element knowing the previous one
I have a a fixed list of objects (almost it is actually coming from a db) and i want to be able to pick one element at a time and never pick one that was seen previously before doing the all set of elements Any idea how to do that ? it is related to getting a randint(0, N) but knowing the last pick . Can i force the seed maybe ? -
Django: same static files are uploaded everytime I run collectstatic
I use django-pipeline, AWS S3 for managing static files of my Django application. Since django-pipeline has compressor, it generate compressed version of staticfiles like this: cart.js => cart.1daf2tgser.js Whenever I release my new version of project in production server and call collectstatic command, this compressed version of static files are newly uploaded in S3 like this: I tried installing Collectfast, it doesn't work either. How can I keep only recent static files? Thanks. -
Why doesn't the following jquery code close the form after successful submission?
I am trying to close the form but the following code doesn't close the form after I clicks on submit button. Although I can see the alert message appearing which means control is goes in success: label but the form doesn't close what could be wrong ?? please help. html code <div id="signupmodal" class="modal fade" role="dialog of sign up"> <div class="modal-dialog"> <!-- Modal content--> <form id="new_user_form"> {% csrf_token %} <div class="modal-content" data-method="post" id="modalform" > <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Sign Up</h4> </div> <div class="modal-body"> <div class="form-group" > <label for="usr">Username:</label> <input type="text" name="username" class="form-control input-sm" id="username"> <label for="eml">Email:</label> <input type="email" name="emil" class="form-control input-sm" id="emailid"> <label for="passwordd">Password:</label> <input type="password" name="password" class="form-control input-sm" id="password"> </div role="Form group"> </div role="modal-dialog"> <!--Closing Of Sign Up Modal Page --> <div class="modal-footer"> <button type="submit" class="btn btn-default" id="submit">Submit</button> <button type="button" class="btn btn-default" id="close" data-dismiss="modal">Close</button> </div role="modal-footer"> </div role="modal content"> <!--</form>--> </div role="modal-dialog"> </div role="dialog of signup"> <!--Closing of sign up modal --> </form> <script src="/static/bootstrap 3/jquery/jquery.form.js/"> </script> jquery code : <script> $(document).on('submit','#new_user_form',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/librarysystem/registered/", data: { username: $('#username').val(), emailid: $('#emailid').val(), password: $('#password').val(), csrfmiddlewaretoken:$ ('input[name=csrfmiddlewaretoken]').val () }, success: function(){ alert("Registeration successfully.") $('#new_user_form').modal('hide'); } }); }); </script> -
django bootstrap dropdown not working
I am building website based in django. I am using bootstrap dropdown in navbar to collapse navbar on low resolution i.e. mobile view, but on clicking button navbar not getting dropdown. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <nav id="main-menu" class="navbar" role="navigation"> <div class="navbar-header"> <button type="button" class="btn btn-navbar navbar-toggle" data-toggle="collapse" data-target=".navbar-cat-collapse"> <span class="sr-only">Toggle Navigation</span> <i class="fa fa-bars"></i> </button> </div> <div class="collapse navbar-collapse navbar-cat-collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'home_page' %}">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Pages</a></li> <li><a href="{% url 'contact_page' %}">Contact Us</a></li> </ul> </div> </nav> -
'NOT NULL constraint failed' even with 'null=True'
I see that error: NOT NULL constraint failed: blog_post.category_id Here is the code: class Post(models.Model): class Meta: verbose_name='Запись' verbose_name_plural='Записи' author = models.ForeignKey('auth.User') category = models.ForeignKey('Theme', default=None, blank=True, null=True) title = models.CharField(max_length=200,verbose_name='Заголовок') text = RichTextField(verbose_name='Текст') created_date = models.DateTimeField(verbose_name='Время создания',default=timezone.now) published_date = models.DateTimeField(verbose_name='Время публикации',blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approved_commentimages(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title class Theme(models.Model): class Meta: verbose_name='Категория' verbose_name_plural='Категории' title = models.CharField(verbose_name='Заголовок', max_length=40) slug = models.SlugField(verbose_name='Транслит', null=True) def __str__(self): return self.title What am i do wrong? -
Could Django-channels co-exists with celery
If I make up a site with Django-channels(nginx + channels, I like its websocket ability), Could I still adding in some celery app/tasks run at background as other normal django project? -
Using payslip app in my Django Project
This question is specific to importing Django-payslip app in my project. I am a beginner in Django and have to use this app for my project, but am not sure how will I be able to import this app. If anyone can guide me through, from scratch, it will be helpful. Link to django-payslip app: https://pypi.python.org/pypi/django-payslip Thanks! -
Django 404 error polls:detail not found?
I'm learning Django through django's official docs but when i completed 4th tutorial in making polls app.I didn't get correct result it gives an below error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/(%25%20url%20'polls:detail'%20question.id%20%25) Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^$ [name='index'] ^polls/ ^(?P<pk>[0-9]+)$ [name='detail'] ^polls/ ^(?P<pk>[0-9]+)/results/$ [name='results'] ^polls/ ^(?P<question_id>[0-9]+)/vote/$ [name='vote'] ^admin/ The current URL, polls/(% url 'polls:detail' question.id %), didn't match any of these. My Project directory is C:\Users\Krt_zox\mysite My urls.py (C:\Users\Krt_zox\mysite\polls) from django.conf.urls import url from . import views app_name ='polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'), url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'), ] My index.py (C:\Users\Krt_zox\mysite\polls\templates\polls) {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} My views.py (C:\Users\Krt_zox\mysite\polls) from django.shortcuts import get_object_or_404,render from django.http import HttpResponseRedirect from .models import Question,Choice from django.urls import reverse from django.views import generic # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name … -
Form Validation Error when a required field is remained blank in django
I want to have errors as a label above a field if it is not filled. This is my views.py: @login_required(login_url='user_profile:login') def NewWriting(request): if request.method=="POST": form=WritingForm(request.POST) if form.is_valid(): post=form.save(commit=False) post.author=request.user post.save() return redirect('user_profile:index') else: form = WritingForm() subject = Subject.objects.all() return render(request,'user_profile/writing_form.html', {'form':form , 'subject':subject}) what should I add to my code? Thanks -
High response time when setting value for Django settings module inside a middleware
In a Django project of mine, I've written a middleware that performs an operation for every app user. I've noticed that the response time balloons up if I write the following at the start of the middleware module: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings") It's about 10 times less if I omit these lines. Being a beginner, I'm trying to clarify why there's such a large differential between the respective response times. Can an expert explain it? p.s. I already know why I shouldn't modify the environment variable for Django settings inside a middleware, so don't worry about that. -
Django Celery task on Heroku causes high memory usage
I have a celery task on Heroku that connects to an external API and retrieves some data, stores in the database and repeats several hundred times. Very quickly (after ~10 loops) Heroku starts warning about high memory usage. Any ideas? tasks.py @app.task def retrieve_details(): for p in PObj.objects.filter(some_condition=True): p.fetch() models.py def fetch(self): v_data = self.service.getV(**dict( Number=self.v.number )) response = self.map_response(v_data) for key in ["some_key","some_other_key",]: setattr(self.v, key, response.get(key)) self.v.save() Heroky logs 2017-01-01 10:26:25.634 132 <45>1 2017-01-01T10:26:25.457411+00:00 heroku run.5891 - - Error R14 (Memory quota exceeded) Go to the log: https://api.heroku.com/myapps/xxx@heroku.com/addons/logentries You are receiving this email because your Logentries alarm "Memory quota exceeded" has been triggered. In context: 2017-01-01 10:26:25.568 131 <45>1 2017-01-01T10:26:25.457354+00:00 heroku run.5891 - - Process running mem=595M(116.2%) 2017-01-01 10:26:25.634 132 <45>1 2017-01-01T10:26:25.457411+00:00 heroku run.5891 - - Error R14 (Memory quota exceeded) -
How to make validation between conditional lists in python?
I have 3 initialized lists : list_1 = [1,2] list_2 = [2,1] list_3 = [1,2,3] Note ---> numbers inside [] are the ids from Django Model I want to make validation that if numbers in list_1 are there in list_2 then return True, but if i do validation between list_2 and list_3, or between list_1 and list_3, then the result will be False. How to do that guys? Thanks :D -
django codemirror get code from editor
Below is my code for code editor {% load static %} <script src="{% static 'codemirror.js' %}"></script> <link rel="stylesheet" href="{% static 'codemirror.css' %}"> <script src="{% static 'clike.js' %}"></script> <script> var myCodeMirror = CodeMirror(document.getElementById('text_area'), { value: "int main()", mode: "text/x-c++src", lineNumbers: true, indentUnit: 4, }); </script> How do i get the code after submit button from post method? Note: I m using CodeMirror library from github -
Gunicorn sock not found, connection failed with Nginx
I've been battling with setting up Gunicorn, nginx for my django app. After following the tutorial here and the one here Nginx could not find trav.sock. My problem is this, Gunicorn failed to create the trav.sock. Why I said this is that when I tried Uwsgi following this tutorial my trav.sock was created after running the below command sudo uwsgi restart Why I decided to use Gunicorn is a story for another day :) Back to Gunicorn, my nginx error log is saying: [crit] 7459#7459: *1 connect() to unix:/var/www/example.com/src/run/trav.sock failed (2: No such file or directory) while connecting to upstream I have created the /run/ directory and sudo chown with the same user and group I used for gunicorn config. Gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=kipman Group=sudo WorkingDirectory=/var/www/example.com/src ExecStart=/var/www/example.com/travenv/bin/gunicorn --workers 3 --bind unix:/var/www/example.com/src/run/trav.sock trav.wsgi:application [Install] WantedBy=multi-user.target Nginx conf upstream kip_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Gunicorn master nukes a # single worker for timing out). server unix:/var/www/example.com/src/run/trav.sock fail_timeout=0; } server { listen 80; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } access_log /var/www/example.com/logs/access.log; error_log /var/www/example.com/logs/nerror.log; charset utf-8; … -
<function details at 0x7f440740dd70>
Am a a bit new to python and django programming, can someone help me understand what's happening here Am creating a small polls app and this is what i have In my template details.html <table> <tr><td><a href="/polls/{{ que.id }}/up"><i class="fa fa-chevron-up"></i> </a></td></tr> <tr><td><a href="/polls/{{ que.id }}/up"><i class="fa fa-chevron-down"></i></a></td></tr> </table> That url maps to this in my urls.py file from django.conf.urls import url from .import views urlpatterns=[ url(r'(?P<question_id>[a-z0-9A-Z]+)/(?P<method>[a-z]+)/$', views.like') Then this is my views.py def like(request, question_id, method): #get the question question = Questions.objects(id=question_id).get() #get the method type if method == 'up': question.likes + 1 elif method == 'down': question.likes - 1 else: #handle the other invalid methods But on clicking the link i get this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/586748a8d6ca3f1b30ee4ff9/up/%3Cfunction%20details%20at%200x7f440740dd70%3E Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: 1. ^admin/ 2. ^polls/ ^(?P<question_id>[a-z0-9A-Z]+)/(?P<method>[a-z]+)/$ The current URL, polls/586748a8d6ca3f1b30ee4ff9/up/<function details at 0x7f440740dd70>, didn't match any of these. So what's this function thing. Any help is appreciated! -
How to subtract two datetime variable in django
now = datetime.today() for item in itemList: elapsed = item.endDate if elapsed - now > 1: item.overdue = 1 elif now - now > 3: item.banned = 1 can't subtract offset-naive and offset-aware datetimes -
When starting a new django project via django-admin.py is there a way to inject my own variables?
When starting a new Django project via django-admin.py is there a way to inject my own variables? I'd like to use {{ <my_var_name }} so that the project is automatically setup for me. Thanks for the help! Casey -
How to get a Django signal on password change
When a user changes their password, I want to send a signal so that I can do some stuff on some models. How can I create this signal? I've looked at the post_save signal for User: post_save.connect(user_updated, sender=User) However, there doesn't seem to be anything in there for me to check if the password was changed: def user_updated(sender, **kwargs): print(kwargs) # {'created': False, 'raw': False, 'instance': <User: 100002>, 'update_fields': None, 'signal': <django.db.models.signals.ModelSignal object at 0x7ff8862f03c8>, 'using': 'default'} Any ideas?