Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Able to add the same user multiple times to the another model
I have a model which adds(assigns) users to the academy (academy user), the issue is I am able to add the same user multiple times to the academy. What am I doing wrong here? class AcademyPlayer(models.Model): academy = models.ForeignKey(Academy, on_delete=models.CASCADE) player = models.ForeignKey('player.Player', on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.player.user.name -
Form not showing in Django app
I picked up a very very simple django challenge, but am having a problem with inputing details and submitting it into Database. My forms are not even showing talkless of inputing details, and I don’t know what am doing wrong. models.py class Users(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime from django.http import HttpResponseRedirect from .models import Users from .forms import UserForm def home(request): return render(request, 'pages/home.html', {}) def list(request): users = Users.objects.order_by('created_at').all() context = {'users': users} return render(request, 'pages/list.html', context) def add(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = User(name=request.POST['name'], email=request.POST['email']) user.save() return HttpResponseRedirect('/list/') return render(request, 'pages/list.html', {'form': form}) forms.py from django import forms from django.core.validators import validate_email from .models import Users class UserForm(forms.Form): name = forms.CharField(label='Name', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(label='Email', max_length=60, widget=forms.TextInput(attrs={'class': 'form-control'})) def clean_email(self): email = self.cleaned_data['email'] if Users.objects.filter(email=email).exists(): raise forms.ValidationError('Email already exists') return email add.html (Template): {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>Add user</h1> {{ form.non_field_errors }} <form name='form' method="POST" action="/add/"> {% csrf_token %} {% for field in … -
Generate symfony 2.4 password from Python/Django
I'm working on a project where i have to insert user into a database from a Python/django application. Those users authenticate themselves in a symfony 2.4 application so i have to generate a password that will be decrypted properly. The symfony project use the sha256 algorythm (as i can see in the security.yml file) Do you have some informations about the way symfony 2 encode the password with this algorythm ? (I know i have to build a salt and a hash) Thanks -
Postgres,Django:How to approve every insert into postgres table?
I'm working on a django application with postgres. I have a html form which takes user inserted data. As of now the data entered in the form is directly getting inserted into postgres table.But I want to add a step in between where the DBA should check the data from the form and then approve it for insertion. How can I do it ? Thanks in advance. -
Have to print the result one by one in django template
I have a json response like {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} I want to access this response one by one in django template -
if condition tag is not working properly
In demo.html <table class="table table-hover" style="width:80%;"> <tr> <th>Test Case</th> <th>File Name</th> <th>Coverage </th> </tr> {% for key, value in d.items %} <tr> <th>{{ key }} </th> </tr> {% for k,v in value.items%} {% if forloop.counter <= count1 %} <tr> <td> </td> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endif %} {% endfor %} {% endfor %} </table> if condition works only when i declare as {% if forloop.counter <= 2 %} Instead if i use variable as above mentioned code it does not work.Please to help me out what is the error in above code. As if use {{ count1 }} the value is printing correctly. -
How do I pass user_id into a Django method
I need to pass user_id (or a User object that will resolve to user_id) into a function - from both templates and other backend functions. The purpose is to first check if a token exists for the user and if not, then to appropriately call an external API to generate a token. My question is, how do I pass the user_id into the method? Django doesn't appear to have a clear user_id method in the User object and using Django auth I can't set username as the ForeignKey. class Token(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) provider_id = models.ForeignKey(Providers, unique=False, on_delete=models.DO_NOTHING) access_token = models.TextField() refresh_token = models.TextField() r_lasttime = models.DateTimeField expires_in = models.IntegerField token_type = models.TextField() @classmethod #check if a user / provider combination exists def token_exists(cls, user_id, provider_id): return cls.objects.filter(user_id=user_id,provider_id=provider_id).exists() @classmethod def new_token(cls, provider_id, user_id, access_code): # use to acquire a new access token and update it in the database # requires the front end to have already been provided an authorisation token called access_code # determine if the user / provider combination already exist if Token.token_exists(user_id, provider_id) == True: status = {'code': 400, 'desc': 'User/provider combination already exist. Use refresh instead'} return (status) # the user / provider combination does … -
How to configure cloud public server in Django 1.11?
I am working on django 1.11 whenever i try to write an application it default takes development server as 127.0.0.1:8000 localhost. Instead of running localhost i want to run cloud server in that application. I have Microsoft Azure account also i just want to configure with my ip address which running on cloud. so can anybody help me on this. Thanks & Regards, Gunasekaran J -
Django form not saving inputs- refreshes upon submission
I am trying to create a website with two dropdown menus: Department and Course Number. The data for the dropdown menus comes from the "courses" table of my SQL database. Right now my website initializes properly and shows the correct options in the dropdown menus. However, when the user selects an option within the dropdown menus and submits their choices, the website reloads as a blank slate so their selections are not being saved or processed. The error lies somewhere in the CourseForm form because I have another form (Working_Form) that is created in a different way but works perfectly. What is wrong with CourseForm/its associated models? models.py from django.db import models class Dept(models.Model): dept = models.CharField(max_length=255, db_column = 'dept') class Meta: managed = False db_table = 'courses' def __str__(self): return self.dept class Course_num(models.Model): course_num = models.CharField(max_length=255, db_column = 'course_number') class Meta: managed = False db_table = 'courses' def __str__(self): return self.course_num forms.py from django import forms from django_select2.forms import ModelSelect2Widget from .models import Dept, Course_num class CourseForm(forms.Form): dept = forms.ModelChoiceField( queryset=Dept.objects.distinct().\ order_by('dept').exclude(dept__isnull=True), required=False, empty_label="No preference", label=u"Department") course_num = forms.ModelChoiceField( queryset=Course_num.objects.distinct().\ order_by('course_num').exclude(course_num__isnull=True), required=False, empty_label="No preference", label=u"Course Number") views.py from django.shortcuts import render from django import forms from .models import Dept, … -
(Django) Cannot upload images for the users avatar
So I'm trying to make it possible for users to update their Avatar/Profile image by allowing them to upload their image + I want to implement an image cropper so they can crop the image to a ratio of 1 to 1. All tho I think the first thing is making it possible to upload. I've searched around trying to make it possible but I think I've almost been everywhere. The thing is the image field I'm using is like an extension to the User table I basically called it extendeduser that has all the extra information included in it. Media is set 2 i can upload files from the admin panel and they show normally. Views.py @login_required def useravatar(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() user.extendeduser.avatar = form.cleaned_data('avatar') user.save() messages.success(request, 'Your avatar was successfully Uploaded!') return redirect('useravatar', user_pk=request.user.pk) logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_user = get_object_or_404(User, pk=user_pk) driverslicence = DriversLicenceCategories.objects.all() feedback = FeedbackSupportForm() password = PasswordChangeForm(request.user) avatar = UpdateProfileForm(instance=request.user) context = { 'avatar' : avatar, 'logged_in_user': logged_in_user, 'requested_user': requested_user, 'feedback' : feedback, 'password' : password, } return render(request, 'user/avatar.html', context) Models.py class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=20) … -
how to handle new button in submit_line.html in django
i already create a class to validating xml file, and i try in actions its work but how i can make the script work in new button i create in submit_line.html this is my admin.py with actions class CrsFileAdmin(admin.ModelAdmin): list_display = ('fi', 'file', 'import_datetime', 'state') readonly_fields = ('state','import_datetime','log') actions = ['some_action','Validating'] def Validating(self, request, queryset): for crsfile in queryset: xsdfile = etree.parse("/home/.../.../.../ex.xsd") xsdpar = etree.XMLSchema(xsdfile) xmlfile = etree.parse(crsfile.file.path) result = xsdpar.validate(xmlfile) if result == True: crsfile.log = "Validate: Successfully validate" crsfile.state=CrsFile.CHECKED print("valid") else: crsfile.state=CrsFile.ERROR crsfile.log = xsdpar.error_log print(crsfile.log) crsfile.import_datetime=timezone.now() crsfile.save() self.message_user(request, crsfile.log) return crsfile.log Validating.short_description = "XML Validate" admin_site.register(CrsFile, CrsFileAdmin) and this new button i create in submit_line.html {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %} {% if show_delete_link %} {% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %} <p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p> {% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %} … -
How to make common authentication between 2 server - Rails & Django
the service I'm developing consists of chrome extension & web application. For it I'm trying to create 2 server: web application server (build by Rails) API server(build by Django) to receive requests from chrome extension and process user data. Those application use same database, same user information. My question is how to authenticate users -- in Rails app, users can sign-up and sign-in via form. But in API server, how to authenticate users? One solution might be JWT authentication, user get JWT token from Rails server and send token to Django server, and Django server authenticate by JWT authorization. Is that best practice -- or simply sending username & password is better then this? Thanks -
How to JSON parse using form.errors.as_json() in Django return JsonResponse(data)
In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings. {"password2":[{"message": "This password is too short. It must contain at least 8 characters.","code":"password_too_short"}]} I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call. Thanks -
Why does the Django django.contrib.auth.authenticate need in-place arguments?
Why does the Django authenticate function work only with this? user=authenticate( username=request.POST['username'], password=request.POST['password'] ) And not with user=authenticate( request.POST['username'], request.POST['password'] ) -
Integrate PayPal in Django app using Paypal Python SDK
I'm working on a Project in which I'm using Python(3.6) & Django(1.10) and I need to implement Paypal payment method in this project.I have decided to use the official Python SDK from Paypal instead of other third-party packages. Here's what i have tried: According to the docs as Here: Here's my Template: <form class="form"> {% csrf_token %} <div id="paypal-button"></div> <script src="https://www.paypalobjects.com/api/checkout.js"></script> <script> var CREATE_PAYMENT_URL = '{% url 'users:payment' %}'; var EXECUTE_PAYMENT_URL = 'https://my-store.com/paypal/execute-payment'; paypal.Button.render({ env: 'sandbox', // Or 'production' commit: true, // Show a 'Pay Now' button payment: function () { return paypal.request.post(CREATE_PAYMENT_URL).then(function (data) { return data.paymentID; }); }, onAuthorize: function (data) { return paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID}).then(function () { // The payment is complete! // You can now show a confirmation message to the customer }); } }, '#paypal-button'); </script> </form> From urls.py: url('^payment/$', views.PaymentProcess.as_view(), name='payment'), From views.py: class PaymentProcess(LoginRequiredMixin, generic.DetailView): def post(self, request, *args, **kwargs): mydict = { 'paymentID': 'PAYMENTID', } print('Getting payment request') return json.dumps(mydict) When Paypal submits a post request to /payment it returns 403 Forbidden error due to csrf_token, how I can pass the csrf_token with this request. Any resource or tutorial will be really appreciated. Help me, please! Thanks in advance! -
Django forms error: Select a valid choice. That choice is not one of the available choices
I am trying to create a website with two dropdown menus: Department and Course Number. The data for the dropdown menus comes from the "courses" table of my SQL database. Right now my website initializes properly and shows the correct options in the dropdown menu. However, when the user selects an option within the dropdown menu and submits their choice, Django throws a "Select a valid choice. That choice is not one of the available choices." error. I suspect that the output of my form isn't in the right format, so the selection can't be found in my database, but I've read many other SO questions with the same issue and still have gotten nowhere. Any help is appreciated. models.py from django.db import models class Dept(models.Model): dept = models.CharField(max_length=255, db_column = 'dept') class Meta: managed = False db_table = 'courses' def __str__(self): return self.dept class Course_num(models.Model): course_num = models.CharField(max_length=255, db_column = 'course_number') class Meta: managed = False db_table = 'courses' def __str__(self): return self.course_num forms.py from django import forms from .models import * class CourseForm(forms.Form): dept = forms.ModelChoiceField( queryset=Dept.objects.values_list('dept', flat = True).distinct().\ order_by('dept').exclude(dept__isnull=True), required=False, empty_label="No preference", label=u"Department") course_num = forms.ModelChoiceField( queryset=Course_num.objects.all().\ order_by('course_num').values_list('course_num', flat = True).\ distinct().exclude(course_num__isnull=True), required=False, empty_label="No preference", label=u"Course … -
Connect to AWS RDS mysql from Heroku Django app
I've been struggling with configuring my Heroku hosted Django app with my AWS RDS. I've been following this Heroku AWS RDS Set Up. Everything on my AWS side is set up and tested. The issue occurs when I'm making a http get to my api which in turn fetches some data from the database. I get a typeError 'sslca' is not a valid argument...Attached is the error heroku log error This is my database config.django settings/heroku database url Any help would be much appreciated. -
Cannot resolve bundle style
I'm trying to integrate Webpack into my Django Project. This is my webpack.config.js file: const path = require("path"); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const VENDOR_LIBS = [ 'jquery', 'mustache' ]; const config = { context: __dirname, entry: { app: 'app.js', vendor: VENDOR_LIBS, }, output: { path: path.resolve(__dirname, './static/bundles/'), filename: "[name].js" }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['env'] } } }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.(jpe?g|png|gif|svg)$/, use: [ { loader: 'url-loader', options: { limit: 40000 } }, 'image-webpack-loader' ] } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }), new BundleTracker({filename: './webpack-stats.json'}), new ExtractTextPlugin('style.css') ], resolve: { modules: ['./static/assets/', './static/assets/javascript/', './static/assets/css/', 'node_modules'] } }; module.exports = config; I'm also using the django-webpack-loader, and I have the following settings on my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/bundles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), # 'CACHE': not DEBUG } } For some reason I'm getting a WebpackBundleLookupError at / "Cannot resolve bundle style" {% load render_bundle from webpack_loader %} … -
Explain this particular line in vagrant file
Explain "config.vm.network "forwarded_port", host_ip: "127.0.0.1", guest: 8080, host: 8080" I was creating a virtual server for django via vagrant. -
Django Or Anguler JS , which Framework i choose?
This is very first time i am trying to develop website (social website) + Android application for same and before that i have tried to figure out which Framework i am going to use. Some where says use Anguler JS, some where says use React JS, Somewhere says use Django and finally i selected two Framework and among them need to select one Anhuler JS (Mostly used as Front End, Back end yet not decided , any suggestion please???) Django (Full stack ) Now i heard Django have not support for Android Development but i needed it as i am going to develop Android application also. So basically requirement is what ever code i do in website which can be easily shared in mobile application ,so my development will be faster. Now anyone have suggestion how can i go further using suitable technology which can be commonly used in Website and it's Android Application? -
Pass additional data via POST from django template submit
Using Django template to display a table of input text. But in the view only input out of this table are present in the request.POST. Dynamically created input are not available in the POST. test.html <form class="form-horizontal" method="post" enctype='multipart/form-data' id="subscription-form"> .... .... <tbody class="draggable-column"> {% for product in products %} <tr> <td class="hidden-xs">{{forloop.counter}}</td> <td class="hidden-xs">{{product.title}}</td> <td class="hidden-xs">{{product.weight}}</td> <td class="" >{{product.yearly_consumption}}</td> <td><input type="text" id="{{product.id}}_jan" data-id="{{product.id}}_jan" class="user-action"></td> <td><input type="text" id="{{product.id}}_feb" data-id="{{product.id}}_feb" class="user-action"></td> <td><input type="text" id="{{product.id}}_mar" data-id="{{product.id}}_mar" class="user-action"></td> ...... ...... <td><input type="text" id="{{product.id}}_total" data-id="{{product.id}}_total" readonly="readonly" class="total-quantity"></td> </tr> <input type="hidden" value="{{product.weight}}" id="{{product.id}}_weight"> <input type="hidden" value="{{product.is_winter}}" id="{{product.id}}_winter"> {% endfor %} </tbody> .... .... </form> This table input are not avalable in the POST of django view. How could make this available in the POST? -
How to use inheritance in Django Templates
Respected All: I want to use the feature of reusability of the Django templates As i wrote in base.html <title>{% block title %}{% trans 'Main Page title' %}{% endblock %}</title> And my otherfile.html is this {% block title %}Other file Title{% endblock %} I want to Set the title without useing tags in otherfile.html is it possible? -
Q: Django Channels on Elastic Beanstalk (aws)
I have a Django(2.0.2) app I deployed successfully to ebs. I implemented websockets with Channels(2.0.2) + Redis(4) and swapped to an Application Load Balancer following this guide: https://medium.com/@abhishek.mv1995/setting-up-django-channels-on-aws-elastic-beanstalk-716fd5a49c4a. Up until recently everything was working just fine but a few days ago I started getting 502 errors when trying to connect to my websockets. failed: Error during WebSocket handshake: Unexpected response code: 502 My supervisor config: [program:daphne] command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 bang.asgi:application directory=/opt/python/current/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_daphne.log stderr_logfile=/var/log/stderr_daphne.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 environment=$djangoenv [program:worker] command=/opt/python/run/venv/bin/python manage.py runworker websocket directory=/opt/python/current/app/src user=ec2-user process_name=%(program_name)s_%(process_num)02d numprocs=4 stdout_logfile=/var/log/stdout_worker.log stderr_logfile=/var/log/stderr_worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 environment=$djangoenv Load Balancer config: option_settings: aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP aws:elasticbeanstalk:environment:process:http: Port: '5000' Protocol: HTTP On localhost everything works fine but currently on aws I can't figure out how to get the websockets to work again. I read that in Channels 2 you no longer need to runworker so I have it removed currently. When I ssh into my eb instance and run sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf status and netstat -antpl I seem to confirm everything is working fine: daphne RUNNING pid 4760, uptime 1:10:11 httpd RUNNING pid 4582, uptime 1:10:17 Proto Recv-Q … -
Getting web session from last.fm api
I'm trying to get web session from last.fm API using method auth.getSession in Django but it is giving me invalid method signature supplied . I don't know what I'm doing wrong. I'm receiving token correctly. {"Error":13,"message":"Invalid method signature supplied"} This is my code: token = request.GET["token"] session="api_key%smethodauth.getSessiontoken%s" %(API_KEY.encode('utf-8'),token.encode('utf-8')) api_signa=hashlib.md5(session.encode()).hexdigest() url="http://ws.audioscrobbler.com/2.0/?method=auth.getSession&api_key=%s &token=%s &api_sig=%s" %(API_KEY,token,api_signa) return HttpResponseRedirect(url) -
How to maintain form parameters when new url is called
I have a form shown in the first picture below and a set of navpills shown in the second picture. When I click the navpill it calls a url that either ends with 'charts' or 'tables'. Whenever I press the navpill though all the values in the form are cleared to the original template. I need them to stay so when I switch from charts to tables I get the same information. i.e. if there is a fund type selected I want it to still be their if I click on tables when I was previously on charts. I tried using "GET" as such: min_year = request.GET.get('year_min', None) if not min_year: min_year = '2013' But that only works if I submit the form. As soon as I click on one of the values it resets. Here is the html for the "Start Year" box: <h6>Start Year</h6> <div class="form-group"> {{form.year_min|attr:"class:form-control"}} </div> And here is the form: CHOICES = ( ('1998', '1998'), ('1999', '1999'), ('2001', '2001'), ('2002', '2002'), ('2003', '2003'), ('2004', '2004'), ('2005', '2005'), ('2006', '2006'), ('2007', '2007'), ('2008', '2008'), ('2009', '2009'), ('2010', '2010'), ('2011', '2011'), ('2012', '2012'), ('2013', '2013'), ('2014', '2014'), ('2015', '2015'), ('2016', '2016'), ('2017', '2017'), ('2018', '2018'), ) year_min …