Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Asynchronous Tasks, Calling multi- function at same time with a function
I want to run a function where i call different different function at same time means a function have a collection of functions which runs at same time. -
How to match the standards of great companies with highest coding standards
This is probably the most asked question. Sorry for the redundancy. I am working on local Python Django projects for a year. I am able to get the features working and my coding skills are good. But not good enough. How can i make sure that i am following the best practices? I was thinking about doing one thing at least by three different ways and measure the quality, readability and efficiency.It will take time but i'll hopefully learn. How can i get my code reviewed from a fierce reviewer who would not let even the minutest error go? Are there sites/tools for this? How can i match the standards of great coding companies who want 'Proven knowledge in Python' etc. What is proven knowledge any way? Is there a good certification so that i can prove to the world that i am a great coder? -
React JSX and Django reverse URL
I'm trying to build some menu using React and need some Django reverse urls in this menu. Is it possible to get django url tag inside JSX? How can this be used? render: function() { return <div> <ul className={"myClassName"}> <li><a href="{% url 'my_revese_url' %}">Menu item</a></li> </ul> </div>; } -
Django, jQuery. I can't load() after the same div multiple times
I am trying to let the user create multiple types of the same input form. The problem is that the first time I click on the button a form is appended to the append_form div, but no matter how many more times I click on the "Add" button, no other form is appended. What am I doing wrong? This is my HTML code: <div class="col-md-9"><strong>{% trans "Please, add as many measures as you like to be available for the institutional simulation" %}</strong></div> <div class="col-md-3"><button class="btn btn-success" onclick="addForm('{% url "add_measure_form" %}')"><i class="fa fa-plus-square"></i> {% trans "Add Measure" %} </button></div> <div id="append_forms"></div> And this is my script function addForm(url){ $("#append_forms").after().load(url); } And this is my django views: def add_measure_form(request): data = { } return render(request, "_frm_inner_form.html", data) and urls url(r'^measures/form/add/$', add_measure_form, name="add_measure_form") -
Django signal admin file upload force synchronus
I have a model which has a FileField. I'm able to upload file using django admin. What I want after uploading file I should be able to parse the file and extract specific content and save into other model(in same app). for that I'm using post_save signal. but when I try to debug, it seems that code of post_save _method executed before file upload is complete. so here i doubt that file upload is asynchronous. and because of that I'm getting An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. this error. would be great if somebody can help me in finding the mistake or guide to resolve this atomic block error. -
Linking Django-oscar to native IOS app for shopping
So currently I am using django-oscar as my self hosted ecommerce solution to allow for merchants to have standard abilities such as uploading products, inventory management, etc.. on the backend. The marketplace however will be on our native IOS app (currently live). We are thinking of using django-tastypie to create the API and transfer data back and forth from the admin to marketplace(on the app). A few questions I have: How would we go about creating the checkout process, shopping carts and etc? Hosted ecommerce solutions such as Shopify have IOS SDKs to handle shopping carts checkout and etc on the IOS side of things but django-oscar from what I see doesn't have such SDK. How would even sending the information back to the admin dashboard(from the IOS app) to update our merchants orders, inventory management, etc work? django-oscar only seems to cover how to do so with web based apps but not with a native IOS app. Nothing around the web seems to explain this particular scenario at all, and I was hoping someone in the development community could lend some insight into this arena, and connect the dots. *we are using swift for our IOS app Thank you! -
django - No Reverse Match found for the test project
I have created a test project in django and I tried to create an event, while rendering the template all i get is a Exception: Reverse for 'createEvent' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'eventManager/teacherLogin/(?P<id>[0-9]+)/createEvent/$'] the following are the url patterns(eventManager.urls) : url(r'^teacherLogin/(?P<id>[0-9]+)/createEvent/$', views.CreateEvent.as_view(), name="createEvent"), base urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.Start.as_view(),name="start"), url(r'^eventManager/', include("eventManager.urls",namespace="eventManager")),] the following are the views associated with the createEvent : class CreateEvent(View): form_class = EventForm template_name = 'eventManager/eventForm.html' def get(self, request,id): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request,id): form = self.form_class(request.POST) if form.is_valid(): # creats an object of form but doesnot save into database event = form.save(commit=False) # cleaned (normalized) data eventName = form.cleaned_data['eventName'] resourcePerson = form.cleaned_data['resourcePerson'] eventVenue = form.cleaned_data['eventVenue'] ECE = form.cleaned_data['ECE'] CSE = form.cleaned_data['CSE'] EEE = form.cleaned_data['EEE'] IT = form.cleaned_data['IT'] mechanical = form.cleaned_data['mechanical'] chemical = form.cleaned_data['chemical'] civil = form.cleaned_data['civil'] eventDate = form.cleaned_data['eventDate'] todayDate=datetime.datetime.now().date() if(eventDate<=todayDate): return redirect('/eventManager/teacherLogin/%i/createEvent/invalidDate/' % int(id)) eventStartTime = form.cleaned_data['eventStartTime'] eventEndTime = form.cleaned_data['eventEndTime'] if(eventStartTime>=eventEndTime): return redirect('/eventManager/teacherLogin/%i/createEvent/invalidTime/' % int(id)) t=Teacher.objects.filter(id=self.kwargs['id']) event.teacher=t[0] event.save() #return redirect('eventDetail/%i/' % event.id) return redirect('/eventManager/teacherLogin/%i/createEvent/createEventSuccess/' % int(id)) return redirect('/eventManager/teacherLogin/%i/createEvent/createEventFailure/' % int(id)) Exception message screenshot Template screenshot found similar questions on stackoverflow.com , but none of it has resolved my problem, … -
Angular Open in a new window
In my django code i have defined the chinese domain $('#zh-cn').click(function(e){ e.preventDefault() var current_path = window.location.pathname.replace('/zh-cn',''); {# $(location).attr('href', {{ chinese }}+ current_path);#} $window.open( "www.google.com"+ current_path, '_blank') }) i have a drop down menu and when the user selects zh-cn i want to open in a new window.but when i select zh-cn it doesn't do anything -
How to retrieve the particular field from the SQLite database in django
LenderStatus = LoanStatus.objects.get(toStatus=request.GET.get('toStatus')) I am retrieving the toStatus field from table LoanStatus but it's not working. -
How to download a csv file in python from a server?
from pip._vendor import requests import csv url = 'https://docs.google.com/spreadsheets/abcd' dataReader = csv.reader(open(url), delimiter=',', quotechar='"') exampleData = list(dataReader) exampleData -
local variable 'statement' referenced before assignment
I am currently creating a while loop in python and I got this problem: local variable 'statement' referenced before assignment this is my code: while (statement == True): self.headNode = settings.EMPTY_UUID try: lastNode = Task.objects.get(mission_id=missionId, parent_task_id=settings.EMPTY_UUID, next = self.headNode) self.headNode = lastNode.id statement = True except: statement = False I am worried if I initialize statement = True before while statement because it might become an infinite loop -
I cannot ignore pycache and db.sqlite on Django even though it refers them at .gitignore
I'd like to ignore the changes of pycache and db.sqlite of Django project. I refer them at .gitignore,however git catches the variation of them. Could you tell me what is problem if you know it? I attached my .gitignore at the end of sentence. .gitignore # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class media/ settings.py .idea/ # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv .venv/ venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject # Database stuff *.sqlite3 migrations/ db.sqlite3 # Atom config file .editorconfig … -
Python Send Weasyprint PDF Email Attachment with Sendgrid
I'm trying to email a PDF generated by Weasyprint with Sendgrid. The Sendgrid Python library is throwing an error HTTP Error 400: Bad Request which while not very descriptive I believe is due to an issue with the encoding of the attachment (Sendgrid wants attachments in base64). html_page, css_page = generatePDF(url) # Generates HTML and CSS from URL pdf = html_page.write_pdf(stylesheets=css_page) # Compiles PDF from HTML and CSS as bytes string pdf = base64.b64encode(pdf).decode() # Base64 encodes PDF data = { 'personalizations' : [ { 'to' : [ { 'email' : data['to'] } ], 'subject' : data['subject'] } ], 'from' : { 'email' : data['from'] }, 'content' : [ { 'type' : 'text/plain', 'value' : data['text'] }, { 'type' : 'text/html', 'value' : '<html><p>{}</p></html>'.format(data['html']) } ], 'reply_to' : { 'name' : '{}'.format(sender_name), 'email' : '{}'.format(sender_email) }, 'attachments' : { 'content' : pdf, 'filename' : data['filename'], 'type' : 'application/pdf' } } sg = sendgrid.SendGridAPIClient(apikey = SENDGRID_API_SECRET) rq = sg.client.mail.send.post(request_body = data) I've found a similar issue here but the posted solution did not resolve my problem. Thanks. -
celerybeat send task fails with ssl error
I am using celerybeat to send periodic tasks to rabbitmq queue. It works as expected for some time and then send celery.backend_cleanup fails with SSL error. [2016-10-24 04:00:02,309: DEBUG/MainProcess] Channel open [2016-10-24 04:00:02,443: ERROR/MainProcess] Message Error: Couldn't apply scheduled task celery.backend_cleanup: [Errno 1] _ssl.c:1309: error:1409F07F:SSL routines:SSL3_WRITE_PENDING:bad write retry [' File "/local/mnt/apps/ipcat/venvs/django16/bin/celery", line 9, in <module>\n load_entry_point(\'celery-ipcat==3.1.23\', \'console_scripts\', \'celery\')()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/__main__.py", line 30, in main\n main()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/celery.py", line 81, in main\n cmd.execute_from_commandline(argv)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline\n super(CeleryCommand, self).execute_from_commandline(argv)))\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/base.py", line 311, in execute_from_commandline\n return self.handle_argv(self.prog_name, argv[1:])\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/celery.py", line 785, in handle_argv\n return self.execute(command, argv)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/celery.py", line 717, in execute\n ).run_from_argv(self.prog_name, argv[1:], command=argv[0])\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/base.py", line 315, in run_from_argv\n sys.argv if argv is None else argv, command)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/base.py", line 377, in handle_argv\n return self(*args, **options)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/base.py", line 274, in __call__\n ret = self.run(*args, **kwargs)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/bin/beat.py", line 79, in run\n return beat().run()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/apps/beat.py", line 83, in run\n self.start_scheduler()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/apps/beat.py", line 112, in start_scheduler\n beat.start()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/beat.py", line 479, in start\n interval = self.scheduler.tick()\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/beat.py", line 221, in tick\n next_time_to_run = self.maybe_due(entry, self.publisher)\n', ' File "/local/mnt/apps/ipcat/venvs/django16/lib/python2.7/site-packages/celery/beat.py", line 207, … -
How to Achieve Mysql Operation UNHEX & HEX with Django Model Database API
thanks for coming in.I was just planning on integrating an audio fingerprint Python Module into Django Framework. I encountered this problem when rewrite its database operation. One of Mysql command looks like this: INSERT INTO %s (%s, %s, %s) values (%%s, UNHEX(%%s), %s); And I didn't find similar method for Django.Models to achieve that and Hex() as well.If anyone knows how to do that, please help. -
streaming large parsed CSV with Django StreamingHttpResponse timing out?
The following code based on Django's documentation 1 works fine to parse certain years from a 400MB CSV and download through StreamingHttpResponse (for example, requesting only 2016 yields a 13MB CSV). Adding a filter parameter to return records matching certain locations (British Columbia, for example) returns only the header row. When I edit the CSV to place a sample of British Columbia records to the top of the CSV, those are output... and then the download stops. The test case passes, I assume this is some kind of timeout with the HTTPResponse? Is there a keepalive option? import csv import os import urllib import datetime from io import BytesIO from zipfile import ZipFile from django.http import HttpResponse from django.http import StreamingHttpResponse from STC_Arrivals import settings class Echo(object): def write(self, value): return value def extract_years_from_csv(startyear, endyear, filter_text): f = open(settings.MEDIA_ROOT + settings.CANSIM_FILE + ".csv") reader = csv.DictReader(f) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) yield writer.writerow(reader.fieldnames) try: for row in reader: readyears = row['Ref_Date'] readyear = int(readyears[:4]) if int(startyear) <= readyear <= int(endyear): if len(filter_text): search_text = row['GEO'] + row['TRAV'] if filter_text.lower() in search_text.lower(): yield writer.writerow( [row['Ref_Date'], row['GEO'], row['TRAV'], row['Vector'], row['Coordinate'], row['Value']]) else: yield writer.writerow( [row['Ref_Date'], row['GEO'], row['TRAV'], row['Vector'], row['Coordinate'], row['Value']]) except … -
Data sequencing based on the 'next' field
Hi I am programming using python and I want to display the list in correct order based on next field. I have a model which looks like: Task() id name next 001 task1 007 005 task2 000 007 task3 005 I do not know how to display it because I only know the basic taskList = Task.objects.all() so when I display it, it should look like task1 task3 task2 the first data's id is 001 and its next field is 007 so that means the next data's id should 007 and its next field is 005 and so on -
Using JavaScript only to give success response on AJAX request
I have a follow button which when clicked it AJAXly allows a user to a follow/unfollow a thing and as well change the count of the number of users that follows the thing.But i notice it takes few seconds(6-10) to give a success response on the follower count.I want to perform the success response purely on the client-side that is for JS to know the number of followers and add +1 or -1(depending) and display it on click.Kindly help Here is my code: <a id='follow-auth' class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored"> {% if following %} <!--the button if user is following --> Unfollow {% else %} <!--the button if user is not following --> Follow {% endif %} </a> <!--text that displays number of users following--> <span style="text-align:center" id="num_fllwrs">{{no_of_fllwrs}}</span> <script> $('#follow-auth').click(function(){ // var el = $(this); $.ajax({ type: "POST", url: "{% url 'follow_org' %}", data: {'pk': '{{auth.pk}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(){ $('#follow-auth').load("{% url 'auth_details' pk=auth.pk slug=authority.slug %} #follow-auth"); $('#num_fllwrs').load("{% url 'auth_details' pk=auth.pk slug=auth.slug %} #num_fllwrs"); } }); }); </script> -
Nginx reverse proxy uwsgi django intermittent 502
I have a site setup with Nginx as load balancer (least_conn) that uses a seperate uwsgi/django server as its upstream. This is normally a pool of about 5 uwsgi/django servers but I've limited it to just one to make sure it's not a bad server. Under 'normal' user behavior, everything appears to be working fine. My problem is that rapid, successive requests will intermittently generate a 502 error. I can recreate this with a few tries by opening a page in our admin that contains a list to all the articles. By opening a bunch of the links in new tabs, about 1 in 10 will fail with a 502 error. Another curiosity, the 502s happen very quickly when they do happen. For example, when a 502 does show up it's as instantaneous as the tab opening. Where I would expect the nginx frontend to wait a bit before coming back with an error. I'm using uwsgi_pass to directly proxy between the nginx load balancer and uwsgi. I've read in a number of other posts about having to increase buffers. I've tried setting uwsgi_buffers_size 16k; and uwsgi_buffers 4 16k; but they have not made a difference. Error logs from both … -
Customizing registration form with Django
I'm new to Django and I'm trying to customize my registration form. I'm trying to add fields = ("username", "first_name", "last_name", "email", "password1", "password2") in my HTML template to add css style on it. My forms.py looks like this: class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.TextInput() last_name = forms.TextInput() class Meta: model = User fields = ("username", "first_name", "last_name", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user views.py: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('register_god') else: form = RegistrationForm() args = {} args.update(csrf(request)) args['form'] = form return render_to_response('chatapp/register.html', args) register.html (only part with first name, because is to long) <form action="/chatapp/register/" method="post"> {% csrf_token %} <h2>Please Sign Up <small>It's free and always will be.</small></h2> <hr class="colorgraph"> <div class="row"> <div class="col-xs-12 col-sm-6 col-md-6"> <div class="form-group"> <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1"> </div> </div> I wonder where should I put it? Thanks! -
How to stop Django Rest Framework from rendering html for exceptions
I have set Debug=False in my settings to test my error handling in my client, but am getting an html payload (<h1>Server Error (500)</h1>) from an exception in this api_view: @api_view(['POST', ]) @permission_classes((permissions.IsAuthenticated,)) @renderer_classes((JSONRenderer,)) @transaction.atomic() def process_payment(request): # Do some work return Response(serializer.data) I am making the call from AngularJS, using the default Accept headers: Accept: application/json, text/plain, */* The documentation on the Renderers page seems to indicate that I can expect json if I'm explicitly using the json renderer for successful responses. Is this a side effect of local development? I don't want to have to write code to test for non-json responses if I can help it. -
Django Data-Migrations: Converting ID's to Foreign-Keys
I'm trying to migrate a legacy database between Django apps. The legacy db is a mysql db and I have to bring the data over into a postgresql db. There are going to be some schema changes, renamed columns and so on but the legacy db isn't going to change shape or structure at all; it's a static target. I've got the two databases registered with django and I've set up a read-only router.py for the mysql legacy db so I can currently read from the legacy database using the ORM with no problems. In the legacy db there are no foreign keys. Any cross table references are just achieved with int fields containing the id of whatever row needs to be looked up. I guess this is a 'quasi foreign-key' or something. For example, there is a sections table that looks like this: sections | CREATE TABLE `sections` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `parent_id` int(11) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `exclude_from_nav` tinyint(1) DEFAULT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=utf8 Here parent_id is a recursive reference to another section's id field, thus giving us subsections. My question … -
Django URL pattern not appearing in production, page not found
Problem I've created a url pattern for an agencies page, which works fine locally, but does not when the project is pushed to production. When trying to debug the error, the url pattern does not appear on the 404 page url(r'^agencies/$', views.agencies, name='agencies') _home.html <div class="cards"> <a href="agencies/"> <div class="card card--earners"> <img src="{% static 'salaries/img/building.png' %}" class="card__icon"> <p class="card__title">Agencies</p> <p class="card__desc">Find salary information for public safety workers, government employees and elected officials.</p> </div> </a> <a href="teachers/"> <div class="card card--salary"> <img src="{% static 'salaries/img/school.png' %}" class="card__icon"> <p class="card__title">Schools</p> <p class="card__desc">Find salary information for superintendents, principals and teachers in Missouri public schools.</p> </div> </a> </div> Page not found Using the URLconf defined in payrolls.urls, Django tried these URL patterns, in this order: ^salaries/ ^$ [name='home'] ^salaries/ ^(?P<agency_id>[0-9]+)/$ [name='agency'] ^salaries/ ^(?P<department_id>[0-9]+_[0-9]+)/$ [name='department'] ^salaries/ ^(?P<agency_id>[0-9]+)/agency_search/$ [name='agency_search'] ^salaries/ ^master_search/$ [name='master_search'] ^salaries/ ^teachers/$ [name='teachers'] ^salaries/ ^teachers/(?P<district_id>[0-9]+)/$ [name='district'] ^salaries/ ^teachers/(?P<district_code>[0-9]+)/(?P<school_code>[0-9]+)/$ [name='school'] ^salaries/ ^teachers/(?P<district_code>[0-9]+)/position/(?P<position_code>[0-9]+)/$ [name='dist_position'] ^salaries/ ^teachers/(?P<district_code>[0-9]+)/(?P<school_code>[0-9]+)/position/(?P<position_code>[0-9]+)/$ [name='school_position'] ^salaries/ ^educator_search/$ [name='educator_search'] ^salaries/ ^teachers/(?P<district_id>[0-9]+)/district_search/$ [name='district_search'] ^salaries/ ^teachers/detail/(?P<teacher_id>[0-9]+)/$ [name='person'] ^admin/ The current URL, salaries/agencies/, didn't match any of these. urls.py from django.conf.urls import url from salaries import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^(?P<agency_id>[0-9]+)/$', views.agency, name='agency'), url(r'^(?P<department_id>[0-9]+_[0-9]+)/$', views.department, name='department'), url(r'^(?P<agency_id>[0-9]+)/agency_search/$', views.agency_search, name='agency_search'), url(r'^master_search/$', views.master_search, name='master_search'), url(r'^teachers/$', views.teachers, name='teachers'), url(r'^teachers/(?P<district_id>[0-9]+)/$', … -
dynamic form complains about number of "steps" as an unexpected keyword argument
My form allows for multiple "steps" to be submitted in the form. The steps are added via push of a button on the form via JavaScript. The problem is django form and validating thereof: class TaskForm(forms.Form): task_name = forms.CharField step_number = forms.IntegerField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): step_fields = kwargs.get('step_number', 0) super(TaskForm, self).__init__(*args, **kwargs) self.fields['step_number'].initial = step_fields for index in range(int(step_fields)): self.fields['step_field_{index}'.format(index=index)] = forms.CharField() This creates form with the task name as the only input field when the page is first loaded. That's expected. I add the steps to my task through the browser, this works fine and the hidden field is incrementing. Then I submit, but I get the error: TypeError at 'task-app/create-task.html' __ init__() got an unexpected keyword argument 'step_number' Obviously, the keyword argument comes from the views.py: def add_task(request): if request.user.is_authenticated(): if request.method == 'POST': form = TaskForm(request.POST, step_number=request.POST.get('step_number')) if form.is_valid(): # do something with the form create_task(form) messages.success(request, "The task form was valid") return redirect('task-app:homepage') else: messages.warning(request, "The form is not valid") return render(request, 'task-app/create-task.html', {'form':form}) else: form = TaskForm() return render(request, 'task-app/create-task.html', {'form':form}) -
Why am I getting "Name Error" in Django
I am trying to use Django Tables 2. My original code worked. However, when I tried to apply my previously written script, I received a bunch of errors. Essentially what my code does is download data from a JSON file from a satellite and pulls data from it. This data is stored in arrays. For example, I pull the dateAndTime of the observation, as well as the x-cen and y-cen of the window. Next, using a for loop, I create one object for each observation to populate the database. When I try and display the data table, I get a nameError. I've tried renaming the model, making migrations, and rewriting the whole file. The traceback says that the issue is in this line of code, in my views.py: observation = HEK_Observations(noaaNmbr=noaaNmbr, dateAndTime=dateAndTimeHEK[i], xcen=xcen[i], ycen=ycen[i], xfov=xfov[i], yfov=yfov[i], sciObj=sciObj[i]) Here is my views.py: dateAndTimeHEK = [] xcen = [] ycen = [] xfov = [] yfov = [] sciObj = [] location = [] dateAndTimeJSOC = [] latMin = [] latMax = [] lonMin = [] lonMax = [] location = [] def getNumberOfEntries(hekJSON): return len(dateAndTimeHEK) def getInfo(counter, hekJSON): cont = True while cont: try: dateAndTimeHEK.append(hekJSON["Events"][counter]["startTime"]) xcen.append(float("%.2f" % hekJSON["Events"][counter]["xCen"])) ycen.append(float("%.2f" % hekJSON["Events"][counter]["yCen"])) …