Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rest-auth use cookie instead of Authorization header
I want to build the SPA application using Django Rest Framework as a back-end. The application will use Token authentication. For maximum security, I want to store the authentication token inside of httpOnly cookie, so it will not be accessible from javascript. However, because the cookie is not accessible from the javascript, I am not able to set the 'Authorization: Token ...' header. So, my question is, can I make the DRF auth system (or Django-Rest-Knox/Django-Rest-JWT) to read the authentication token from the cookie instead of reading it from the "Authorization" header? Or the "Authorization" header is the only and correct way to authenticate in DRF? -
Upload files using a random folder name in django
I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name. So far I can upload both files to different random folders using the following: from uuid import uuid4 def path_and_rename(path, dataset): def wrapper(instance, filename): main_folder = '{}/{}/'.format(path, uuid4().hex) name = '{}.csv'.format(dataset) return os.path.join(main_folder, name) return wrapper class Dataset(Model): trainFile = FileField(null=False, blank=False, validators=[FileExtensionValidator(['csv'])], upload_to=path_and_rename('files/', 'train')) testFile = FileField(null=False, blank=False, validators=[FileExtensionValidator(['csv'])], upload_to=path_and_rename('files/', 'test')) class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ( 'id', 'trainFile', 'testFile', ) read_only_fields = ('created',) How could I get both files to be uploaded to the same random folder? -
Django: Unable to get user's groups from LDAP user
My Django ( Django 1.11) project is using django-auth-ldap 1.2 as authentication backed. I have no problem to authenticate any user agents LDAP database using: @login_required(login_url='/accounts/login/') and in this case, any user from any group can login to the site. I want to allow only user from 'group1' to be able to access the website. I used the code listed below from django.shortcuts import render from django.template import loader from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views @user_passes_test( lambda u: hasattr(u, 'ldap_user') and 'group1' in u.ldap_user.group_names, login_url='/accounts/login/') def index(request): template = loader.get_template('main/index.html') return HttpResponse(template.render()) This is code is not working and user will never pass the test. According to the model documents django-auth-ldap Document I can use ldap_user.group_names to get group names of a user. Here is my ldap settings from settings.py: import os import django AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',) import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTH_LDAP_SERVER_URI = "ldap://mydomain.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=mydomain,dc=com" AUTH_LDAP_BIND_PASSWORD = "mypass" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=ou_org_unit,dc=mydomain,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=ou_org_unit,cn=group1,cn=group2,dc=mydomain,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 My question is: Why I am … -
creating a many to one relationship in django with an existing model
How can I create a many to one relationship with an existing model in django? Looking at the documentation, You can see that you can create a foreign key and create and object with a reference to the other model. For example, r = Reporter(first_name='John', last_name='Smith', email='john@example.com') r.save() a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r) a.save() You can then access the id of r with a.reporter.id. One problem with this, however is that if you wanted to check the id of r through a, you have to create a in order to do it. How would you do this with an already existing model? As an example, if I have a user and I want the user to be able to create multiple characters for a game, how can I assign the character a foreign key to the user if the user already exists? Looking at this answer, you see that you need to give the model that you want to reference to the foreign key, but it doesn't actually explain how to do it. -
How to select all elements of an input in javascript or jquery
I would like to select all elements of an input and make a comparison, be it in javascript or jquery. This input has the same id and same name. I know that getelementbyid will only return the first element, but I want all elements of this input -
How to add edit and delete buttons in django admin
I want to add 2 buttons in django admin, like on this screenshot, but instead of "Deposit" and "Withdraw" there should be "Edit" and "Delete" I found lots of answers how to add custom actions, but is there a proper way to add such buttons? All methods for them are written, it seems to me that this two buttons should be added mush more easier. -
MDBootstrap dropdown returns None in Django
I'm using MDBootstrap for my project and in the form, one of the field is a dropdown Select. I can render the field in my templates and even dynamically populate values, but when I submit, it posts as None. Could anyone please help me here? Here's my code: Forms.py class NewPersonForm(ModelForm): class Meta: model = Person fields = ['status', 'title', 'company_name', 'industry'] # Status is a dropdown select field Templates (The form is really huge, so this is just the relevant field) <form method="post" name="create_form" action="{% url 'person_home' %}"> {% csrf_token %} <div class="md-form" style="margin-bottom: 35px"> <select class="mdb-select"> {% for value, option in person_form.status.field.choices %} <option value="{{value}}">{{option}}</option> {% endfor %} </select> <label>{{person_form.status.label}}</label> </div> </form> Views.py def person_home(request): ctx = {'title': 'Person', 'active_tab': 'person'} if request.method == 'POST': person_form = NewPersonForm(request.POST) if person_form.is_valid(): raise Exception(person_form.cleaned_data['status']) # Returns None else: ctx['person_form'] = person_form return render(request, 'profile/person.html', ctx) But if I were to do it the regular way, without the MDB classes, by just saying this in my template, that works fine. I can get the status value. The MDB way though isn't working. What could be the reason? <form method="post" name="create_form" action="{% url 'person_home' %}"> {% csrf_token %} {{person_form}} <button class="btn btn-primary" … -
How can I get POST data from $http request?
I'm using Angular and Django and am trying to use a POST to write data to my database. It seems like the documentation is very unclear about how to transfer information between the two without creating a massive querystring. I'm currently just trying to read the message in the post and I can't even get that far, here's the code... Js: $('#datasubmit').on('click', function(){ $http({ method: 'POST', url: '/postdata/', params: 'hi=2', body: 'hi=2' }); }); Views.py def postdata(request): if request.method == 'POST': print('ISSA POST') print(request.POST) return HttpResponse('hi') I understand some things like the http response and params in the $http don't make any sense, but they are just there so I don't have errors while doing this. I'm not sure what I need to label in my $http to be able to then read in the request.method in python. EDIT: I've handled the CSRF issues so at this point print(request.POST) is giving me an empty querydict -
GEt number of users registered on a specific day
I am trying to get number of regisetered users grouped by day but so far failed. class Profile(models.Model): createdon=models.DateField() the following raw sql works fine: SELECT COUNT(day(createdon)),day(createdon) from members_profile where month(createdon)=11 and year(createdon)=2017 GROUP BY day(createdon) The output now is: 1 10 5 8 In ORM, the closest i came was: Profile.objects.extra({'d':"day(createdon)"}).values('d').annotate(count=Count('id')) 1 1 5 1 5 1 But that doesn't surprise it since id is unique field. I instead want to group by 'd', which annotate column complains can not be resolved. -
Django: Python path syntax to my custom validators.py?
I want to implement the solution detailed in this thread but I can't for the life of me figure out the Python path syntax in settings.py needed to link back to my custom validators.py I'm not even sure where to put it. I feel like a simple explanation of how the Python path syntax works in Django ought to be in the docs but after almost 20 minutes of looking through them I don't see anything. Any help would be greatly appreciated. -
Create Django RESTful service for execute an algorithm
I need to implement a Django RESTful service where I can run an algorithm and get the result. On the server I need to have a CSV file with the records for the algorithm. A service, let's say /train will allow me to train a Random Forest with the data in the CSV file, and finally another service /predict will receive the parameters and send me the result. The problem is that I have this running as a script on my computer and I don't know how to structure it for a web application. I have already done RESTful APIs in Django but this problem is different I think. I won't need models? What about the serializers? My idea is to send a GET request to /predict with the parameters needed for the Random Forest and return the algorithm result. Any suggestions? Or a public repo with a similar problem? -
Installing Django on Ubuntu 16.04, python3
I am unable to install django on python3 in ubuntu 16.04. Here is what I have tried: 1. pip3 install django 2. pip3 install --trusted-host pypi.python.org django 3. pip3 install --index-url=http://pypi.python.org/simple --trusted-host pypi.python.org django I keep getting the same error: Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django I have Django installed on python 2.7, but I need it on python 3.6. When I run sudo apt-get install python3-django it says python3-django is already the newest version (1.8.7-1ubuntu5.5). I believe this is because I have python3.5 installed with Django on python3.5, but I need it on 3.6. Python3 refers python3.6. Any help is appreciated. -
Update Model Instance via Django REST POST
I've got a model "Assignment" that I want to be able to update through the api. urls.py router = routers.DefaultRouter() router.register(r'assignments', views.AssignmentList, base_name='Assignments') urlpatterns = [ url(r'^api/v1/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py class AssignmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Assignment fields = ( 'id', 'company_id', 'farm_id', 'sensor_id', 'name', 'location', 'notes', 'units', 'max_height', 'frequency', 'interval', 'max_threshold', 'min_threshold', 'notify', 'last_alert_time', 'last_alert_water_level') views.py class AssignmentList(viewsets.ModelViewSet): serializer_class = AssignmentSerializer pagination_class = None def get_queryset(self): queryset = Assignment.objects.all() company_id = self.request.query_params.get('company_id', None) sensor_id = self.request.query_params.get('sensor_id', None) if company_id is not None: queryset = Assignment.objects.filter(company_id=company_id) if sensor_id is not None: queryset = Assignment.objects.filter(sensor_id=sensor_id) return queryset Currently my view allows for easy filtering based on two of the fields, 'company_id' and 'sensor_id'. This allows for easy access of the data in json. Unfortunately I can't figure out how to POST back even with the built in API form. I would like to be able to filter down to a single instance and edit a single field, let's say "assignment.name" for now. It's my understanding that... The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). (DRF Docs) So what do I need to do to leverage them to edit a model instance … -
Selecting the outer div based on inner input type
I have the following html for a user to input information when registering a new account: <span class="label"><label for="id_email">Email address:</label></span> <div class="editable-input-box-container"><input id="id_email" maxlength="254" name="email" type="email" /></div> <span class="label"><label for="id_phone_number">Phone Number:</label></span> <div class="editable-input-box-container"><input id="id_phone_number" name="phone_number" type="text" /></div> <p class="help-text">xxx-xxx-xxxx</p> <span class="label"><label for="id_can_help">Can provide extra help:</label></span> <div class="editable-input-box-container"><input id="id_can_help" name="can_help" type="checkbox" /></div> <p class="help-text">Would you be willing to provide your help if needed?</p> What is currently displayed is a nice registration template: But the checkbox is aligned left, when instead I want it to align right with the title "Can provide extra help:". However, when I select the checkbox using input[type="checkbox"] in my CSS, it targets only the input element and right aligns it within the div, which does not right align on the page. Is there a way to select the outer editable-input-box-container div based on the inner input being a type checkbox, so that I can right align it? -
Django Form Class
I designed a job vacancy page that list all available vacancy advertised, each listed job vacancy is linked to a detail page that explains more about the position. I added a register button that links to a form page where the user can apply for the position. On the form page, the user has to select the position from the list of advertised position. How can i design the form page in a way the user will not need to select the position from the list of advertised positions,but rather the position will automatically save on the database table as the user register for that position. Below is my view.py class CareerApplicationCreate(CreateView): template_name = 'library/careerForm/careerForm.html' model = CareerApplication form_class = CareerApplicationForm success_url = '' def get_context_data(self, **kwargs): context = super(CareerApplicationCreate, self).get_context_data(**kwargs) context['neew'] = NewsPage.objects.filter(is_visible = True) return context def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset1 = EducationExperienceFormSet() formset2 = WorkExperienceFormSet() formset3 = RefereeFormSet() formset4 = UploadDocumentFormSet() authenticated = request.user.is_authenticated() if authenticated == True: username = request.user.username return self.render_to_response(self.get_context_data(form=form, formset1=formset1, formset2=formset2, formset3=formset3, formset4=formset4, authenticated=authenticated, username=username)) else: return self.render_to_response(self.get_context_data(form=form, formset1=formset1, formset2=formset2, formset3=formset3, formset4=formset4, authenticated=authenticated)) return self.render_to_response(self.get_context_data(form=form, formset1=formset1, formset2=formset2, formset3=formset3, formset4=formset4, authenticated=authenticated, username=username)) -
Is it possible to build a portable webapp when using oracle with django
I started developing a django webapp which will need to connect to oracle databases. But using oracle with django requires an Oracle client if I'm not mistaken which is platform dependant. If it's not possible to create a portable webapp with django and oracle, could the app use an oracle client install on the machine where the app is running? Thanks -
Cannot debug error message for psycopg2 with django and postgreSQL
I am trying to create a postgreSQL database connected to a django web app using psycopg2. I am recieving the following error when I run python manage.py migrate (temp-python) ❯ python manage.py migrate Traceback (most recent call last): File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "~/git-repos/MyApp/connecting/models.py", line 2, in <module> from django.contrib.auth.models … -
Casecading dropdown on admin site in django
The level has two option(B.Sc and M.sc). I want to make a such like that when I select B.sc LEVEL, it shows 8 semesters in sem option.On the other hand, when I select M.sc level, it shows 2 semesters in sem option.How can I do this?? Anyone, please help. -
Celery workers unable to connect to redis on docker instances
I have a dockerized setup running a Django app within which I use Celery tasks. Celery uses Redis as the broker. Versioning: Docker version 17.09.0-ce, build afdb6d4 docker-compose version 1.15.0, build e12f3b9 Django==1.9.6 django-celery-beat==1.0.1 celery==4.1.0 celery[redis] redis==2.10.5 Problem: My celery workers appear to be unable to connect to the redis container located at localhost:6379. I am able to telnet into the redis server on the specified port. I am able to verify redis-server is running on the container. When I manually connect to the Celery docker instance and attempt to create a worker using the command celery -A backend worker -l info I get the notice: [2017-11-13 18:07:50,937: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Cannot assign requested address.. Trying again in 4.00 seconds... Notes: I am able to telnet in to the redis container on port 6379. On the redis container, redis-server is running. Is there anything else that I'm missing? I've gone pretty far down the rabbit hole, but feel like I'm missing something really simple. -
csv import into django models
My python csv import script creates an extra empty entry in the database model every time I load data. I have tried to work around various ways but I still get one empty entry plus the actual data am loading from the csv.Here is what my script is like. Please your help will be of great achievment. class CsvUploadView(LoginRequiredMixin, FormView): form_class = CsvAttendeeForm template_name = 'attendee/upload_attendee_csv.html' success_url = reverse_lazy('home') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) file = request.FILES.get('file') if form.is_valid(): if file: reader = csv.reader(file, delimiter=',') next(reader) attendee_instance = Attendee() Attendee.objects.bulk_create( [Attendee(firstname=row[0], surname=row[1], email=row[2], ) for row in reader]) attendee_instance.save() return self.form_valid(form) else: return self.form_invalid(form) -
Django - get param from request.get and add it with another number
I have following code. I want to get values from from request and add it to another float number. I tried this code but gives me error :unsupported operand type(s) for +: 'float' and 'NoneType' class RatingsUpdateView(UpdateAPIView): serializer_class = serializers.RatingsSerializer queryset = models.Ratings.objects.all() def update(self, request, *args, **kwargs): instance = self.get_object() #average = instance.total_number = instance.total_number + 1 instance.sum_of_all_ratings =instance.sum_of_all_ratings + request.data.get("rating_give_by_user") instance.save() Look at the line where i am getting value 'request.data.get("rating_give_by_user")_give_by_user'. This value us NoneType but i want to add it to another float number. What is the solution and best practice. Thanks. -
how to make payouts with bitcoin on django website?
I'm building a website with Django, python 3.5. And I need to get payments from users and make payouts. Can you recommend an application, payment gateway, or some article with some information about this? There is a lot of articles how to accept payments, but I can't find any of how to make payouts. -
Django doesn't load second page
I have just started Django, and I'm facing some difficulty. When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing. Here's my project's URL: from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^first_app/', include('first_app.urls')), ) App's URL: from django.conf.urls import patterns, url from first_app import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^about/', views.index, name='about'), ) And views.py: from django.http import HttpResponse def index(request): return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>") def about(request): return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>") I'm using Django 1.7 and python 2.7. Thanks. -
Access Many-to-Many field within Django template
I have the following blog project : models.py: from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) categories = models.ManyToManyField('Category') def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.category_name # Change the name in Admin from categorys to categories class Meta: verbose_name_plural = "categories" views.py: from django.shortcuts import render from .models import Post, Category, Comment def getPosts(request): posting = Post.objects.all().order_by('-pub_date') categories = Category.objects.all() context = { 'posting':posting, 'categories':categories, } return render(request, 'posts/getPosts.html', context) getPosts.html template : {% if posting %} {% for article in posting %} <h3>{{article.title}}</h3> <ul>{{article.body}}</ul> <ul>Posted : {{article.pub_date}}</ul> <ul> <em>Found in category : </em> {{ article.categories }} {% for category in categories %} {{category.title}} {% endfor %} </ul> {% endfor %} {% endif %} {{article.categories}} is giving me: posts.Category.None And the second loop outputs the list of all categories, which I expected as just a test run. I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel. I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), … -
Webhooks with Python and Django
I have a subscription model: class Subscription(models.Model): STATUS_CURRENT = ["trialing", "active"] plan_amount = models.CharField(max_length=120, null=True, blank=True) plan_id = models.CharField(max_length=120, null=True, blank=True) subscription_id = models.CharField(max_length=120) subscription_owner = models.OneToOneField(Provider, related_name='subscription') cancel_at_period_end = models.BooleanField(default=False) canceled_at = models.DateTimeField(blank=True, null=True) current_period_end = models.DateTimeField(blank=True, null=True) current_period_start = models.DateTimeField(blank=True, null=True) ended_at = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=25)# trialing, active, past_due, canceled, or unpaid def status_display(self): return self.status.replace("_", " ").title() def __str__(self): return self.subscription_id I also have the following stripe webhook set up and have no problems with that: @require_POST @csrf_exempt def subscription_cancelled_callback(request): # Process webhook data in request.body and parse it as JSON stripe_payload = json.loads(request.body) print('cancelled') return HttpResponse(status=200) What I am trying to achieve is update my subscription object for example update the status of the subscription in my backend with the json returned through the webhook, i.e "active" or "cancelled" New to using webhooks but not sure how to update the object from the webhook json. Any pointers would be a great help.