Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms with ajax, what would be the best approach?
I am building a plataform inspired on LinkedIn design. I have my pagination made with ajax, when the user scrolls down the page load texts and information which I want them to be editable. The user will be seeing his information, but when he hovers the info he will see an edit icon, if he clicks all that information becomes an editable form. What would be the best approach for building it? Do you suggest using some form library? Until now I am using django built in forms. Thanks -
Database Connect Error: Centos 6 / Apache 2.4 / Postgres 9.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7
I am trying to get my website up and running. Everything seems to work fine, but when I go to a page with a database write - I get this: [Wed Oct 19 09:53:12.319824 2016] [mpm_prefork:notice] [pid 12411] AH00173: SIGHUP received. Attempting to restart [Wed Oct 19 09:53:13.001121 2016] [ssl:warn] [pid 12411] AH01909: sXXX-XXX-XXX-XXX.secureserver.net:443:0 server certificate does NOT include an ID which matches the server name [Wed Oct 19 09:53:13.003578 2016] [mpm_prefork:notice] [pid 12411] AH00163: Apache/2.4.18 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 mod_wsgi/3.5 Python/2.7.6 configured -- resuming normal operations [Wed Oct 19 09:53:13.003590 2016] [core:notice] [pid 12411] AH00094: Command line: '/usr/local/apache/bin/httpd' (XID fsf92m) Database Connect Error: Access denied for user 'leechprotect'@'localhost' (using password: YES) [Wed Oct 19 09:53:17.637487 2016] [mpm_prefork:notice] [pid 12411] AH00169: caught SIGTERM, shutting down This line shows that a user "leechprotest" cannot connect: (XID fsf92m) Database Connect Error: Access denied for user 'leechprotect'@'localhost' (using password: YES) However I don't have a user called leechprotect. leechportect is a default user on MySQL (im guessing), because MySQL is installed as the default database on my dedicated server. My Django settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'prelaunch_db', 'USER': 'postgres_user', 'PASSWORD': 'XXXXXXXXXXXXXXX', 'HOST': 'localhost', 'PORT': '', } } I already … -
Set value to page Django
Hi everyone what is the best way to solvent this problem... I create a app in my django CMS, I create a AppHook with this app, and now I can choose in multiples pages. I need to use in two different page, en my app looks like this... The select have two options, depends that the option that I choose,show one thing or other thing. when I click in update bottom I call a URL, the problem is that this URL is different for each page and option so page1 has option1 => url1 option2 => url2 page2 option1 => url3 Option2 => url4 I think the solution is, I have to associate each link with each page. But what is the best way to do that... 1.- It is posible when I associate the app to page create a text input to set the value of URL. 2.- Or extending the page and create a text input there to set the value. In this case is posible show this new text input for only this 2 page that needed. 3.- Management the app from admin, and associates a page with the URL. 4.- Other option... -
Angular ui-router state inherit Django staticfile reference?
In the process of transitioning html content to ui-router states I encountered a problem with how ui-view loads its content, specifically ng-src attributes that load images from Django staticfiles. Here's what normally works with angular and Django <!-- main index.html registered as view and url --> {% load staticfiles %} <body> <img ng-src="{% static 'img/apple.png' %}"> <!-- after load --> <img src="/static/img/apple.png"> </body> Here's what goes wrong <!-- loads first --> {% load staticfiles %} <body> <ui-view> <!-- loads second from state--> <img ng-src="{% static 'img/apple.png' %}"> <!-- after load --> <img src="{% static 'img/apple.png' %}"> <!-- stays as string --> </ui-view> </body> Because each state is loaded in separately the {% static '' %} tags will stay as strings. One solution is to register the state partials as views with urls but that requires taking them out of the static file directory and placing them into normal Django templates directory. Ui-router then has a problem with loading states as they do not exist as static html. Is there a way to have ui-view inherit {% load staticfiles %}? Or is it reasonable to forgo using {% static '' %} tags and just use: {% load staticfiles %} <!-- for … -
Django CheckboxSelectMultiple not rendering as list
I have a field courses which needs to be rendered as list( CheckboxSelectMultiple renders items as list)- courses = forms.ModelMultipleChoiceField( queryset=Course.objects.all().order_by('name'), widget=forms.CheckboxSelectMultiple(), required=False, ) From Django docs:- CheckboxSelectMultiple¶ class CheckboxSelectMultiple[source]¶ Similar to SelectMultiple, but rendered as a list of check buttons: <ul> <li><input type='checkbox' name='...' ></li> ... </ul> but when my form(im using crispy forms) its not being rendered as a unordered list, instead as labels -
Django error when passing parameter to ModelForm
I'm trying to pass a parameter to a form, in this case is an object_id. The form gets used only on the change_view, this code works: My admin model: class MyModelAdmin(admin.ModelAdmin): def change_view(self, request, obj_id): self.form = MyForm return super(MyModelAdmin, self).change_view(request, obj_id) def add_view(self, request): self.exclude = ('thig_to_exclude',) return super(MyModelAdmin, self).add_view(request) My form: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.my_id = kwargs.pop('my_id', None) super(MyForm, self).__init__(*args, **kwargs) class Meta: model = MyModel fields = ('thing_to_show_a',) But when I do: class MyModelAdmin(admin.ModelAdmin): def change_view(self, request, obj_id): self.form = MyForm(my_id=obj_id) return super(MyModelAdmin, self).change_view(request, obj_id) ... I get: 'MyForm' object has no attribute '__name__' -
How to show recent blog posts on homepage with Django?
I would like to show the 2 most recently uploaded posts on my homepage. How would I do this? Heres my code so far: homepage views.py: from django.shortcuts import render from blog.models import Post from django.views.generic import ListView, DetailView # Create your views here. def index(request): posts = ListView.as_view(queryset=Post.objects.all().order_by("-date"))[0:3] return render(request, "home/info.html") homepage url.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name="index"), ] blog models.py from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__ (self): return self.title If you need anymore code from me just ask and ill edit the OP. -
Gunicorn only giving 400 through socket
Hi I am using gunicorn to host a django app. The command I am using to run gunicorn is /usr/local/bin/gunicorn --workers 5 --bind unix:/home/myuser/myapp/myapp.sock myapp.wsgi:application When I try to ping it with command curl --unix-socket /home/myuser/myapp/myapp.sock http:localhost/api I get 400 errors. But if I run the same gunicorn command with a bind address of /usr/local/bin/gunicorn --workers 5 --bind 127.0.0.1:8000 myapp.wsgi:application And then curl the same address I get a 200 and the response I am looking for. Does anyone know what I am doing wrong with the gunicorn socket implementation? -
Specifying a custom template for the django-lazysignup convert view
In my urls.py I tried to pass the template_name argument to the convert view: url(r'^convert/', include('lazysignup.urls'), {'template_name': 'chat/templates/chat/sign_up.html'}, name='convert') That does not seem to have changed anything. Do I need to make a new view to call the convert view? -
Django: authenticate the user
I have the following code: # creating user: def create_user(request): if request.method == 'POST': user_info = forms.UserInfoForm(request.POST) if user_info.is_valid(): cleaned_info = user_info.cleaned_data User.objects.create_user(username=cleaned_info['username'], password=cleaned_info['password']) render(.......) This works. I can check the auth_user and I see the username and password along with all the other fields created and added. Now, I try to authenticate the user with the following code after creating user with username='testcase' and password='test': using above code. # Authenticate User def get_entry(request): if request.method == 'POST': user = authenticate(username='testcase', password='test') if user: ......... The user is always returned as none. What is going on? I am running django 1.10.2. -
How to expose user passwords in the most "secure" way in django?
I am working on Django 1.9 project and I have been asked to enable some users to print a page with a list of a set of users and their passwords. Of course passwords are encrypted and there is no out-of-the-box ways of doing this. I know this would imply a security breach so my question is kind of contradictory, but is there any logical way of doing this that doesn't imply a huge security breach in the software? -
Django: Change Choice selection from FK in a Form linked to an UpdateView
The Model flow Topic -> Section -> Article. I am building an Update View for my FAQ project to update already created Articles. I want the Form to provide a selection of Sections based on the Topic the Article was created under. As I already have the Articles PK passed in through the URL I was hoping to use it to walk back up to the Topic when creating my filter. I am receiving an object has no attribute ‘section’ error when the template is attempting to render the form on line self.fields['section'].queryset = Article.objects.filter(section__topic_id=self.section.topic.pk) in the UpdateAriticleForm. I need help to figure out my query filter. The URL: url(r'^ironfaq/article/update/(?P<pk>\d+)/$', ArticleUpdateView.as_view()), The Form: from django import forms from .models import Topic, Section, Article class CreateArticleForm(forms.ModelForm): section = forms.ModelChoiceField(queryset=Section.objects.none()) def __init__(self, *args, **kwargs): topic_pk = kwargs.pop('topic_pk') super(CreateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.filter(topic_id=topic_pk) class Meta: model = Article widgets = { 'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}), } fields = ('title','section','answer') class UpdateArticleForm(forms.ModelForm): section = forms.ModelChoiceField(queryset=Article.objects.none()) def __init__(self, *args, **kwargs): super(UpdateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Article.objects.filter(section__topic_id=self.section.topic.pk) class Meta: model = Article widgets = { 'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}), } fields = ('title','section','answer') The View: class ArticleUpdateView(UpdateView): model = Article form_class = UpdateArticleForm … -
python django - invalid file path? Type Error cannot concatenate 'str' and 'instancemethod' objects
I'm getting the: Type Error: Cannot concatenate 'str' and 'instancemethod' objects at the line where I have the code: csvFilePath = settings.MEDIA_ROOT + 'csv/' + doc.filename + '.csv' I simply wanted to have a file to open and create by setting the csvFilePath using MEDIA_ROOT path. Is my code even valid? My file uploads are correctly being sent there so would the method that I'm trying to do invalid? Is there another way for me to set the file path where I want to send it? -
Django – remove trailing zeroes for a Decimal in a template
Is there a way to remove trailing zeros from a Decimal field in a django template? This is what I have: 0.0002559000 and this is what I need: 0.0002559. There are answers suggesting to do this using floatformat filter: {{ balance.bitcoins|floatformat:3 }} However, floatformat performs rounding (either down or up), which is unwanted in my case, as I only need to remove trailing zeros without any rounding at all. -
Directive duplicating entire dom with Django
I'm trying to use a angular directive inline within my django application, but whenever I do, rather than just injecting the directive's template, it is including the entire dom. If I try to do this in a JS fiddle without django, it works correctly as seen here. But the exact same code included with django inheritance will include the whole dom as shown in this image: What could the inclusion of Django possibly have to do with this since Django's server side magic wouldn't ever make a difference to the html output that angular gets to work with? What do I need to do to stop the whole dom from being rendered whenever calling the template, and instead just rendering the template? I'd imagine this might be avoidable by having the directive in a separate template file but that isn't an option currently and I'd like to understand why its failing. base.html <!DOCTYPE html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> {% block head %}{% endblock %} </head> <body ng-app="MyApp"> <div ng-controller="MyController">{% block body %}{% endblock %}</div> </body> </html> template {% extends 'base.html' %} {% block head %} <script> var SearchTerms = angular.module("MyApp", []); SearchTerms.controller("MyController", ["$scope", function($scope) {}]); SearchTerms.directive('modelSearch', function(){ return { … -
Create a select in template from list
Hi everyone I have this in my template {% with 'By Visit, By Patient' as list %} <div class="selector_healthApp"> <div class="container"> <div class="row"> <div class="col-xs-3"> <label for="sel1">Select Categoty:</label> <select class="form-control" id="item_project"> {% for cat_name in list.split %} <option>{{ cat_name }}</option> {% endfor %} </select> </div> </div> </div> </div> {% endwith %} {% endblock content %} I have a list and I want to show each item of list in a select if I used {% for cat_name in list.split %} I have 4 element in the select By Visit By Patient id I use {% for cat_name in list %} it is separate by characters How to do this to show in the select 'By Visit' and 'By Patient' Why if I try in the terminal this works list = [By Visit, By Patient] >>> for iten in list: ... print iten ... By Visit By Patient >>> Thanks in advances -
reverse for view fails because argument is None
Ok once again im a noobie at django and i have a tables.py and imported django-tables2 class CarownerTable(tables.Table): .... Car_registration=tables.LinkColumn('register_docs', args =[A('register__id')],text='View Register', orderable=False) and two url for it as url(r'^register_docs/$', views.register_docs, name='register_docs' ), url(r'^register_docs/(?P<docid>(\d)+)$', views.register_docs, name='register_docs' ), and the view as def register_docs(request, docid=None): #This view allows for the display of the pdf file if docid is None: #this line here loads a default image doclink = '........./Car/Misc/noImageOnFile.pdf' return HttpResponse(doclink, content_type="application/pdf") else: register_doc_path = Register.objects.get(pk=docid).register_File_Path register_doc_data = open(register_doc_path, "rb").read() t = loader.get_template('carmanager/display_docs.html') variables = RequestContext(request, {'file':register_doc_data}) output = t.render(variables) return HttpResponse(register_doc_data, content_type="application/pdf") the issue is that when i load results some of the objects don't have a document attached to it. causing this Reverse for 'register_docs' with arguments '(None,)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['carmanager/register_docs/(?P<docid>(\\d)+)$', 'carmanager/register_docs$'] i tried and create two url one that accepts an arguement and one that doesnt but it still wont allow the table to load with those who dont have. i want both to load even though a car registration document cant load -
Django: create database tables programmatically/dynamically
I've been working on a Django app for some time now and have encountered a need for dynamic model and database table generation. I've searched far and wide and it seems as though the Django API does not include this function. From what I have gathered, South has a function to do this (i.e. south.db.create_table). However, from what I have gathered from South's release notes, South is not compatible with Django 1.7 and higher and my project was built using Django 1.9. I have already written a script that creates model instances of the schema I would like to migrate to my database using the following method: attrs = {'__module__':model_location, 'Meta':Meta} model = type(table_name, (models.Model,), attrs) p.s. please note that this is not the entirety of the mentioned script. If you think this would be useful for me to provide I can add it upon request. Has anyone found a workaround for using South 1.0.2 with Django 1.9? If not does anyone have any ideas on how I could achieve this functionality without South? I have tried to think of alternative methods (rather than dynamically generating tables) but this really seems like it would provide the most concise and clean … -
TypeError: __init__() got an unexpected keyword argument 'current_app' Django
I just uploaded my app into a production server (Centos7) with migrations via Gitlab and everything works fine, the problem here is that once I want to access through the browser I get this error on my logs: File "/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 49, in render context_instance = RequestContext(request, current_app=current_app) TypeError: __init__() got an unexpected keyword argument 'current_app' The weird thing is that everything works properly in my local machine and I can run it without any issue, the only difference in the server side is that I run the server with production-settings (with a configuration for a production server) Hint: if I run funtions through url, everything runs properly seems the problem is that every time it goes into the "return render" I get that message too. Thanks for your attention, -
How to link post to user?
I have a foreign key to User in my Post model, which is meant to give each post an Author attribute. I have tested this using two dummy accounts. For example, when account B writes a post, his name will be displayed in the author field. This works fine when B is logged in. However, when I logout B and login A, the article which was written by B is now attributed to A. How do I fix this, so that the author field is actually dependent on the author of the post, and not whichever user is currently logged in? -
Django says there are no changes to be made when I migrate
I'm attempted to create a database for a fictional school. Unfortunatley when I try to migrate the tables this happens: C:\Python34\Scripts\schoolDatabase>manage.py makemigrations school C:\Python34\Scripts\schoolDatabase>python manage.py makemigrations school No changes detected in app 'school' This is the model I am referring to: TYPE_OF_PERSON = ( ('T', 'Teacher'), ('S', 'Student'),) DETENTION_COMPLETED = ( ('Y', 'Yes'), 'N', 'No' OUTCOME = ( ('P', 'Pass'), ('F', 'Fail') ) class Person: first_name = models.CharField(max_length = 25) surname = models.CharField(max_length = 25) address = models.CharField(max_length = 45) year_group = models.CharField(max_length = 10) form = models.CharField(max_length = 15) type_of_person = models.CharField(choices = TYPE_OF_PERSON) person_id = models.CharField(primary_key = True) class Subject: name = models.CharField(max_length = 25) class SchoolClass: class_id = models.IntegerField(primary_key = True) person_id = models.ForeignKey('Person') subject = models.ForeignKey('Subject') year_group = models.ForeignKey('Person') class Attendance: school_class = models.ForeignKey('SchoolClass') date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() person_id = models.ForeignKey('Person') class Assignment: assignment_id = models.IntegerField(primary_key = True) subject = models.ForeignKey('Subject') school_class = models.ForeignKey('SchoolClass') teacher = models.ForeignKey('Person') description =models.TextField() date_set = models.DateField() due_date = models.DateField() mark = models.CharField(max_length = 20) comments = models.TextField() class Detention: detention_date = models.DateField() student_id = models.ForeignKey('Person') reason = models.CharField(max_length = 30) completed = models.CharField(choices = DETENTION_COMPLETED) class Exam: exam_id = models.IntegerField(primary_key = True) subject = models.ForeignKey('Subject') … -
Metaclass inheritance in Python 2 and Python 3
I have following sample code for Python 2.7: class MetaA(type): def __new__(cls, name, bases, attrs): print('MetaA::__new__') print('CLS:' + str(cls)) print('Name:' + name) print('============================') return super(MetaA, cls).__new__(cls, name, bases, attrs) class A(object): __metaclass__ = MetaA class MetaB(type(A)): pass class SomeMixin(A): pass class B(A): __metaclass__ = MetaB class C(SomeMixin, B): pass After executing it I have such output: MetaA::__new__ CLS:<class '__main__.MetaA'> Name:A ============================ MetaA::__new__ CLS:<class '__main__.MetaA'> Name:SomeMixin ============================ MetaA::__new__ CLS:<class '__main__.MetaB'> Name:B ============================ MetaA::__new__ CLS:<class '__main__.MetaA'> Name:C ============================ MetaA::__new__ CLS:<class '__main__.MetaB'> Name:C ============================ The thing is when class C defined, at first method __new__ is invoked for metaclass MetaA (base one) and then for metaclass MetaB invoked. If I change the order of mixin and inherit class in my class C like this class C(B, SomeMixin): the output is following: MetaA::__new__ CLS:<class '__main__.MetaA'> Name:A ============================ MetaA::__new__ CLS:<class '__main__.MetaA'> Name:SomeMixin ============================ MetaA::__new__ CLS:<class '__main__.MetaB'> Name:B ============================ MetaA::__new__ CLS:<class '__main__.MetaB'> Name:C ============================ Method __new__ for metaclass MetaA not invoked in this case, only for metaclass MetaB. If I run almost same code in Python 3, despite of inheritance order in class C, method __new__ will be invoked only for metaclass MetaA. Could someone please explain why this happens and what was changed in Python … -
Django data error: value too long for type character varying(30)
I am new to Django. Trying to save selection from a drop down menu to a Postgres table. The drop down is populated from contents of relationship table and the drop down's selection is being saved into g_1 table. I have seen many folks report this error here. However, in this case both the tables i.e. from which the drop down reads and writes to, have the same schema. I am definitely doing something else wrong. Please advise. Details Django version: 1.10 Forms from django import forms from django.forms import modelformset_factory from rel.models import relationship class RelationshipForm(forms.Form): relations = forms.ModelChoiceField(queryset=relationship.objects.all()) class Meta: model = relationship fields = ('relation',) Models from django.db import models from datetime import datetime class relationship(models.Model): relation = models.CharField(max_length=30) def __str__(self): return self.relation class g_1(models.Model): relation_name = models.CharField(max_length=30) Views from django.shortcuts import render from rel.models import relationship, g_1 from rel.forms import RelationshipForm def rel(request): if request.method == 'POST': relation_name = RelationshipForm(request.POST) if relation_name.is_valid(): cd = relation_name.cleaned_data g_1_obj = g_1(relation_name = relation_name) g_1_obj.save() # do something. else: relations = RelationshipForm() return render(request, 'rel/test.html', {'relations': relations}) Postgres table schema screen shot -
Call custom function when Django rest-auth/register succeeds
Is there an easy way to tap into a successful call to the Django REST Framework /rest-auth/register API call so that a custom function can be called when a user has been successfully registered? The custom function I have written sends a push notification to my phone every time a user signs up. Obviously I can edit the rest-auth code plugin but this edit would not last if I update the plugin to a newer version. -
Django Admin Actions: selected checkboxes don't sum up
i got a Problem with jquery 3.0.0 and django 1.10. In Django Admin when i select checkboxes the number "0 of x selected" next to the select field does not change and a js error is raised: ReferenceError: interpolate is not defined admin/static/admin/js/actions.js Line 47 Can't find variable: interpolate