Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Push Notifications in python
I am attempting to send basic push notifications to GCM and APNS in python. I am experienced in python, but mostly for data analysis/modeling. I have tried pushjack and have successfully sent a push. But there is little documentation on it. from pushjack import GCMClient client = GCMClient(api_key='API-KEY') registration_id = 'REG-ID' notify = {'title': 'Push_test', 'body': 'This is a python test!!', 'icon': ''} res = client.send([registration_id], '', notification=notify) But the icon on the actual push does not look right and I cannot send without the icon key in the notify dict. I am not sold on using this module, and am open to using to django, but I have no experience with this and (correct me if I am wrong) seems much too advanced for sending a basic push. Any help/suggestions would be very much appreciated. -
We are trying to match people in django with specific fields in the models
We have a website that matches people together depending on their service they provide and the need of another user. So, If I can do photography and I need auto repairs it would match me with a person who does auto repair and needs photography. We have it matching via zipcode before hand. Here is what the view.py looks like: def Post_list(request): if request.user.is_authenticated(): queryset_list = CustomerService.objects.all() service = request.user.customer.customerservice.servicesID need = request.user.customer.customerservice.needsID need.lstrip('[') need.rstrip(']') need.split(", ") service.lstrip('[') service.rstrip(']') service.split(", ") zip = request.user.customer.zipCode customers_list = CustomerService.objects.all() matchedUsers_list = customers_list.filter(customer__zipCode = zip) matchedUsersTwo_list = matchedUsers_list matchedUsersThree_list = CustomerService.objects.none() serviceList = matchedUsersTwo_list.values_list('servicesID', flat=True) for x in need: for y in serviceList: if y.find(x): matchedUsersThree_list=matchedUsersTwo_list.filter(y) We were trying to have a list of the needs and services and look through it to filter whichever user does not match. That is the part we are having trouble with. The models.py looks like this: from django.db import models from django.contrib.auth.models import User class customerManager(models.Manager): def makeCustomer(self, user, zipCode, bio): customer = self.create(user=user, zipCode=zipCode, bio=bio) return customer class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) zipCode = models.IntegerField(default = '55555') bio = models.TextField(max_length = 1500) objects = customerManager() def __str__(self): return self.user.username class customerServiceManager(models.Manager): def makeCustomerService(self, customer, … -
how do i execute django in my command prompt?
I have installed Django and I also got get-pip. but none of these run whenever I type pip or import Django in my command prompt. I am a beginner so please bear with me and help me fix this as soon as possible. your answer will be very helpful to me. -
ValidationError Date in different Format
I'm building a Bus Reservation Website using Django. User enter--- to, from and date to get available buses on that date. However, I'm getting this error. ValidationError at / ["'13/04/2017' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] All my entire code of forms, models, views, templates is here -- https://dpaste.de/K02Z -
Get songs from playlist
Here is my Playlist model class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') songs = models.ManyToManyField('Song') def __str__(self): return self.name @property def playlist_id(self): return self.id It works fine ,but how do I get the songs from the playlist? -
Django, how validate between 3 tables?
I have 3 models. class Thing (model.Models): name = models.CharField(max_length = 222) ... class UserProfile(model.Models): infos class Rate(models.Model): thing = models.ForeignKey(Thing) user = models.ForeignKey(User) How to make validate between? I want one user to have one rating for one thing. -
How to know IP Lan request client in python?
Is there a way to know the lan IP request client?. I am work in django, I tried this: def get_ip_test(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('8.8.8.8', 0)) IP = s.getsockname()[0] except: IP = '127.0.0.1' finally: s.close() return IP But this return IP from server, I saw in javascript an example to get LAN IP example javascript Many thanks for your help. -
DjangoORM: Resolve F Expression in Custom DB Function
I am trying to write a custom postgresql function in Django that will coerce datetimes to a specified timezone inside of a queryset. My first pass at the db function looks like this: from django.db.models.expressions import Func class DateTimeInTimezone(Func): template="%(expressions)s AT TIME ZONE %(tz_info)s" This function works in the simple case where I pass a timezone string into the function directly like so: MyModel.objects.filter(timefield__gte=DateTimeInTimezone(Now(), tz_info='EST')) However it doesn't work in the more complex case, where the timezone is defined on some field on the model. Consider the following contrived example: class User(models.Model): time_zone = models.CharField() class Meeting(models.Model): users = models.ManyToManyField(User) start_time = models.DateTimeField() # in UTC end_time = models.DateTimeField() # in UTC To answer the question "What users will be in a meeting at 12pm local time today?", I'd need some variation of this queryset: noon_utc = ... User.objects.filter( meetings__start_time__lte=DateTimeInTimezone(noon_utc, tz_info=F('time_zone')), meetings__end_time__gt=DateTimeInTimezone(noon_utc, tz_info=F('time_zone')) ) As currently written, however, DateTimeInTimezone will simply inject the string F('time_zone') into the sql rather than resolving the field. Is it possible to add support for F Expressions to this function? Is there some other approach that I should consider? -
Django template variables not working
(I am new to Django) I'm having a problem with my Django template. The cruise_details filter should only return one row, but when I try and display this in the template with cruise_details.port for example, nothing is displayed. "code" is correctly getting passed from the URL. If I remove .port and just put cruise_details I am presented with this on the page <QuerySet [<Cruise: B724>]> view.py def cruise(request, code): return render(request, 'cruise.html', { 'cruise_details': Cruise.objects.filter(code=code) }) cruise.html {{ cruise_details.port}} models.py class Cruise(models.Model): code = models.CharField(max_length=10) destination = models.CharField(max_length=60) url = models.URLField ship = models.ForeignKey(Ship) duration = models.IntegerField start = models.DateField end = models.DateField added = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) port = models.CharField(max_length=30) -
IOERROR [Errno socket error] [Errno 0] Error
I'm getting the following error now I've migrated a django project from my laptop and onto a development server with Apache serving the files. [Errno socket error] [Errno 0] Error This error is following this call to GoogleMaps: url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='+request.session['postcode']+'&destinations='+s.post_code+'&key='+GOOGLE_MAPS_DIRECTIONS_KEY result= simplejson.load(urllib.urlopen(url)) Having got the error, if I refresh the screen it works. It also works using the django development server on my laptop. The key is valid and has been set up with no restrictions. What's going wrong? Thanks for help in advance. -
Download multiple files from S3 django
Here is the link i have used (Download files from Amazon S3 with Django). Using this i'm able to download single file. Code: s3_template_path = queryset.values('file') filename = 'test.pdf' conn = boto.connect_s3('<aws access key>', '<aws secret key>') bucket = conn.get_bucket('your_bucket') s3_file_path = bucket.get_key(s3_template_path) response_headers = { 'response-content-type': 'application/force-download', 'response-content-disposition':'attachment;filename="%s"'% filename } url = s3_file_path.generate_url(60, 'GET', response_headers=response_headers, force_http=True) return HttpResponseRedirect(url) I need to download multiple files from S3, as a zip would be better. Can the mentioned method be modified and used. If not please suggest other method. -
Multiple search fields using Haystack and ElasticSearch in Django
My problem is that when I load the template (http://localhost:8000/search) I always get only one search field on the template. I have this code in search_indexes.py: from haystack import indexes from compounds.models import SportsCenter class SportsCenterIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) text2 = indexes.DateTimeField name = indexes.CharField(model_attr='name') phone = indexes.CharField(model_attr='phone') district = indexes.CharField(model_attr='district') address = indexes.CharField(model_attr='address') opening_hour = indexes.DateTimeField(model_attr='opening_hour') closing_hour = indexes.DateTimeField(model_attr='closing_hour') description = indexes.CharField(model_attr='description') def get_model(self): return SportsCenter And this is sportscenter_text.txt: {{ object.name }} Then this is sports_center_tex2.txt: {{ object.district }} I want to have a search that has 2 search input bars, one for name and one for district, but for now I only get one search input bar. -
Does Django Channels work as intended as a WSGI app?
I am trying to implement Django Channels because I need to have users receive notifications when another user does something, and I am completely confused by this part: http://channels.readthedocs.io/en/stable/deploying.html Deploying applications using channels requires a few more steps than a normal Django WSGI application, but you have a couple of options as to how to deploy it and how much of your traffic you wish to route through the channel layers. Firstly, remember that it’s an entirely optional part of Django. If you leave a project with the default settings (no CHANNEL_LAYERS), it’ll just run and work like a normal WSGI app. The problem is that I have quite limited rights on the shared hosting that I am using and therefore, I can't use the runworker command. The quote above says that this part is "optional" and that without it, it'll work like a normal WSGI app. But can I use Django Channels with a normal WSGI app? If not, then doesn't that mean that it's not optional at all? So my question is: if I skip this part, will the channels still work and will I be able to use the things showed on this page (routing, sending messages, … -
django 1.10 Application level URL does not recognize positional parameter
I'm trying to employ positional parameters on a view inside one app of my django application. The app is called member. and the member/urls.py is called by the project trekfed: trekfed.py from member import urls as mviews from public import views as pviews urlpatterns = [ url(r'^member/', include(mviews)), url(r'^admin/', admin.site.urls), member\urls.py urlpatterns = [ url(r'$', views.index, name='myprofile'), url(r'^(?P<mbr>)/$', views.index, name='profile'), url(r'^api/', include(router.urls)), ] views.py @login_required def index(request, mbr=""): print(mbr) data = {} if mbr: user = User.objects.filter(Q(id=mbr)|Q(username=mbr)).values('User_id') else: user = request.user data['user'] = user data['member'] = models.Member.objects.get(User=user) data['Address'] = models.Address.objects.filter(User=user).get(Primary=True) data['Phone'] = models.Phone.objects.filter(User=user).get(Primary=True) data['Family'] = models.Family.objects.filter(Primary=user.member) data['Sponsor'] = models.Family.objects.filter(Dependent=user.member.pk) data['rank'] = models.Promotion.objects.filter(User=user).latest('Date_Effective') return render(request, "member/profile/page_user_profile.html", data) when authenticated, if I go to http://localhost:8000/member/ I can see my profile. No problems. If I go to http://localhost:8000/member/user2/ I still see my profile, not user2's. Is there something that I'm missing here? Thanks. -
How can i use a lookup table to get a row from a parent table using parameter in django
I have the following model in django. What I wanted to do was make a user login a specific service and direct him/her based on the type of the service after login. A user can have maximum one service but a service can have multiple users. However, a service does not necessarily need a user. Hence, I cant create a one-to-one relation with users model. So, i added a second table. What I want is after a user is logged in, to get the details of the service (id,name and service kind) so I can redirect to the right view based on the kind. class Service(models.Model): SERVICE_TYPE = ( ('Local', 'Local'), ('External', 'External'), ) name=models.CharField(max_length=50, unique=True) serviceNature=models.CharField(max_length=25,choices=SERVICE_TYPE,default='Local') def __str__(self): return self.name class Meta: ordering=('name',) class ServiceUser(models.Model): ''' User to Service ''' service=models.ForeignKey(Service,related_name='service_user',on_delete=models.CASCADE) user=models.OneToOneField(User,related_name='user_service',on_delete=models.CASCADE,unique=True) def __str__(self): return self.user.username + ', ( ' + self.user.first_name + '), ' + self.service.name class Meta: ordering=('service','user') def myservice(self,user): #for the given user, return the service name and type, if exists. I failed to attach it here correctly here. return [self.service.id,self.service.name,self.service.serviceNature] I am able to attach a user with a service from the admin area (users dont have staff or super status so they cant login … -
How do I give users the ability to make their private playlist?
I am creating a song website where users can view songs and add them to their playlist. So I created almost every functionality of the website (songs,albums,artists) except User and Playlist. I know that we can create users account management system by two ways: 1) By using django's own user system 2) By creating our own custom UserProfile I created the user profile system using Django's own user system. Users can register & login to my page. Now I want to add the functionality of playlist to my website. After users are logged in, they could create their own private playlist and add as much as songs to their playlist. How can I add this functionality of playlist?Thanks -
django query get last n records on database server
Hi accroding to django query get last n records Is it good idea to get this last n record using [:n]? Can I do it on database serwer (for example in sql "select top 10"), not on server where is django? -
Django static files using whitenoise on heroku
I am trying to use Heroku's documentation to serve static files on my local machine and in production. However, whenever I run my app with debug=True everything works as expected; static files are retrieved and the app displays as intended. However, whenever I change debug=False I get a Server Error (500). As far as I can tell it all boils down to my STATICFILE_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'. When I comment that out, my app will run with debug=False, but with no styling due to the lack of static files. I have gone through the whitenoise documentation, and heroku's but I can't figure out what is going on, apart of from STATICFILE_STORAGE being the issue. Is whitenoise not meant for production? Do I have to use a CDN in production? It's a small time app, so I was hoping not to have to use CDN, but will if necessary. settings.py (I only included the parts of settings.py that I thought were relevant. If you need the whole thing, let me know.) import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False MIDDLEWARE = … -
TemplateDoesNotExist when using as_view()
I receive: TemplateDoesNotExist at /skills2/ portfolio/skill_list.html when access http://127.0.0.1:8000/skills2/ mysite/mysite/urls.py from django.conf.urls import url from django.contrib import admin admin.autodiscover() from portfolio.views import skills, experience, index, v_index, SkillsView from django.conf.urls import include, url urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^skills2/$', SkillsView.as_view(), name='skills'),] mysite/portfolio/models.py from django.db import models class Skill(models.Model): publish_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=True, default='') description = models.TextField(default='') def __str__(self): return self.name mysite/portfolio/views.py from .models import Skill, Experience class SkillsView(generic.ListView): model = Skill mysite/portfolio/templates/index2.html {% extends "base_generic.html" %} {% block content %} <h1>Portf site</h1> <p>Welcome to <em>My Site</em>, a very basic Django website</p> <h2>Dynamic content</h2> <p>The site has the following record counts:</p> <ul> <li><strong>Skills:</strong> {{ num_skills }}</li> <li><strong>Exp:</strong> {{ num_experience }}</li> </ul> {% load static %} <img src="{% static 'oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/> {% endblock %} mysite/portfolio/templates/base_generic.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>My portfolio web-site</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> <li><a href="{% url 'v_index' %}">Home</a></li> <li><a href="{% url 'skills' %}">All skills</a></li> <li><a href="{% url … -
Django-rest-framework testing with mock server
We are working on a micro-service project, where the services communicate using DRF. Some of the micro-services are "chained", that is they receive some request, do some logic, such as store some things to a db, and then they themselves call other services running on the same or different domains. I want to cover the components with unit tests, however, when I use the APIRequestFactory to test my views, and when such views send requests to other microservices, I run into the problem that those "other" servers are not accessible. Is there a way to mock up those "other services", so that I can check the logic in those "primary" microservices? -
Join with more than one, specific one-to-many rows
I have to join one row from table Type1 with two rows from table Type2. There are example models of database: class Type1(models.Model): name = models.CharField(max_length=300) class Type2(models.Model): foreign = models.ForeignKey(Type1) name = models.CharField(max_length=50) value = models.IntegerField() In SQL, query looks like this: SELECT A.name, B.value, C.value FROM Type1 A, Type2 B, Type2 C WHERE B.foreign = C.foreign = A.id AND B.name = _VAR1_ AND C.name = _VAR2_ How to do that query using Django methods (not raw SQL!)? -
Django Get user for social token
I want to try and get the users social token after they login via facebook with django allauth. If i go to a view, i can get it like so @login_required() def current_datetime(request): now = datetime.datetime.now() print(request ) html = "<html><body>It is now %s.</body></html>" % now access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') r = requests.get( 'https://graph.facebook.com/me/friends?access_token=' + access_token.token ) print(r) This works. However i am trying to get it using signals and i cant get the user. def makefbuser(sender ,**kwargs): if kwargs['created']: access_token = SocialToken.objects.get(account__user=kwargs['instance'], account__provider='facebook') r = requests.get( 'https://graph.facebook.com/me/friends?access_token=' + access_token.token) print(r) post_save.connect(makefbuser, sender=User) I need to know how to get the user as to put it into account_user. kwarges['instance'] and request.user have the same data in it,expect kwarges['instance'] is of type User and request.user is of type SimpleLazyObject -
Execute Threaded Socket in Django only once
I am using Django v1.10 (Same Error in 1.9 and 1.8), hosting on IIS. I use threaded sockets within Django to connect to another app to request data from. When site is running (on Apache or IIS), it has the tendency to open another thread, sometimes several and Django still runs perfectly... however (drumroll): There can only be one same port connection at a time, meaning a new thread runs a new and seperate instance of my sockets module, which causes a clash between the ports and the sockets then become unusable throughout the site. It took me a long time to work out this was the issue, having rebuilt my sockets and threading module several times (smashes head into keyboard). If I import the whole module into Views, it is ran in other Django threads and the sockets crash. The closest thing I found was: [here][1] What I need to do is to have the threads running and still be able to make requests from the module which contain the running threads eg: module.SendRequest and module.ReceiveRequest. If I import these into Views, they don't work with the threads. I've tried importing the modules in Apps, then importing the SendRequest … -
how to render MathML output to django template?
I want to render Fraction part vertically in my django template. for example ('5/6') to be printed vertically. I've seen LaTex, MathML but didn't find a proper way to render it inside Django template. -
'QuerySet' object has no attribute 'timesheet_id' InLineFormSets
I'm trying to display existing entries for particular criteria on my webpage using an inlineformset. Here are the lines in my view TimeFormSet = inlineformset_factory(TimeSheet, Time, form=TimeForm, extra=1) person_timesheets = Time.objects.filter(timesheet_id=timesheet) print person_timesheets.count() time_formset = TimeFormSet(instance=person_timesheets) I don't understand why this is causing 'QuerySet' object has no attribute 'timesheet_id' print person_timesheets.count() returns a number to my console no problem... I must be using instance wrong here. Here are my models class Time(models.Model): description = models.CharField(max_length=150) timesheet_id = models.ForeignKey(TimeSheet, null=True, related_name="time_set") def __unicode__ (self): return self.description class TimeSheet(models.Model): start_date = models.DateField() status = models.CharField(max_length= 50, default="Open", choices=STATUS_CHOICES) When I save my Time in my view I set the timesheet_id field with the Django assigned id of the related TimeSheet (not sure if this is a messy way to do this...). Help!?