Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got InvalidClientIdError (invalid_request) Mismatching redirect URI. using requests_oauthlib
I am trying to simulate token exchange between consumer and provider (server_to_server) using library requests_oauthlib. I getting error after I receive the code after authorization at provider side and exchanging the code for the token. So I get my code in my callback function but it is saying that redirect uri doesn't match. I already checked Redirect uri in provider's DB. They are the same. (as variable redirect_uri in code below) See my Django implementation: views.py # create session from importlib import import_module SessionStore = import_module(settings.SESSION_ENGINE).SessionStore session = SessionStore() client_id = "123456" client_secret = "123456" authorization_base_url = 'http://localhost:8000/o/authorize/' token_url = 'http://localhost:8000/o/token/' redirect_uri = 'http://localhost:8888/callback' # ONLY FOR A LOCALHOST import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' def index(request): provider = OAuth2Session(client_id, redirect_uri=redirect_uri) authorization_url, state = provider .authorization_url(authorization_base_url) # state is used to prevent CSRF, keep this for later. session['oauth_state'] = state # redirect to provider return redirect(authorization_url) def callback(request): # handles code from provider and redirects to profile page redirect_response = request.build_absolute_uri() # (http://localhost:8888/callback?code=123456&state=SomeStateCode) state = session.get('oauth_state') laas = OAuth2Session(client_id, state=state) token = laas.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) # here is mismatch error session['oauth_token'] = token return HttpResponseRedirect(reverse('app:profile')) def profile(request): # shows access token if existing if session.get('oauth_token') is not None: return HttpResponse("Token: " … -
Django Rest: Add data to a "required" field automatically
I want to automatically assign a value for a required field in django rest framework, without the value having to be given in the post request. My View: class WaitercallCreate(CreateAPIView): serializer_class = WaitercallCreateSerializer permission_classes = (IsAuthenticated, ) The Serializer: class WaitercallCreateSerializer(serializers.ModelSerializer): class Meta: model = Waitercall fields = ('order', 'user', 'done', 'type_of_call') read_only_fields = ('user', 'done') Users should be able to do a postrequest, only giving their token in the header and the order id as the body. I want to set the value for user by default to the requests user. I tried overwriting the perform_create method in my view like this: def perform_create(self, serializer): serializer.save(user=self.request.user) This didn't work. Then I tried overwriting the create method in the view like this: def create(self, request, *args, **kwargs): data = request.data data['user'] = request.user serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Which also didn't work, because Orderdicts are immutable. For the first (and the last try, read further) I allways get the same response: { "user": [ "This field is required." ] } Lastly I found this stackoverflow post, which recommends overwriting the create method in the serializer. Like this: def create(self, validated_data): print(self.context['request'].user) validated_data['user'] = … -
django pagination "That page contains no results"
I want to use django pagination. The first page able to load products but last page not showing. my index view here def index(request): categories = Category.objects.filter(parent_category=None) product_list = Product.objects.filter(is_deleted=False).order_by('created_at') paginator = Paginator(product_list, 1) # Show 25 contacts per page page = request.GET.get("page",1) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(1) context = { 'products': products, 'categories': categories } return render(request, 'product/urunler.html', context) here is .html <div class="blog-pagination"> <ul class="flat-pagination style1"> {% if products.has_previous %} <li class="prev"> <a href="?page={{products.previous_page_number}}" title=""> <img src="{% static 'images/icons/left-1.png' %}" alt="">Önceki Sayfa </a> </li> {% else %} <li class="prev"> <a href="#" title=""> <img src="{% static 'images/icons/left-1.png' %}" alt="">Önceki Sayfa </a> </li> {% endif %} {% for i in products.paginator.page_range %} {% if products.number == i %} <li class="active"> <a href="?page={{i}}" class="waves-effect" title="">{{i}}</a> </li> {% else %} <li> <a href="?page={{i}}" class="waves-effect" title="">{{i}}</a> </li> {% endif %} {% endfor %} {% if products.has_previous %} <li class="next"> <a href="?page={{products.next_page_number}}" title=""> Sonraki Sayfa <img src="{% static 'images/icons/right-1.png' %}" alt=""> </a> </li> {% else %} {% if products.has_next %} <li class="next"> <a href="" title=""> Sonraki Sayfa <img src="{% static 'images/icons/right-1.png' %}" alt=""> </a> </li> {% endif %} {% endif %} </ul> <div class="clearfix"></div> </div> … -
Why null field for foreign key?
Using django 1.11 I am using an API backend for a django accounts project. The following is an example of a class: from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.conf import settings import datetime class Credit(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=200) payment_reference = models.IntegerField() amount = models.IntegerField() payment_type = models.CharField(max_length=200,default='Paypal') country = models.CharField(max_length=200,default='Ireland') payment_location = models.CharField(max_length=200,default='On-site') date = models.DateTimeField(auto_now_add=True) The standard user was over-written in another app called profiles and I have included this in settings.py - 'AUTH_USER_MODEL = 'profiles.User' from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from django.utils import timezone # Create your models here. class Profile(UserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): objects = Profile() When I try to run makemigrations however I am told that I am trying to change the nullable field 'user' to non-nullable without a default. Why would I need a default if im making reference to the active user? I want the foreign key value to be … -
Django: Correct request to database to calculate DAU
Could someone find a mistake(s) in my request to the database in Django? So, I have the next model: class GameEvent(models.Model): game = models.ForeignKey(Game, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) app_id = models.CharField(max_length=255, blank=False) datetime = models.DateTimeField(blank=False) def __str__(self): return u"%s [ %s ]" % (self.game.title, self.name) @receiver(models.signals.pre_save, sender=GameEvent) def update_datetime(sender, instance, **kwargs): instance.datetime = datetime.datetime.now() I create the record in the database each time when my game sends me some event like:level complete, level failed etc. To recognize which copy of application sends me the events the copy has unique app_id. So the question is how to calculate DAU. I make the next request to database but it returns wrong answer: dau = GameEvent.objects.filter(game = game, datetime__gte = date_start, datetime__lte = date_end) .extra({'date' :'date(datetime)'}) .values('date') .annotate(count=Count('app_id', disntict=True)) .order_by('date') If I choose date range for one day it returns dau[0].count = 1200, but the next request which calculates the count of unique app_id returns 100: app_ids = GameEvent.objects.filter(game = game, datetime__gte = date_start, datetime__lte = date_end) .values_list('app_id', flat=True).distinct() So, where is mistake? Thanks for helping -
Django template doesn't render models as I would expect
So I have this Lecture class. Now for this class, I have 2 choices: "Classes" and "Seminars", and I want that each time I add a lecture to either one, the template will shows firstly the choice and then all the lectures. Example: Classes will have Lecture1, Lecture2, Lecture3 etc. Problem is that right now when I iterate, choice shows each time, for every lecture and I want each choice to show only ONCE. class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) lecture_title = models.CharField(max_length=100) content = models.TextField() link = models.URLField(blank=True) file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.lecture_title <ul> {% for c in lectures %} <b>{{ c.get_lecture_category_display }}</b> <p>.......................</p> <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} <hr/> </ul> -
Use a model field to query another model field in django
I have two models in our django app class Reg(models.Model): transactions = ManyToMany price = IntegerField class Transaction(models.Model) amount = IntegerField Now I would like to make a lookup like: Registration.objects.filter(reg__price==transaction__amount) Previously we used the following approach: Registration has a property is_paid that computes wether a transaction with equal amount exists [r for r in Registration.objects.filter(...) if r.is_paid] This is ofc very query-consuming and inefficient. I wonder whether there would be a better way to do this! Any hint is appreciated :) -
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')