Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO avoid repeating date on DateTime calculation
I have managed to create a very simple model which allows me to subtract 2 DateTime fields, like so: class Log(models.Model): date = models.DateField() take = models.DateTimeField() land = models.DateTimeField() tot = models.CharField(max_length=200, blank=True, default='00000') def __str__(self): return str(self.date) def time_delta(self): tdelta = self.land - self.take return str(tdelta) def save(self, *args, **kwargs): self.tot = self.time_delta() super(Log, self).save(*args, **kwargs) My problem is the user would have to specify on every field the date, how could i make the fields take and land refer to date once and for all? -
Django filter using select_related()
I have the following query which works perfectly: campaignFixtures = UserSelection.objects.select_related().filter(user=currentUserID,campaignno=currentCampaignNo).order_by('fixtureid__fixturedate')[:1] However, I need to filter a field from another table as follows: campaignFixtures = UserSelection.objects.select_related().filter(user=currentUserID,campaignno=currentCampaignNo,straightredfixture__fixturematchday=18).order_by('fixtureid__fixturedate')[:1] But, I am receiving the following error: Cannot resolve keyword 'straightredfixture' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid The models are as follows: class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturestatus = models.CharField(max_length=24,null=True) fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') spectators = models.IntegerField(null=True) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) homegoaldetails = models.TextField(null=True) awaygoaldetails = models.TextField(null=True) hometeamyellowcarddetails = models.TextField(null=True) awayteamyellowcarddetails = models.TextField(null=True) hometeamredcarddetails = models.TextField(null=True) awayteamredcarddetails = models.TextField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season') def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid') class Meta: managed = True db_table = 'straightred_userselection' Any help would be appreciated, Alan. -
Problems installing a Django app using virtualenvwrapper and pip
I am relatively new to Django, and I must admin I'm getting confused (not to mention frustrated) with its frankly, bizarre folder structure - and the differentiation between website, projects, apps and modules. I am trying to install and use django-realestate into my virtenv (using virtualenvwrapper) After I created the new virtenv, I installed the Django app in the new environment. The problem is that the entire codebase is actually created under ~./virtualenvs/myenv The problem is that I want to be able to modify and (quite extensively) extend the code to suit my own purposes. However, I can't do that - if the code is under the "control" of virtualenv. My gut instinct is to do either of the following: Move the code from the src folder under ~./vitualenvs/myenv to /path/to/proj Create a brand new Django install and add(/merge?) the folders realestate, testproject and test to my project folder? It is a hideously complicated setup for what is a straightforward requirement: I want to have the latest Django version, and also have the code for the latest real-estate app (which I will modify extensively). How do I solve this problem? -
Django admin and migrate issue after terminal crash
Ok, this is kind of long in order to give you all the details, but the short version is that I can’t get Django to migrate or put my models in the admin. Django-1.10.4, Python 3.5.2, Ubuntu 16.04, Postgresql 9.4.8 I had just hit enter to run startapp when something went wrong in the terminal. I have no idea what, but it stopped accepting any keyboard input. When I got it back the app folder was there but Django kept telling me there were no changes to migrate. There is a migrations folder in the new app but there’s nothing in it but an empty init. But it was not in the admin. Yes, I filled out admin.py. Then when I hit Ctrl-C to stop runserver, it ran the system check and started runserver again. I also got the error message that the port was already in use. It did it 4 times before I got back to bash $ The django_admin_log table is empty, and django_migrations only shows the usual auth, sessions, etc. No apps. (blog) malikarumi@Tetuoan2:~/Projects/aishah/blog/src$ python manage.py makemigrations posts App 'posts' could not be found. Is it in INSTALLED_APPS? (Yes) I decided to try running startapp again … -
javascripts inside <body> does not run after running .load function
I encounter an strange problem in javascript and could not find solution. it is similar to this question Javascript function does always not run after .load but the answer is so wage and i am not using php. I have a script in that reload a to update the scores every 4 second. so every 4 second it sends a request and get a new data. I am trying to show Q.scorechange as red or green based on if the number is negative or positive. my code bellow works only for the first 4 seconds so first Q.scorechange is red after 4 seconds it becomes black for the reset of time. also i am using django. <head> <script> var myVar = setInterval(ReLoad , 4000); //refresh every 4 seconds function ReLoad() { $("#live").load(document.URL + " #live"); } </script> </head> <body> <div id="live"> <p> change in score : <span onload="readyFn()" id="rg" style="font-size:14px"> {{Q.scorechange}} </span> <script> function readyFn( jQuery ) { var num = {{ Q.PriceChange|safe }}; if(num<0){ document.getElementById("rg").style.color = "red"; } else if (num >0){ document.getElementById("rg").style.color = "green"; } else{ document.getElementById("rg").style.color = "black"; } } $( document ).ready( readyFn ); </script> </div> </body> -
Django admin show column in list_display from non-relational Model
I have four models and one admin model. These are StudentScore, Student, Teacher, TeacherPay and StudentScoreAdmin. Model 'Teacher' has One to Many relation with 'Student' model and One to One relation with 'TeacherPay' model. Student model has One to One relation with StudentScore. I am adding the relation flow below- *StudentScore* id student_id fk (Student) *Student* id teacher_id fk (Teacher) *Teacher* id *TeacherPay* id teacher_id fk (Teacher) payment_status *StudentScoreAdmin* Model relation flow: StudentScore->Student->Teacher TeacherPay->Teacher *StudentScoreAdmin* {display data from Student and TeacherPay model} I can show data in the table page from "Teacher" model. But unable to show data from TeacherPay. On the StudentScoreAdmin, I want to display 'payment_status' column in the admin list_display screen. Also, I want to use 'payment_status' in list_filter. THanks -
django admin - how to improve search using elasticsearch
I have implimented elasticsearch to search through files and overriden the get_search_results method of the django 1.8 admin page and I'm able to perform the search with elasticsearch: def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(InventoryAdmin, self).get_search_results(request, queryset, search_term) if 'action' in request._get_request() and request._get_request()['action'] == 'delete_selected': return queryset, use_distinct elif len(search_term.strip()) > 0: results = do_elastic_search(search_term) queryset |= self.model.objects.filter(id__in=results) # add the filters to the queryset: for key, val in request._get_request().items(): if key in Inventory._meta.get_all_field_names(): param = {key: val} queryset = queryset.filter(**param) return queryset, use_distinct My data is loaded in the django db as well as elasticsearch. The concern is that if there are many results, this will fail because it django uses GET method for the search and it will hit the max length... I know how to do pagination in elasticsearch but not sure how to override pagination in django. Is there a solution to this problem other than making a custom admin page? -
How to redirect a REST query to a non-REST view only when a query parameter is set?
I have a REST viewset for which I want to be able to perform a redirection to a non-REST view if a request comes in with a specific flag. I want: A GET to my viewset to redirect to another view when flag is set on the request and return a JSON response otherwise. If the client sets the Accept HTTP so both JSON or HTML are possible, I want the format returned to be JSON if flag is not set, and HTML when flag is set. (That is, the default format should vary depending on whether flag is set.) The only valid response format is HTML when flag is set, and JSON when flag is unset. This is what I have: class FooViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = SomeModel.objects serializer_class = SomeModelSerializer lookup_field = "pk" renderer_classes = (renderers.JSONRenderer, ) def retrieve(self, request, *args, **kwargs): # The original code validates the value of `flag` but # that's not relevant to the issue here. flag = request.GET.get('flag', None) if flag: if request.accepted_renderer.media_type != "text/html": raise NotAcceptable return HttpResponseRedirect(SomeModel.objects.get(pk=kwargs["pk"]) .get_absolute_url()) if request.accepted_renderer.media_type != "application/json": raise NotAcceptable return super(FooViewSet, self).retrieve(request, *args, **kwargs) The problem with the code above is that the accepted renderer never has … -
Django multiple model query in view
I've made a query set as like below to add multiple model query passes to view. class ProjectListView(ListView): model = Projects template_name = 'project.html' def get_queryset(self): group_name = 'example' object_list = self.model.objects.filter(group__name__contains=group_name) object_list['group_details'] = Group.objects.all() return object_list But it shows 'QuerySet' object does not support item assignment. How can I fix this. -
Django 1.8 How Drop all tables using manage.py?
I'm having a real bad time using manage.py to drop certain tables of the database, the project is already running. the only way I found is accessing the tables by: python manage.py dbshell but again, not sure how to drop the tables. -
Post method of a form sends data to get method of a class based view
Django 1.10.4 There are two breakpoints. Could you help me understand why the debugger stops at breakpoint 1? The method is post. Why the flow is directed to get handler? def form_view(request): html = """<form action='/testform' method="post"> <input name="q"> <input type=submit> </form> """ return HttpResponse(html) class TestHandler(View): def get(self, request): q = request.GET.get("q") # Breakpoint 1. return HttpResponse(q) def post(self, request): pass # Breakpoint 2. return HttpResponse(result) urlpatterns = [ url(r'^form/$', form_view, name='form'), url(r'^testform/$', TestHandler.as_view(), name='testform'), ] -
Add conditional filter to ListView Django
I have list of events. Using ListView to render them. In models.py def event_date_time(self): event_date_time = datetime.combine(self.event_date, self.event_time) return event_date_time In ListView i also have now= datetime.utcnow() Need to add a filter to queryset. if now > event_date_time: #don't render that event else: #render -
How can I filter on two different related fields and have them both be satisfied in one query?
I have some models with a relationship like the following: class Container(models.Model): pass class Child(models.Model): container = models.ForeignKey(Container, related_name='children') tag = models.CharField(max_length=40) val = models.IntegerField() I would like to filter the container on whether I can find two separate children, one having a tag of 'foo' with a val in [1,2,3] and the other having a tag of bar with a val in [3,4,5]. When I filter like the following: print list(Container.filter( Q(children__tag='foo', val__in=[1,2,3]) & Q(children__tag='bar', val__in=[5,6,7])) ).distinct() Django is too smart. It filters every single Child to make sure it has both a tag of 'foo' and of 'bar' as well as values in both [1,2,3] and [5,6,7] with the following SQL: SELECT COUNT(DISTINCT `app_container`.`id`) FROM `app_container` INNER JOIN `app_child` ON (`app_container`.`id` = `app_child`.`container_id`) WHERE app_child.tag = 'foo' AND app_child.val in (1,2,3) AND app_child.tag = 'bar' AND app_child.val in (5,6,7) I want django do do something like the following to get Containers with two different children: SELECT COUNT(DISTINCT `app_container`.`id`) FROM `app_container` LEFT JOIN `app_child` c1 ON (`app_container`.`id` = `c1`.`container_id`) LEFT JOIN `app_child` c2 ON (`app_container`.`id` = `c1`.`container_id`) WHERE c1.tag = 'foo' AND c1.val in (1,2,3) AND c2.tag = 'bar' AND c2.val in (5,6,7) -
How do I append binary file data to a <form> and submit it synchronously?
I've got a template that works nicely with synchronous submission. I've got a couple of images that I'm trying to upload with the form, having resized them in the browser to the desired size in a <canvas>. I could append these to a FormData object, but I'm trying to avoid asynchronous submission because I'd really like to reprocess the template through the django template context processor (for various reasons). Is it possible to get my binary image data in the form, submit synchronously, and still be "recognisable" as a request.FILES object server side? If so, how do I do this? -
Nginx + uWSGI worker is killed by signal 9 during a request
I created a web server by Nginx + uWSGI + Django. The basic flow is: when a request is received, uWSGI worker will read some items from db. Sometimes the request client got FileNotFound exception randomly from nginx, and the reason is because the corresponding uwsgi worker is killed by signal 9 without any other error message. So I benchmarked with the case which request uwsgi directly(without nginx), and didn't see such failure. Any clue to triage such nginx + uwsgi issue? Another thing I found is that last log of the killed worker is always reading data from db, but I'm not sure whether it's related to worker issue. -
Django Forms pyodbc Mssql TypeError: not all arguments converted during string formatting
I'm developing an web app alongside an existing windows app on SQL server 2014.Using the following settings DATABASES = { 'default': { 'NAME': ' Name', 'ENGINE': 'sql_server.pyodbc', 'SERVER': 'server', 'USER': 'sa', 'PASSWORD': 'password', 'OPTIONS': { 'driver_supports_utf8': True, 'autocommit': True, 'unicode_results': True, 'host_is_server':True, 'driver': 'SQL Server Native Client 11.0', } } } I'm Using stored procedures in my django app to use the existing functionalities class Viewpatform(forms.Form): Name = forms.CharField(max_length=100) Phone_Number = forms.IntegerField(label='Phone Number', required=True) Sex = forms.ChoiceField(widget=forms.Select(choices=sexchoice)) Age = forms.IntegerField(label='Age') AgeType = forms.ChoiceField(choices=Agetype, required=True, label='Type') Address = forms.CharField(max_length=500, required=False) Registration_Date = forms.DateField( label='Registration Date') with connection.cursor() as cursor: cursor.execute(''' EXEC dbo.insert_patients @Name = ?, -- varchar(100) @Phone_Number = ?, -- int @Age = ?, -- int @AgeType = ?, -- int @Address = ?, -- varchar(200) @sex = ? -- varchar(2) ''', [ Name, Phone_Number, Sex, Age, AgeType, Address] ) I have been getting the following errors while executing the form File "c:\python35\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "c:\python35\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "c:\python35\lib\site-packages\sql_server\pyodbc\base.py", line 535, in execute sql = self.format_sql(sql, params) File "c:\python35\lib\site-packages\sql_server\pyodbc\base.py", line 503, in format_sql sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string … -
Deploying React and Django on Heroku
I've been hitting my head against this problem for a while and can't seem to figure it out. I'm trying to deploy a Django app to heroku where the front end uses react. I'm pretty new to react so it's possible I'm missing something fundamental here. I have one heroku app right now that has two buildpacks (heroku/nodejs and heroku/python). To run the app locally I use python manage.py runserver along with node server.js on port 3000. I know Heroku only lets one port receive HTTP requests so I think the problem is there. My main question is: To use Django and React on a Heroku app do I need to have two separate apps (one for django and one for react) or can I maintain only one app? I've been searching through this repository and it seems like only one app is used. However I can't see how the node server is working. Thanks for any clarification or a push in the right direction! Let me know if I need to clarify my question. Edit: A couple other things I've tried: Following this tutorial Adding a heroku-postbuild script to my package.json file that starts the node server. This prevents … -
Django get Model fields in order
Is there a way to get them in code order, or set an order for the fields of a Django Model? When I call MyModel._meta.get_fields() they come unordered (altough is the same 'unordered' order as long as you don't reset the server it seems). I've read about ordering in Forms https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.order_fields, but not in the Model itself -
User registration - validation form doesn't work
I'm new to django, and I'm trying to make a user registration system, but the validations to the form aren't working propely. I want to change the displayed error messages, as english isn't my first language, these modifications that I did, simply doesn't work at all, they should, I'm getting a lousy form, without any validation as I want, the error messages are still in english. Forms.py # -*- coding: utf-8 -*- from django import forms from django.contrib.auth.models import User class UserModel(forms.ModelForm): User._meta.get_field('email').blank = False User._meta.get_field('first_name').blank = False class Meta: model = User fields = ["username", "first_name", "last_name", "email", "password"] widgets = { 'first_name': forms.TextInput(attrs={'class': 'form control', 'maxlength':255, 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form control', 'maxlength': 255}), 'email': forms.TextInput(attrs={'class': 'form control', 'maxlength': 255}), 'username': forms.TextInput(attrs={'class': 'form control', 'maxlength': 255}), 'password': forms.PasswordInput(attrs={'class': 'form control', 'maxlength': 255}) } error_messages = { 'first_name': {'required': 'Este campo é obrigatório'}, 'last_name': {'required': 'Este campo é obrigatório'}, 'email': {'required': 'Escreva um email válido'}, 'username': {'required': 'Este campo é obrigatório'}, 'password': {'required': 'Este campo é obrigatório'}, } Views.py from django.shortcuts import render from usuarios import forms # Create your views here. def cadastro(request): form = forms.UserModel(request.POST or None) context = {'form': form} if request.method == 'POST': if … -
Django SMTP settings
Maybe I wasn't clear enough about the problem, so I will try once more. I need to use SMTP server to send large amount of emails with Django application. Settings that I used to establish connection are: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.premium-web-domain.com' EMAIL_HOST_USER = 'username@premium-web-domain.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 25 And I get error like this: smtplib.SMTPAuthenticationError: (535, '5.7.8 Error: authentication failed:') Any ideas what might be the problem? -
Django requests_ntlm authentication in Ubuntu
I have developed an app in django that consumes SOAP request from a .NET WebApplication host in a Windows Server. I develop this django-app on Windows, working on a specific environment created with virtualenv. All seemed to work right, until i had to put the app in my production server, which is an Ubuntu Server 14.04. (Later on i tried with version 16.04 and have the same result). The problem I am having is that when I authenticate the session of the request, it returns a protocol violation error (_ssl.c: 590). This did not happen in the development environment I had in windows. I look for some solution, but I did not find anything that solved the problem. My environment: **cffi==1.9.1 cryptography==1.7.1** diff-match-patch==20110725.1 **Django==1.8.2** django-cors-headers==1.0.0 django-extensions==1.5.5 django-filebrowser==3.5.7 django-filter==0.10.0 django-grappelli==2.5.7 django-import-export==0.2.7 django-security==0.1.12 djangorestframework==3.1.1 djangorestframework-jwt==1.5.0 enum34==1.1.6 idna==2.1 ipaddress==1.0.17 MySQL-python==1.2.5 **ndg-httpsclient==0.4.2** **ntlm-auth==1.0.2** ordereddict==1.1 Pillow==2.8.2 pyasn1==0.1.9 pycparser==2.17 PyJWT==1.3.0 **pyOpenSSL==16.2.0 requests==2.12.4 requests-ntlm==1.0.0** **six==1.9.0 suds==0.4 suds-requests==0.3** tablib==0.10.0 xmltodict==0.10.2 and the OpenSSL version is 'OpenSSL 1.0.2g 1 Mar 2016'. The code below shows how i make the connection and authentication in the request, using requests_ntlm (because the WS authentication is NTLM) for the authentication. Also i had to use an Adapter for session mount, because I could … -
How to register a user after external authentication in ejabberd?
In ejabberd, i have authenticated(external authentication) user with django's user. Once that is done, how do i register a user to the host? -
How to get extended User custom fields in django template?
I have extended django builtin user model. I am currently using django 1.10. I am trying to display user name, short_name in template. note: short_name is extended field <span> {{ request.user.profile.username }} </span> <span> {{ user.profile.username }} </span> {{ user.get_username }} {{ user.username }} this template tag is not working for django 1.10 using this I would like to display role based content. class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) employee_name = models.CharField(max_length=50) short_name = models.CharField(max_length=50) access = ( ('admin', 'admin'), ('director', 'director'), ('management', 'management'), ('employee', 'employee'), ) access_control = models.CharField(max_length=50, choices=access) YES_NO = ( ('yes', 'Yes'), ('no', 'No'), ) active = models.CharField(max_length=50, choices=YES_NO) -
How to link Django project with restframework?
I created a python-django project by referring a video tutorial. In that video, there are 2 project folders. One for project and another for API. How can I link the API with my project? Please refer a clear tutorial for API. -
Concatenate HTML with Django variable in HTML Template
I have a question which could help me a bit in my project. I would like to know if it's possible to concatenate an HTML input action with a Django variable ? For example : <form method='POST' action='/BirthCertificate/BirthCertificate_PDF/'+ {{birthcertificate.id}}> {% csrf_token %} In order to get : /BirthCertificate/BirthCertificate_PDF/12/ Where 12, for example refers to the last ID created in my table. Then, I have a function which takes this id number and makes some things because I know the useful row : From views.py file : def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) return render(request, 'BC_raw.html', {"birthcertificate" : birthcertificate}) From urls.py file : from django.conf.urls import url from . import views urlpatterns = [ url(r'^accueil$', views.BirthCertificate_Home, name="home"), url(r'^formulaire$', views.BirthCertificate_Form, name = "form"), url(r'^formulaire_traite/(?P<id>\d+)/$', views.BirthCertificate_Resume, name="treated"), url(r'^BirthCertificate_PDF/(?P<id>\d+)/$', views.BirthCertificate_PDF, name="PDF") ] I think my question is really ugly but it could work if I can concatenate both elements. Thank you if you have advices,