Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-auth + allauth Facebook registration requires CSRF token
I am trying to build a register API using Facebook in my app. I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API from DRF browse-able API view and it is successfully performing the registration. When I try this API from somewhere else like postman it asks for CSRF token. I tried to use csrf_exempt decorator but that doesn't seem to be effective on this url. Here is my url config: url(r'^rest-auth/facebook/$', csrf_exempt(FacebookLogin.as_view()), name='fb_login'), Rest of the things are same as they mentioned in the documentation for django-rest-auth. I can't figure out what am I missing, or where should I look for a fix. Any help to diagnose the issue would be appreciated. -
HTML page not showing values
I a have a Python web app that sending parameter from the database to an HTML page when the page is loaded i cant see the result. I have check in the network tab in inspect mode and i can see the values are getting to the page . The parameter that are not presented in the page are: chaccount_id ,bank_name ,Company, seq_id This is my code : <form id="accounts_form" method="post" enctype="multipart/form-data"> {% csrf_token %} {% load staticfiles %} Account Number:<input list="accountslist" id="accounts_id" name="accountsname" value="{{ Account_id }}" > <button id="getacc_id" type="submit" name="getacc" value="commit">Get Account Details</button> <img id="GETACC_loading" src="{% static "app/images/small_loading.gif" %}" hidden> <br /> <br /> <br /><br /> <datalist id="accountslist"> <select id="accounslist" size="5"> {% for account in accounts %} <option value="{{ account.0 }}"></option> {% endfor %} </select> </datalist> </form> <table id="theTable" hidden> <thead> <tr> <td>Account id</td> <td>Bank Name</td> <td>Company Name</td> <td> Counter</td> </tr> </thead> <tbody> <tr> <td>{{ chaccount_id }}</td> <td>{{ bank_name }}</td> <td>{{ Company }}</td> <td>{{ seq_id }}</td> </tr> </tbody> </table> {% endblock %} {% block scripts %} <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script> $(function () { $('#getacc_id').click(function(evt){ acctoshow=document.getElementById('accounts_id').value; evt.preventDefault(); $('#GETACC_loading').show(); $.ajax({ type: "POST", url: 'Accountinfo', data: { 'acctoshow' : acctoshow, 'csrfmiddlewaretoken': '{{ … -
Django rest api: Postman can't get csrftoken cookie
I'm using django rest-framework api for user registration. This my curl command is: curl -i -H 'Accept: application/json; indent=4' -H 'Content-Type:application/json' -H 'Referer:https://domain' -X POST https://domain/users/:register/ -d "id=222111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames=" When I try it from cygwin is working properly and I get the csrftoken in cookies. This is the output: HTTP/1.1 200 OK Date: Thu, 26 Oct 2017 08:35:40 GMT Server: Apache/2.4.18 (Ubuntu) Allow: POST, OPTIONS Referer: https://domain/ Content-Length: 188 X-Frame-Options: SAMEORIGIN Vary: Accept,Cookie X-CSRFToken: MLJKNmBdYdF02ANX7pvZ7UavOVXtuPdW34vcF0RuLy94c1mQrL6blzkLMHCAFYkP Set-Cookie: csrftoken=sFkh2JjHxma3qnGpcRiOkQmH0xs9txqIJY6JUnzYkHE7AOfiwdT0yvwXYj7gEGxB; expires=Thu, 25-Oct-2018 08:35:40 GMT; Max-Age=31449600; Path=/ Content-Type: application/json { "isnew": "false", "user": { "firstname": "zinonas", "id": "222111", "lastnames": "Antoniou", "yearofbirth": 2007, "othernames": "" } } When I try the curl command in postman I get forbidden 403 error - CSRF token missing or incorrect. I have enabled postman interceptop and I set Referer header equal to https://domain. However I get the csrf cookie as can be seen in the image below: -
add NEXT_POST button to django template
i know that someone asked similar question but the answers didn't help me because i dont want to send the user to the next post, i want to send him to the next post in specific series. Models.py class Series(models.Model): title = models.CharField(max_length=100) tags = models.CharField(max_length=100) requirements = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=150) summery = models.CharField(max_length=100) body = MarkdownxField() # create/update info created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User) # Post info tags = models.CharField(max_length=100) series = models.ForeignKey(Series, blank=True, null=True) views = models.PositiveIntegerField(default=0) votes = models.PositiveIntegerField(default=0) def __str__(self): return self.title the button should appear in the post_detail template so the template contains the post and its fields if this will help in the answer thanks in advanced -
How to add another database server node in Django
I've a 2 databases which I've been running on a single machine. my question is how how can I add More database server along with that I wanna use django sharding so how can I shard my data from both database according to users means user 1 data from db1 and db2 on 1st server user 2's data on another -
Django: Fields of DeclarativeFieldsMetaclass (without instance)
I try to discover the fields which a django form class has. I only have a class, not an instance. The form-class is of type DeclarativeFieldsMetaclass. If I try this: class FooForm(forms.Form): spreadsheet = forms.FileField() for field in FooForm: print(field) I get this exception: TypeError: 'DeclarativeFieldsMetaclass' object is not iterable I know that I could do FooForm() instead of FooForm, but in my real use case I only have a class. -
How can I provide the Rest Framework API to intranet machine?
I use the rest framework write APIs, and when I runserver the website I can access the APIs in the development machine(the intranet ip is 10.10.10.111): But how can I access the API in other computer which is in the 10.10.10.0/24 intranet? If can, this will become more convenient for our team to debugging. -
Django form not showing in template
Why is the form not showing in the browser? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{ structure.name }} - Details</title> </head> <body> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <h3>Structure: {{ structure }}</h3> <h3>Ajouter enregistrement</h3> <form action="{% url 'Structure:addrecord' structure.id %}" method="post"> {% csrf_token %} {% for structure in all_structures %} <input type="radio" id="record{{ forloop.counter }}" name="record" value="record.id"> <label for="record{{ forloop.counter }}"> Nom de l'enregistrement: {{ record.record_name }} </label> {% endfor %} </form> </body> </html> When I test this in my browser, and inspect it, it gives me a form of this size: 1340px * 0 px. I even explicitly gave a style="height: 500px", but it still gives me an empty form. Here's a screenshot Thanks for the help guys! -
Speeding up chat bot replies in django python
I have made a chat bot in django python which listens via Http requests. Certain chat channels, such as slack, require an immediate 200OK http response from the server. Hence I register a celery task (into a queue) to return http 200OK instantly and let the reply be processed in background. It is taking 3-4 seconds in production (SQS based) for the bot's reply to be received by the end user. Through logs I have found out that the delay is in the task to reach the celery worker. I want to make my chat bot's replies to come really fast when a user types in a message and am looking for a faster alternative to celery for this specific use case. Thank you! Note that I do not want to use slack's RTM api because I do not intend to make my bot slack specific. -
Why not use enctype="multipart/form-data" always?
By change I discovered that the django admin interfaces uses enctype="multipart/form-data" always. I would like to adopt this pattern, but I am unsure if I see all consequences this has. Why not use enctype="multipart/form-data" always? -
Django migrations : relation already exists
I have trouble with django model migrations. I have some models in my app, and I already have some data inside. When I added some models in my application, and I run makemigrations, the app report that there is no change. I know that sometimes some errors came when migrate, so I delete django_migrations table in my database and run makemigrations again, and now program found my new fields. The problem now is that if I run migrate system tell me that some tables already exist. (Which is ok and correct, because they do). I don't want to delete those tables, because I have data already inside. I can't run migrate --fake, because program will think that I already have all the tables, which is not true. So, I am looking for a way to tell the program : run migration, if table exist skip it. (--fake it) Another question is why is this happening to me, that makemigrations don't recognise my changes (some cache problems,...)? -
Reseting URL in Django through views.py
I am using Python 3.6, Django 1.11 with Salesforce NPSP as my back-end. I have an issue, where-in I generate a User activation link URL & send mail to the user. Once user clicks & confirms, he will be logged-in & allowed to use the application. The url which I generate for mail activation is something like below, it has token values in it localhost:8080/naka/activation/abg479843fiuegf/hfduige433274 Once user clicks above url he will be taken to home page which is having url localhost:8080/naka/activation/abg479843fiuegf/hfduige433274/home.html I am looking to reset the above url as localhost:8080/naka/home.html Reason being it will be easy to access my other pages like localhost:8080/naka/aboutus.html localhost:8080/naka/contactus.html and so on I have added my view.py file which has activation method in it def activate(request, uidb64, token): context=locals() try: uid = force_text(urlsafe_base64_decode(uidb64)) user = uid except(TypeError, ValueError, OverflowError): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') return render(request,'home/home.html',context) #return HttpResponseRedirect('http://localhost:8000/naka/home.html') else: return HttpResponse('Activation link is invalid!') I have also added a line from my urls.py file related to activation url(r'^naka/activate/(?P[0-9A-Za-z_-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), kindly suggest. -
Make_Password returning different hash value for same password
i don't want to use django default user table so i created a user table with username and hashed password. I hashed the password with make_password() when posting to database but when i tried retrieving information from the database using the same method to hash user input password, i get a different hash for same password. below is the view code for saving the user and retrieving the details. view.py class HMUser(APIView): def post(self, request): request.data['password'] = make_password(request.data['password']) print(request.data['password']) serialize = serializers.HMUserSerializer(data=request.data) if serialize.is_valid(): serialize.save() return Response(1, status=status.HTTP_201_CREATED) return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST) class Login(APIView): def get(self, request, username, password): print("pass ", password) userpassword = make_password(password) print("Hash", userpassword) user_details = models.HMUser.objects.get(username=username, password=userpassword) serialize = serializers.HMUserSerializer(user_details) return Response(serialize.data) -
Handling objects differently based on dates in Django Template
I am in the process of building out a timeline for a list of objects. The model is simply laid out as follows: class Note(models.Model): added_by = models.ForeignKey(User) context = models.TextField() timestamp_added = models.DateTimeField(auto_now_add=True) And I plan to use this to create a timeline passing the following through: notes = Note.objects.all() However, to make things a bit cleaner, I would like to put a header for each date and then show all events for that date. Something as follows in my view: <ul class="timeline"> <!-- timeline time label --> {% for note in notes %} {% if note.timestamp_added is first %} <li class="time-label"> <span class="bg-red"> {{note.timestamp_added|date:"D m, Y" }} </span> </li> {% endif %} <li> <i class="fa fa-envelope bg-blue"></i> <div class="timeline-item"> <span class="time"><i class="fa fa-clock-o"></i> {{note.timestamp_added}}</span> <h3 class="timeline-header"><a href="#">{{note.added_by}}</a> added note</h3> <div class="timeline-body"> {{note.context}} </div> </div> </li> {% endfor %} </ul> However, is there an appropriate way to write an if statement here based on first instance of the date? -
Unable to execute fabric script for vagrant box
I am trying to run a fabric script which is uploading data in a postgres database in a vagrant box. The same script was running fine a couple of months ago and nothing was changed. But this time when I execute the script from my host machine as: ./pipeline-import.sh But then I get a strange behavior. First I am requested to enter a password for the vagrant user, while before I was never requested. After I put the default pass: vagrant I get these errors: Loaded environment from env/dev.yml [localhost:2222] Executing task 'pipeline_sql_schemas' Continue (y/n)? y [localhost:2222] sudo: echo 'CREATE SCHEMA IF NOT EXISTS gaul;' | PGPASSWORD='xxxx' psql -U user -d user_db [localhost:2222] Login password for 'vagrant': No handlers could be found for logger "paramiko.transport" Fatal error: No existing session Underlying exception: No existing session Aborting. -
How to make js/javascript retrieve the specific html option value inside a django python forloop
So I want to get the option currently selected on my looped option value, but it only keeps getting the last index of the loop whenever I press submit. specific code inside my "admin.html" The loop is for listing all the users who aren't inside the specific group <label class="control-label col-md-3 col-sm-3 col-xs-12">Add Members:</label> <div class="col-md-8 col-sm-6 col-xs-12"> <select name="employeeName" id="employeeLocation" class="select2_single form-control" tabindex="-1"> {% for user in users %} {% ifnotequal user.profile.group.id groups.id %} <option name="userGroup" id="userGroup-{{ user.id }}" value="{{user.id}}">{{user.username}}</option> {% endifnotequal %} {% endfor %} </select> </div> javascript code <script> function editGrpAjax(id,groupid){ var newid = document.getElementById(id).value; var newgroupid = document.getElementById('groupid-' + groupid).value; $.ajax({url: 'http://127.0.0.1:8000/editGrp/?pkid='+ newid + "&groupid=" + newgroupid, success: function(result){ // insert success message here } }); } </script> It keeps getting the last value of the loop, and not the one that is currently selected or highlighted in the option value upon submit. -
Pycharm : Process finished with exit code -1
I am using PyCharm 2017.1.3 and got an unexpected error Process finished with exit code -1 Can anyone please explain this ? -
Celery doesn't found postgres container
I use django and celery in my project with docker. In docker, i have three containers: app, celery, postgres In the celery task, when i tried to get a model: @app.task def test(): Model.objects.get(pk=1) , i had this error: Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? That error comes from the celery container. If i remove this lodel call, everything works well. The postgres container is at port 5432, it works well with app container. I thought that maybe because when the celery task executes, the task itself is not part django project, so it doesn't have the right configuration. I tried django-celery, but had the same error. -
Django data submission, verification by different group of users
In django, I have to create a system such that, certain group of users submit data which are then reviewed and approved by certain higher privileged group of users and then only updated to the central database. Data submission is done by forms. How can I implement this type of system in django? -
Beginner Docker-Compose & Django
I'm reading through the Docker Compose docs and have a question about the first code example under the heading: Create a Django project To create a new django project, it states that you should run the following line of code: docker-compose run web django-admin.py startproject composeexample . What I'm not understanding is why we should run this command in the context of docker-compose run. It's still creating the folder on our local machine. So why are we going through docker-compose to do this? -
How can I filter out the data that for root model?
From the post: Django rest framework - filtering for serializer field I can filter out the serializer-field that meet a condition, but, How can I filter the root serializer's field that meet a condition? I have models: class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) is_active = models.BooleanField(default=True) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() is_active = models.BooleanField(default=True) class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) class Track3(models.Model): track = models.ForeignKey(Track, related_name='track3s', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() is_active = models.BooleanField(default=True) class Meta: unique_together = ('track', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) And I have serializers: class Track3Serializer(serializers.ModelSerializer): class Meta: model = models.Track3 fields = ('order', 'title', 'duration') class TrackSerializer(serializers.ModelSerializer): track3s = Track3Serializer(many=True, read_only=True) class Meta: model = models.Track fields = ('order', 'title', 'duration', 'track3s') class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SerializerMethodField('get_active') # TrackSerializer(many=True, read_only=True) def get_active(self, album): qs = models.Track.objects.filter(is_active=True, album=album) serializer = TrackSerializer(instance=qs, many=True) return serializer.data class Meta: model = models.Album fields = ('album_name', 'artist', 'tracks') and in the views: def a_list(request): if request.method == 'GET': albums = models.Album.objects.all() serializer = serializers.AlbumSerializer(albums, … -
How to serialize several fields from different models without foreign key in django-rest-framework?
For better performance, I choose to give up foreign key in my codes. So I use employee_id to relate the two tables. from django.db import models from datetime import datetime Class Person(models.Model): employee_id = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=50) Class BussinessTrip(models.Model): employee_id = models.CharField(max_length=20) city = models.CharField(max_length=50) leave_time = models.DateField() back_time = models.DateField(null=True, blank=True) is_latest = models.BooleanField(default=True) add_time = models.DateTimeField(default=datetime.now) Now I need to get the latest trip infomation of all people by unique employee_id [ { employee_id: 'A', name: '', city: '', leave_time: '', is_latest: True }, { employee_id: 'B', name: '', city: '', leave_time: '', is_latest: True }, ... ] How can I serialize the models in this format? from rest_framework import serializers class PersonBussinessTripSerializer(serializers.Serializer): // How can I match employee_id between the two models to get my serializer? The problem makes me confused. Can it be easily achieved? -
QueryDict getlist returns empty list
I'm sending from frontend object with one property which equal to array. In backend I need to get data from that array. when i write request.POST i see: <QueryDict: {u'response[0][doc_id]': [u'14'], u'response[1][uuid]': [u'157fa2ae-802f-f851-94ba-353f746c9e0a'], u'response[1][doc_id]': [u'23'], u'response[1][data][read][user_ids][]': [u'9'], u'response[0][uuid]': [u'8a0b8806-4d51-2344-d236-bc50fb923f27'], u'response[0][data][read][user_ids][]': [u'9']}> But when i write request.POST.getlist('response') or request.POST.getlist('response[]') i get [] request.POST.get('response') doesn't work as well (returns None). What is wrong? -
FB.UI dialog is not appearing in the django application
I am trying this for the sharing of post on the facebook: <div id="shareBtn" class="btn btn-success clearfix">Share Dialog</div> <p>The Share Dialog enables you to share links to a person's profile without them having to use Facebook Login. <a href="https://developers.facebook.com/docs/sharing/reference/share-dialog">Read our Share Dialog guide</a> to learn more about how it works.</p> <script> document.getElementById('shareBtn').onclick = function() { FB.ui({ display: 'popup', method: 'share', href: 'https://developers.facebook.com/docs/', }, function(response){}); } </script> I want to know what is missing owing to which my application is not getting the sharing dialog. Here is the console error I found: (index):292 Uncaught ReferenceError: FB is not defined at HTMLDivElement.document.getElementById.onclick ((index):292) -
Error when running migrate command Django
I am trying to deploy my first web project on a server. I am getting this error when running migrate and makemigrations: ProgrammingError (1146, "Table '<user>$<dbname>.<table_name>'' doesn't exist") Everywhere it says that you should run manage.py syncdb but this is obsolete , also when running manage.py --run-syncdb the same error is given. models class Book(models.Model): name = models.CharField(max_length=350) author = models.CharField(max_length=350) category = models.CharField(max_length=200) def __str__(self): return self.name snipppets from settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<your_username>$<your_database_name>', 'USER': '<your_username>', 'PASSWORD': '<your_mysql_password>', 'HOST': '<your_mysql_hostname>', } } #Everything is replaced with the correct credentials INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app', 'accounts', ] The DB is empty on the server. On my PC (when I developed it locally) it worked, it created the table for me when it didn't exist in the DB. I am using Django 1.11 and Mysql 5.6.27. I tried other answers but did not help me. Can you please suggests what can I do to solve this issue?