Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use Websocket in Angularjs
I'm trying to use Websocket in Angularjs. I have added this implementation in a factory becouse want to use it in different controllers, so this is my code .factory('webSocketBridge', function () { const webSocketBridge = new WebSocketBridge(); webSocketBridge.connect('/ws/user-notification/'); webSocketBridge.listen(function(action, stream) { console.log(action, stream); }); webSocketBridge.socket.addEventListener('message', function() { console.log("message"); }); webSocketBridge.socket.addEventListener('open', function() { console.log("Connected to WebSocket"); webSocketBridge.send({prop1: 'value1', prop2: 'value1'}); }); return webSocketBridge; }); Open event working and I see "Connected to WebSocket" console but Message event not working. Can someone show me how I can send message and get it -
NoReverseMatch: Reverse for '...' not found
I want to implement Django REST Framework and change my views accordingly. The FBV phase1 was changed to CBV DescriptorList my template phase1.html {% load rest_framework %} ... <li><a href="{% url 'szenariohome' projectid %}">Return to Project Overview</a></li> my urls.py in app named szenario urlpatterns = [ url(r'^(?P<id>[0-9]+)/szenariohome/$', views.szenariohome, name='szenariohome'), url(r'^(?P<id>[0-9]+)/phase1/$', views.DescriptorList.as_view(), name='phase1'), ] views.py class DescriptorList (APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'szenario/phase1.html' def get(self, request, id): descriptor = Descriptor.objects.all() serializer = DescriptorSerializer(descriptor, many=True) return Response({'serializer': serializer, 'descriptor': descriptor}) @permission_required_or_403('szenario.view_project', (Project, 'id','id')) def szenariohome(request, id): als links, mitarbeiter, projectleader projectname = get_object_or_404(Project, pk=id) projectuser = AbstractUser.objects.filter (workingproject=id) projectid = id context = {'projectname': projectname, 'projectuser': projectuser, 'projectid': projectid} return render(request, 'szenario/szenariohome.html', context) @permission_required_or_403('szenario.view_project', (Project, 'id','id')) def phase2(request, id): projectname = get_object_or_404(Project, pk=id) projectid = id context = {'projectname': projectname, 'projectid': projectid} return render(request, 'szenario/phase2.html', context) I get the error "Reverse for 'szenariohome' with arguments '('',)' not found. 2 pattern(s) tried".Without the line the template works. Template for phase2 has the same line and works fine. Could this problem occure because I used a serializer or a because i mixed CBV and FBV? Any kind of help is appreciated,thanks. -
API timeout in nginx but the same work in local server Django WSGI
I am facing issue in my Django app... which is working fine in mhy local django WSGI based server. but the same facing timeout in nginx.. what will be the issue? is there anything to deal with increasing nginx process? my nginx response which took 30000ms to respond in my server but without data (i am using AWS), my local got respond in 12000ms with response, any help? My django app is on AWS i am using nginx gunicorn and supervisor for deployment configuration... -
(Reward to best answer in bitcoin) Algorithm for ranking heavy users(both quantity and quality wise) in blogging platform, preferably in python
Hi I'm trying to build a little blogging platform that ranks hot posts, comments AND heavy users that regulary post quality contents on the platform. As for posts and comments, I'm trying to burrow ideas from reddit as posted here. But I have no idea how I can effectively rank users considering both how active they are in posting contents and how good they posts are.(i.e. both quality and quantity of users' posts) Any ideas? Please help. I'm planning to send a little token of gratitude in bitcoin worth 10 starbucks coffees to someone who proposes best ideas...:) -
Populate combos in Django and initialize them with a foreign key
I need to populate two combos in a ModelForm, and I would like to initialize them with the current value of each foreign key. My models are: class Alumno(models.Model): idalumno = models.AutoField(primary_key=True) padre_idpadre = models.ForeignKey('Padre', models.DO_NOTHING, db_column='padre_idpadre', blank=True, null=True) curso_idcurso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='curso_idcurso') nombre = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'alumno' class Curso(models.Model): idcurso = models.IntegerField(primary_key=True) nombrecurso = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'curso' class Padre(models.Model): idpadre = models.AutoField(primary_key=True) socio = models.NullBooleanField(blank=True, null=True) nombre = models.CharField(max_length=45, blank=True, null=True) primerapellido = models.CharField(max_length=45, blank=True, null=True) segundoapellido = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'padre' This is my Form in forms.py: class AlumnoForm(forms.ModelForm): padre = PadreModelChoiceField(queryset=Padre.objects.all(), initial=**XXXXXXXXX**) #I would like to init here with the value of the FK curso = CursoModelChoiceField(queryset=Curso.objects.all(), initial=**XXXXXXXXXX**) #And here too class Meta: model = Alumno fields = ('nombre','padre','curso',) labels = { 'nombre': 'Nombre', 'padre': 'Padre', 'curso': 'Curso', } What should I write in the part XXXXXXXXXX of the code. It could be misconception but I'm think is a common operation, althought I don't find it. -
Django virtualenv avtivate < can't be found [on hold]
window10 64 virtualenv myvenv C:\Users\EY\myvenv\Scripts>activate < cant't be found 'activate'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다. and there no file 'activate' in directory scripts how do i activate virtualenv? -
Passing environment variables from apache via mod_wsgi to use in django 1.11 settings
Found a few versions of this question, such as Django get environment variables from apache, however the advice I've found so far doesn't seem to work with the latest LTS django (1.11). I have an apache configuration which holds a number of environment variables, not limited to connection credentials for the DB. Im using this to make my code portable between dev/prod etc. My apache conf just uses SetEnv to pass in some variables. I've tried two different styles of approach to use these variables, both seem to suffer from the same issue; it needs to read the settings file before we can write to the environment, and the settings file requires values from the environment. My two variants are; import os import django from django.core.handlers.wsgi import WSGIHandler from django.core.wsgi import get_wsgi_application _application = get_wsgi_application() def application(environ, start_response): for key in [keys...]: if environ.get(key): os.environ[key] = environ.get(key) return _application(environ, start_response) and import os import django from django.core.handlers.wsgi import WSGIHandler class WSGIEnvironment(WSGIHandler): def __call__(self, environ, start_response): for key in [keys...]: if environ.has_key(key): print "Key: %s = %s" % (key,environ[key]) os.environ[key] = environ[key] return super(WSGIEnvironment, self).__call__(environ, start_response) os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apiClient.settings') django.setup(set_prefix=False) application = WSGIEnvironment() Either way im trying to use the values in … -
Django cannot assign value, must be another instance
So I am simply trying to add LectureCategory in my Lecture model, I want the user to be only able to select between Classes or Seminars. If I put choices in both models, I can see them on django admin, but I get the error: Cannot assign "'0'": "Lecture.lecture_category" must be a "LectureCategory" instance. If I dont put choices in second model, then in admin panel will show 0 or 1, instead of my values. Any suggestion ? class LectureCategory(models.Model): lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) def __str__(self): return str(self.lecture_category) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', null=True, ) lecture_category = models.ForeignKey('LectureCategory', on_delete=models.CASCADE, default='', related_name='categories', choices=((0, "Classes "), (1, "Seminars"), ) ) -
How to create Django Model with Many-To-Many Parents-Children Relationship?
I already know, that I can achieve ForeignKey Parent-Children relationship within the same model, that allows to create relations with 1 parent = multiple children. But how can I accomplish Many-To-Many relationship within the same model ? At this moment I wrote and tested this: class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) parents = models.ManyToManyField( 'self', blank=True ) And it works, but not as I expected. What it does is: john = Person.objects.get(id=1) sam = Person.objects.get(id=2) >>> john.parents.all() <QuerySet [<Person: Alex>, <Person: Peter>, <Person: Sam>]> >>> sam.parents.all() <QuerySet [<Person: John>]> As you can see, Sam was supposed to be child of John, not his child and parent at the same time. What I want is to get John when I'm retrieving sam.parents.all() But not to get Sam when I'm retrieving john.parents.all() Is there a way to accomplish what I want ? Or that's not gonna work with this logic at least ? Do I have to create second separate model withing the same app ? -
Confusion about timezones oracle and django
I have django app running on ubuntu-14.04 and database is oracle. The timezones are as follow django- settings - TIME_ZONE = 'UTC' ubuntu - Asia/Kolkata oracle dbtimezone - UTC oracle sessiontimezone - Asia/Kolkata #this is via sqldeveloper While storing datetimes into db I am doing following. datetime.datetime.now(timezone.utc) Error I get is time can not be past. I don't want to change the code line. I can set the timezone of my Ubuntu or oracle as that is my development env. -
TypeError in django restapi
I was making a RESTFull API on Django. but when I run the server getting type error and I am not going the my desired url. although I have connected all classes with URLs -
Simplest way to periodically run a function from Django app on Elastic Beanstalk
Within my app i have a function which I want to run every hour to collect data and populate a database (I have an RDS database linked to my Elastic Beankstalk app). This is the function I want to want (a static method defined in my Data model): @staticmethod def get_data(): page = requests.get(....) soup = BeautifulSoup(page, 'lxml') ..... site_data = Data.objects.create(...) site_data.save() From reading it seems I want to use either Celery or a cron job. I am unfamiliar with either of these and it seems quite complicated using them with AWS. This post here seems most relvant but I am unsure how I would apply the suggestion to my example. Would I need to create a management command as mentioned and what would this look like with my example? As this is new to me it would help a lot it someone could point me down the right path. -
Django JSONWebTokenAuthentication not working for views
I am using rest_framework_jwt.authentication.JSONWebTokenAuthentication for my REST APIs . This is working fine for authentication but for my Skill view , I am able to hit the REST endpoint even though I am not passing any authentication token . How can i make my Skill API authenticated . Also I am new to Django so In the User view I do have a class , but for my Skill view i didnt found a correct example to have a class . Please help me with this . I have following view file : from rest_framework.permissions import IsAuthenticated @api_view(['GET']) def skill_collection(request): if request.method == 'GET': skills = Skill.objects.all() serializer = SkillSerializer(skills, many=True) return Response(serializer.data) @api_view(['GET']) def skill_element(request, pk): try: skill = Skill.objects.get(pk=pk) except Skill.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SkillSerializer(skill) return Response(serializer.data) Url file : urlpatterns = [ path('admin/', admin.site.urls), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^rest-auth/login/', include('rest_auth.registration.urls')), url(r'^refresh-token/', refresh_jwt_token), url(r'^user/$', DetailsView.as_view(), name='rest_user_details'), url(r'^', include('api.urls')), url(r'^api/v1/skills/$', wantedly_app_views.skill_collection), url(r'^api/v1/skills/(?P<pk>[0-9]+)$', wantedly_app_views.skill_element) ] -
Filter table based on function in django
I have a table which has a column A I want to filter table after applying some operation on A and filter the result of the operation with some value. What I want is something like this: MyTable.objects.filter(some_function(F('A'))=some_constant) Basically I want to calculate value of column A for each row based on some_function and filter the result of the function with some value. Any different approach for the solution is much appreciated. -
Is mongoengine is compatible to django 1.11.4 and latest mongodb?
I'm trying to find out any documentation for the compatibility of mongoengine with Django 1.11.4. Official Doc -
django form queryset multiple same field filter
Greeting, im trying to filter my user field queryset based on 3 department id, I'm able to filter a single department but when i try to filter multiple time its not working, can anyone help me with this thanks. below is my code : form.py class EditProjectForm(forms.ModelForm): prefix = 'edit_form' class Meta: model = Model_A fields = '__all__' def __init__(self, user, *args, **kwargs): super(EditProjectForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = Employee.objects.filter(department__id=18).filter(department__id=19).filter(department__id=20) -
Django rest framework API calling to another API
I have 2 django project API. What i am trying to do is django 1 api call to django 2 api to create and appointment (to do a get and post method) These are the 2 things i am currently 1. Djangp api 1 will do a get request to django api 2 to get a 200OK response first(for now is just doing testing for 200 status code). Django api 1 will do a post request to django api 2 to create an appointment, getting a queue number if success. I found an answer here: Calling a REST API from django view It is working for now but is it a good solution ? -
Filter the StringRelatedField data in Django rest framework
I'm trying to query two tables data with StringRelatedField method, it's working fine but it throws list of data. But i need to filter the data with some conditions. ex: Top most, recently created . Manually writing extra code it's possible but i need to do that by serializer itself. Can anyone help me with that thing. Below i added sample code. Models.py class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) class UserLog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id = models.ForeignKey(User, related_name='user_log', on_delete=models.CASCADE) Serilizer.py class UserDetailsSerializer(serializers.ModelSerializer): user_log = serializers.StringRelatedField(many=True) class Meta: model = User fields = ('id', 'first_name', 'user_log') -
Celery: Global SoftTimeLimitExceeded Handler function
I want to actually execute a function whenever a celery task exceeds it's allotted global soft time limit. I tried using on_faiure but it won't work as it works only upon FAILED tasks. Any suggestions? Thank You -
Django Beginner Forms, not able to get loop forms
I have a model name Fightmma and a model named Fightmmacard. Commentform works for Fightcard but not for Fightmma. Each fightcard is made of fights. When I comment on any fight, the last fight on the card gets the comment. My Commentform looks for the content type and the id. I am not able to pass the correct fight id to the Commentform properly. In my views it loop though the fights but the id is stored for the last fight only. My python isn't that great but I've been trying for 12 hours All help appreciated. models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from datetime import date from django.contrib.auth.models import User #Blog author or commenter from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id= obj_id) return qs class Comment(models.Model): author = models.ForeignKey(User) body = models.TextField(blank=True) post_date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() objects = CommentManager() class Meta: ordering = ["-post_date"] def __str__(self): """ String for representing the Model object. """ len_title=75 if len(self.body)>len_title: titlestring=self.body[:len_title] + '...' else: titlestring=self.body return … -
Customize Users inside Django Admin
I want to add some fields in Users section, apart from the predefined ones. I want to add a section called "Objectives" and also another called "Tests". How can I do this? -
Alternative to path() in Django 1.11
I have the following code in my URLs.py from django.conf.urls import url, include, path from django.contrib import admin urlpatterns = [ path('moraimono/', include('moraimono.urls')), path('admin/', admin.site.urls), however I found that path() is only included in Django 2.0 and I am using Django 1.11b1. How can I modify this code to make it work in Django 1.11b1 -
Djangae AppEngine misbehaves with IAP
Everything works fine when I use the Djangae appengine with Datastore (Django with datastore support) back-end but when I enable the Google Identity Aware Protocol (Google IAP) everything starts failing. When I checked the logs, It says that there was an IntegrityError in djangae_gaedatastoreuser on the field email_lower IntegrityError: Unique constraint violation for kind djangae_gaedatastoreuser on fields: email_lower The datastore kind has two empty entries in the email_lower field. Even the google.appengine.api.users module starts misbehaving. On first attempt to login, I can login to the AppEngine normally but I cannot logout of the appengine as a google account user, I see that I have logged out of my Google account(that's great but). When I try logging in, I see that no authentication was required to login (Google Sign In). When I login from another browser instance, It shows DatabaseError: save with update_fields did not affect any rows. Can someone please explain why this is happening and what I must do to avoid this. -
How to modify python source code using ubuntu on putty?
I am now running Ubuntu using putty, and try to modify a Django project using virtualenv. But I don't know how to open the source code. Please how to open source code and modify Thank you -
Django: Is it possible to run django without Nginx, gunicorn?
What I want to do is to run my django project on my desktop(Ubuntu 16.04) computer at my home. I have a Wi-Fi-router and use port-forwarding function to access other computer at my home by ssh. It also supports one free DDNS so I have a my own domain. Let say domain name is THIS_IS_MY_DOMAIN This is my idea : Run django on my desktop Set DEBUG=False, ALLOWED_HOST=["*",] in settings.py Run django by python super_crawler/manage.py runserver 0.0.0.0:8002 Port-forwarding on my Router : 8002(external) -> 8002(internal) When I run my django application, it shows like this in terminal: python manage.py runserver 0.0.0.0:8002 Performing system checks... System check identified no issues (0 silenced). January 19, 2018 - 17:38:03 Django version 1.11.8, using settings 'config.settings.production' Starting development server at http://0.0.0.0:8002/ Quit the server with CONTROL-C. Now I access some pages via other computer's browser with other network(from outside), and it shows like this: THIS_IS_MY_DOMAIN:8002/ => Not Found. The requested URL / was not found on this server. THIS_IS_MY_DOMAIN:8002/admin/ => Server Error (500) On my desktop, Nginx was off. I wonder whether I can run django ON MY DESKTOP in any other way. Must I use nginx, gunicorn? Edit Actually if I set DEBUG=True, …