Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django celery,something wrong with shared_task
i use django-rest-framework and celery this ims my views.py # GET /server/test/<para>/ class Testcelery(APIView): def test(self): print(celery_test()) def get(self, request, para, format=None): print('test') self.test() # result = add.delay(4, 4) # print(result.id) result = OrderedDict() result['result'] = 'taskid' result['code'] = status.HTTP_200_OK result['message'] = 'success' return Response(result, status=status.HTTP_200_OK) this is a simple celery task @shared_task() def celery_test(): print('celerytest') return True i debug the django it can goes to the test method but the program stuck at the next step in call in local.py where the error happens the debug stops there,and shows like this debug result -
Pycharm Import Error
guys. I'm trying to develop a program to create excel file with using xlwt. I have used pip install xlwt to install it. In Terminal, it can be imported with no error. And the Django project could be run correctly. But in pycharm, it shows import error when running the Django project. The error code shows below: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/motion/Documents/GitHub/motion-op/motion/urls.py", line 4, in <module> from product.views import home File "/Users/motion/Documents/GitHub/motion-op/product/views.py", line 22, in <module> from .ProductService import ProductService File "/Users/motion/Documents/GitHub/motion-op/product/ProductService.py", line 13, in <module> from method import ProductServicePO,send_email, SaveImg, create_excel_file File "/Users/motion/Documents/GitHub/motion-op/product/method/create_excel_file.py", line 2, in <module> import xlwt ImportError: … -
Django chain multiple queries in view
I have three models: Course Assignment Term A course has a ManyToManyField which accesses Django's default User in a field called student, and a ForeignKey with term An assignment has a ForeignKey with course When a user logs in to the page, I would like to show them something like this bootstrap collapse card where I can display each term and the corresponding classes with which the student is enrolled. I am able to access all of the courses in which the student is enrolled, I'm just having difficulty with figuring out the query to select the terms. I've tried using 'select_related' with no luck although I may be using it incorrectly. So far I've got course_list = Course.objects.filter(students = request.user).select_related('term'). Is there a way to acquire all of the terms and their corresponding courses so that I can display them in the way I'd like? If not, should I be modeling my database in a different way? -
Database not storing JSON variable
I have an django app in which I am trying to store the gridster widget configuration in the form of JSON variable to database.But when I click"Update" button on my webpage my database does not stores any value. My JS Code which sends serial value to database var gridster; var $color_picker = $('#color_picker'); var URL = "{% url 'save-grid' %}"; gridster = $(".gridster ul").gridster({ widget_base_dimensions: [80, 80], widget_margins: [5, 5], helper: 'clone', resize: { enabled: true } }).data('gridster'); $(".add-button").on("click", function() { $('#test').click(); $('#test').on('change', function(e) { var test = document.getElementById('test'); if (!test) { alert("Um, couldn't find the fileinput element."); } else if (!test.files) { alert("This browser doesn't seem to support the `files` property of file inputs."); } else if (!test.files[0]) { alert("Please select a file before clicking 'Load'"); } else { file = test.files[0]; console.log(file); fr = new FileReader(); fr.readAsDataURL(file); fr.onload = function() { var data = fr.result; // data <-- in this var you have the file data in Base64 format callbackAddButton(data); test.value = ''; $('#test').replaceWith($('#test').clone()) }; } }) }); function callbackAddButton(file) { // get selected color value var color = $color_picker.val(); // build the widget, including a class for the selected color value var $widget = $('<li>', { 'class': … -
HTML in django widgets?
I'm creating a project in Django. I use ModelForms quite a bit to get user data. I'd like to add help text to each of my fields. How I'd like those to appear is like this: A tiny "?" image to the right of the input, then a popup that appears when the "?" is hovered over. I have this working in CSS and HTML. What I need to do is put in an tag before every instance of help_text being displayed, along with some other HTML. From my understanding I can do this by subclassing widgets, but I've seen in several places that I shouldn't add HTML to widgets? It seems much less elegant to stop using the ModelForm auto-rendering in all my templates and instead re-write it using loops and then put the HTML in there. The help_text is never going to be controlled by anyone except me, so I don't believe XSS is a concern. Am I missing something? Is there an easier/better way to do this? Also, if someone could point me to a guide on this with an explanation, it would be much appreciated. -
Why do I get an operational error, saying a database is read-only?
I'm using SQLite with Django, have been for a few months. Today I was about to do replace a table with an updated version, which I regarded as tricky so I took a full backup of my entire project. At a certain point, I started getting this error -- with subtext "attempt to write a readonly database." This made no sense to me, but after trying and failing to fix it, I renamed the entire directory and restored the morning backup. No help. I tried a different browser. No help. I logged in with an incognito session. No help. I logged in with an incognito session and a different Django user account. No help. In all cases, it's the login that fails. And it fails just after I enter the password. The site is still in debug mode, and I've pasted the error info to http://dpaste.com/2NS9ZMJ.txt I have no idea how to get my site working again, if a complete restore of the project directory won't do it. -
Modifying a field in serializers.ModelSerializer Class imported from an external library
I'm trying to override/modify a class XXXSerializer(serializers.ModelSerializer) object defined in an external library that I am including in the installed_apps configuration of my settings.py. class XXXSerializer(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())],default='') class Meta: model = User exclude = [ 'is_superuser', 'is_staff', 'is_active', 'content_type', 'groups', 'user_permissions', 'account_id', ] As shown above, the email is required to be unique in their definition. However, I do not want to require it to be unique. My question is therefore, what is the best way to override this field? Some thoughts/attempts: Copy the entire library directly into my project, and take out the validator there. I think this would definitely work but may not be an optimal solution? Somehow override it by defining another YYYSerializer with my desired property, and use import external_library sys.module['external_library.XXXSerializer'] = YYYSerializer. However, I'm not exactly sure about 1. where to put this piece of code, 2. the proper syntax, 3. whether this would even work in an ideal situation. When I put it in settings.py or some __init__ files, it returns Apps aren't loaded yet error - probably because the external_library hasn't been loaded yet. Any suggestions would be appreciated! -
How do I change the url back to mysite.com in django after loging in the user?
I have two apps in my django project. After loging the user in through "visit" app I redirect to "mainapp". How ever my url patter becomes something like this : mysite/accounts/profile/ If I try specifying in urls.py I get redirected to "visit" app. How do I reset my url visit/views.py def profile(request): return HttpResponseRedirect(reverse("main:home")) main/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'accounts/profile', views.home, name='home'), ] main/views.py def home(request): return render(request, 'main/home.html') -
django import csv in several related models
For a web application of naturalistic data for the study of bats (http://www.dbchiro.org), I need to be able to propose a view allowing to import files from spreadsheets (csv, ods files , xls) into database. To import this data into a single table, no problem, several extensions exist (django-import-export or django-csvimport in particular). On the other hand, my need is more particular because my naturalistic data is distributed in several distinct tables (not counting the tables of dictionaries). Here is the schematic diagram: Model Place Place (a locality is a site with unique x / y coordinates as a building). 1-n Model Session (one data = one date and one inventory method by locality) 1-n Model Sighting (one data = one species per session) 1-n Model CountDetail (one data = 1 detail for a species: eg number of males, number of females, etc.) What I would like to get is the ability to import the data of a session with a single csv file that would populate the last two models: Observations (Sighting) and for each observation (each species observed), its detailed data (CountDetail). Is there one or more simple solutions (I'm doing well but I'm not a great python … -
Django save rows of html table selected by checkbox in the database
I have a table in my models which the stocks are saving in it and its name is Stocks this table is desplayed in a template and i want to put a checkbox beside each row to save the checked row in another table of the model here ismy model.py : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.id) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) class SellerDesktop(models.Model): seller=models.OneToOneField(User, related_name='seller', blank=True, null=True) buyer=models.OneToOneField(User, related_name='buyer', blank=True, null=True) stock=models.ForeignKey(Stocks, related_name='stocktoseller', blank=True, null=True) def __str__(self): return str(self.seller) + '-' + str(self.buyer) class Meta: verbose_name=_('SellerDesktop') verbose_name_plural=_('SellerDesktop') and the Template : <form method="post"> {% csrf_token %} <table id="example" class="table table-list-search table-responsive table-hover table-striped" width="100%"> {% for item in myst %} <td><input type="checkbox" name="sendtoseller" value="{{ item.id }}"></td> <td>{{ item.user.profile.companyname}}</td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.pasvand }}</td> <td>{{ item.comment }}</td> <td>{{ item.price }}</td> <td>{{ item.date|timesince }}</td> </tr> {% endfor %} </table> <div style="text-align: center; margin-top:0.5cm; margin-bottom:1cm;"> <input type="submit" name="toseller" value="Submit to seller " style="color:red; width:100%;"/> </div> </form> and the view : def allstocks_view(request): if request.method=='POST': tosave = request.POST.getlist('sendtoseller') stockid=Stocks.objects.filter(id=tosave) SellerDesktop.objects.create(buyer=request.user,stock=stockid) stocks_list=Stocks.objects.all().filter(confirm=_('approved') ).order_by('-date') …