Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
braintree drop in having two forms rendered instead of one
My drop in is being registered twice. (Meaning two forms with paypal / credit card fields are showing up) instead of just one in the dropin div. Here's my code. What am I doing wrong that's causing this? I tried setting the checkout variable which is what another answer recommended... Also, require.js throws a massive error in console is there a better version? HTML <div id="dropin-container"></div> <form id="checkout-form"> <input type='submit' value='Pay' id="pay-btn" disabled/> </form> Braintree script <script src="https://js.braintreegateway.com/js/braintree-2.28.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.js"></script> <script type="text/javascript"> var checkout; </script> <script type="text/javascript"> var braintree_client_token = "{{ braintree_client_token }}"; var amount = parseFloat("{{ cart.total }}");; function braintreeSetup() { braintree.setup(braintree_client_token, "dropin", { authorization: braintree_client_token, paymentOptionPriority: ['card', 'paypal'], paypal: { singleUse: true, amount: amount, currency: 'USD', flow: 'checkout', button: { type: 'checkout', } }, container: "dropin-container", form: 'checkout-form', onPaymentMethodReceived: function (obj) { }, onReady: function (integration) { checkout = integration; $("#pay-btn").prop('disabled', false); }, onError: function (obj) { } }); if (checkout) { // When you are ready to tear down your integration checkout.teardown(function () { checkout = null; // braintree.setup can safely be run again! }); } } braintreeSetup(); $('form').submit(function () { $('[type=submit]').prop('disabled', true); $('.braintree-notifications').html(''); }); -
pycharm 'Command' object has no attribute 'usage'?
in pycharm, running django project,but have the error. Failed to get real commands on module "MyShop": python process died with code 1: Traceback (most recent call last): File "F:\PyCharm 5.0.4\helpers\pycharm\_jb_manage_tasks_provider.py", line 22, in <module> parser.report_data(dumper) File "F:\PyCharm 5.0.4\helpers\pycharm\django_manage_commands_provider\_parser\parser.py", line 47, in report_data command_help_text=VersionAgnosticUtils().to_unicode(command.usage("")).replace("%prog", command_name)) AttributeError: 'Command' object has no attribute 'usage' -
What should i use Reactjs with.. Nodejs or Django
I am in the process or starting to learn Django. I have been building web applications with Nodejs/Express and have recently decided to start to learn Django because it seems to be a powerful backend framework. How is Django different from Nodejs and which one should I stick with. I feel like Django is a more powerful engine to write back-end code on, but I am still new to it. And lastly, can I even use front-end frameworks/libraries with Django ie. Angularjs and Reactjs -
Getting a NoReverseMatch error even though my 'Identity_nest_list' uniform resource locator contains the pk parameter
I am attempt to update an instance and return to the Template view of the instance. Problem : The code renders the edit view however when I edit the instance and press save it returns this error. I realize that the error is telling my that my Identity_nest_list URL doesn't havea pk parameter. However I added it and it is still giving me the error. Essentially I want to be able to edit the object, save the edit and redirect the user to the updated version of the Identity_unique instance, along with the other instances that are already there Request Method: POST Request URL: http://127.0.0.1:8000/nesting/Identity-edit/L882394/?csrfmiddlewaretoken=umHqs06uQmn0fsBNPjnqpuv4yyBIPkGGJNmN1l83TLUSVFh3ja1WPd8reE3IvSEX Django Version: 1.10.5 Python Version: 3.5.3 Installed Applications: ['Identities', 'nesting', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'Identity.middleware.LoginRequiredMiddleware'] Traceback: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in post 240. return super(BaseUpdateView, self).post(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in form_valid 163. … -
Limit number of model object page views for an anonymous user until they have to sign up (Django)?
I'm trying to track the number of views an anonymous (Non-authenticated) user makes on my model object detail pages (Map pages) so that I can redirect them to the sign up page after they view the pages ~5 times. For example: the anonymous user gets 5 free map views before having to sign up (Or these pages will be unaccessible). Not sure if I should use cookies, sessions, or just some kind of javascript for this. I can't really wrap my head around it. A point in any direction would be great, thanks! -
Django View Error - NoReverseMatch
I am new to django and I am trying to solve a NoReverseMatch issue. I think it has something to do with the views but i'm new to this. The code is from a popular boiler plate repo from a few years ago. PLEASE NOTE: I tried reading like every answer on stack overflow already and have been stuck for hours. Any help would be greatly appreciated main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^login/', include('shopify_app.urls')), url(r'^', include('home.urls'), name='root_path'), url(r'^admin/', admin.site.urls), ] urls.py inside of app from django.conf.urls import url from shopify_app import views urlpatterns = [ url(r'^$', views.login, name='shopify_app_login'), url(r'^authenticate/$', views.authenticate, name='shopify_app_authenticate'), url(r'^finalize/$', views.finalize, name='shopify_app_finalize'), url(r'^logout/$', views.logout, name='shopify_app_logout'), ] views.py inside of app from django.shortcuts import redirect, render from django.contrib import messages from django.core.urlresolvers import reverse from django.conf import settings import shopify def authenticate(request): shop = request.GET.get('shop') print('shop:', shop) if shop: scope = settings.SHOPIFY_API_SCOPE redirect_uri = request.build_absolute_uri(reverse('shopify_app.views.finalize')) permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri) return redirect(permission_url) return redirect(_return_address(request)) def finalize(request): shop_url = request.GET['shop'] try: shopify_session = shopify.Session(shop_url) request.session['shopify'] = { "shop_url": shop_url, "access_token": shopify_session.request_token(request.REQUEST) } except Exception: messages.error(request, "Could not log in to Shopify store.") return redirect(reverse('shopify_app.views.login')) messages.info(request, "Logged in to shopify store.") response = … -
How to replace ALL django "Status Code Exception" pages
Any Status Code exceptions like 404, 403, 405, 500, CSRF and more return their own "Django" specific pages, a few are HTML. handler403, handler404, and handler500 exist and can be easily overridden, but there are a lot of these "hidden" Django pages that are being returned upon error, an example is 405 (method does not exist) or CSRF (if no CSRF token is in the request) and probably many more. Is it possible to have a custom view (such as just a generic 404 return) for ALL of these "hidden" Django HTML pages? -
Django Cannot Connect to Remote MySQL Server
I am running a Django and attempting to connect to a MySQL server at my university. First of all: In order to connect the database, I normally SSH into a remote server (with authentication) of theirs, and then run MySQL and enter my MySQL authentications. This works without an issue, in Terminal as well as DataGrip. Now, using PyCharm, I have installed mysqlclient in the intepreter and changed my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '[DB_NAME]', 'USER': '[DB_USERNAME]', 'PASSWORD': '[DB_PASSWORD]', 'HOST': '[REMOTE SERVER ADDRESS HOSTING MYSQL]', 'PORT': '3306', } } Also using PyCharm, I have even opened up a data source in the Data Sources Tool Window and connected through SSH tunnel and MySQL authentication to the database. This is successful, and it is possible to make queries. However, I try to run: manage.py check and I receive: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '[REMOTE SERVER … -
django/rest: User registration API shows""Authentication credentials were not provided."
I'm trying to create an API for user registration in django 1.11.5 and python 3.5. When I write http://127.0.0.1:8000/users/:register/ in my browser I get the message: HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Authentication credentials were not provided." } If I run the rest-api user registration from rest-auth/registration it's working. But I want to configure my own API. Do you know how to fix this and make my API to work properly? This is my serializers.py: from users.models import User from rest_framework import serializers class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['user_id', 'firstname', 'yearofbirth', 'lastname','othernames'] def create(self, validated_data): user = User.objects.create( user_id=validated_data['user_id'], firstname=validated_data['firstname'], yearofbirth=validated_data['yearofbirth'], lastname=validated_data['lastname'], othernames=validated_data['othernames'] ) user.set_password(validated_data['password']) user.save() return user This is my views.py: class UserRegister(CreateAPIView): serializer_class = RegisterUserSerializer token_model = TokenModel def create_auth(request): serialized = RegisterUserSerializer(data=request.data) if serialized.is_valid(): User.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'] ) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) This is my models.py: class User(models.Model): user_id = models.CharField(max_length=255, default="00") firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255, blank=True) othernames = models.CharField(max_length=255, blank=True) yearofbirth = models.SmallIntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2018)]) And this is my urls.py: url(r':register/$', views.UserRegister.as_view(), name='register-user'), -
Saving many-to-one data from form Django
I am creating a job board site. I have the following models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) details = models.TextField(max_length = 2000) salary = models.CharField(max_length = 20) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name A user can register as an employer just fine, but I am having problems getting Jobs to save to the database. Once a user registers/logs in as an employer they are redirected to employer_home.html, where an employer can post a job: {% extends 'core/base.html' %} {% block body %} <h1>Post a Job</h1> <form> {% csrf_token %} {{ form.as_p }} <button type="submit">Post</button> </form> {% endblock %} Here is my forms.py: from django.forms import ModelForm from .models import Job from django.contrib.auth.models import User … -
django authorization using a many to many table
Here are the docs and an example of a many to many relationship in a different post How to add column in ManyToMany Table (Django) now in order to use a many to many relationship in django must we specifiy a many to many relationship in one of the fields? Example: User permissions in my app are below. But First many to many code example. Extra fields on many-to-many relationships class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) now my use I have a user permissions and venue. Multipule users can have Multipule permissions on Multipule venues. so create permissions table: class VenuePermissions(models.Model): Venue = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True) create user table: class User(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) avatar = models.ImageField() #add to datejoined = models.DateTimeField(auto_now_add=True) isauthenticated = models.BooleanField(default=False) is_active = models.BooleanField(default=True) isactingclient = models.BooleanField(default=False) isonlyclient = models.BooleanField(default=False) venuepermissions = models.ManyToManyField(VenuePermissions, through='Authorization') # fields required by django when extending user model USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['email', 'firstname', 'lastname'] EMAIL_FIELD = 'email' def get_full_name(self): """ Returns: The … -
How to Make Django Rest Framework work with CASSANDRA ENGINE?
How can I use DRF to send data (JSON) to Cassandra and receive needed? -
Multiple inheritance and deleting an object in Django
I've got a multiple-inheritance scenario that includes polymorphic base classes, and deleting has become a real headache. Here are the relevant models: class Stimulus(PolymorphicModel): stimulus_id = models.AutoField(primary_key = True) #prevent name clashes in multiple-inheritance scenarios class Meta: verbose_name_plural = "Stimuli" class Vitals(models.Model): vitals_id = models.AutoField(primary_key = True) #prevent name clashes in multiple-inheritance scenarios name = models.CharField(max_length=255) dob = models.DateField() species = models.ForeignKey(Species, on_delete=models.CASCADE) sex = EnumField(Sex, max_length=1) portrait = FilerImageField(null = True, blank = True) bio = models.TextField(null = True, blank = True) def __str__(self): return self.name + "(" + self.species.common_name + ")" class Meta: verbose_name_plural = "Vitals" class Human(Stimulus, Vitals): user = models.OneToOneField(User, on_delete=models.CASCADE, blank = True, null = True) phone_number = PhoneNumberField(null = True, blank = True) def get_name(self): return self.vitals.name def __str__(self): return self.name class Ambassador(Stimulus, Vitals): social_group = models.ForeignKey(SocialGroup, on_delete=models.CASCADE, null = True, blank = True) home_containment = models.ForeignKey(HomeContainment, on_delete=models.CASCADE) handlers = models.ManyToManyField(Human, through='HandlerClearanceRecord', related_name='handlers') def __str__(self): return self.name I can create Humans and Ambassadors with impunity, but if I try to delete one of them via the admin interface (either through Vitals or Humans/Ambassadors), I get: type object 'Vitals' has no attribute 'base_objects' OK, so after Googling around, I found this, which suggests that I … -
Django - template build-in filter tags {% url %}
I am a new coder with Django. So, first apologize for it if this question is too easy. <form action = "{% url 'post:comment' the_topic=topic user_id=1 %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> I am trying to use url tag to call a function is views.py. topic is a variable I passed in when this page is created. this is my code in urls.py url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"), then this is how I do in views.py def comment(request, the_topic, user_id): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': the_topic} # save the data in database save_comments_into_database(the_topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': the_topic}) I get the NoReserveMatchException: exception screenshot I really don't get where it goes wrong. … -
Django: The SECRET_KEY setting must not be empty even if it exists in settings
I'm using python 3.5 and django 1.11.5 in windows 7. I have settings folder that contains base.py, mysql.py and sqlite.py manage.py contains: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GuardianAngel.settings") When I try python manage.py makemigrations I get the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 206, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "c:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "c:\Python35\lib\site-packages\django\core\management\commands\migrate.py", line 15, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "c:\Python35\lib\site-packages\django\db\migrations\autodetector.py", line 13, in <module> from django.db.migrations.questioner import MigrationQuestioner File "c:\Python35\lib\site-packages\django\db\migrations\questioner.py", line 12, in <module> from .loader import MigrationLoader File "c:\Python35\lib\site-packages\django\db\migrations\loader.py", line 10, in <module> from django.db.migrations.recorder import MigrationRecorder File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module> class MigrationRecorder(object): File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration app = models.CharField(max_length=255) … -
MultiValueDictKeyError when getting a Post Value in Django
I'm trying to create an online store in Django. In the views file, I'm looping through the list to see if the product id matches what the user submitted. However, I keep getting "MultiValueDictKeyError". Is there a way I can fix this? VIEWS FILE def index(request): products = { "items" : items } return render(request, "app_main/index.html", products) def buy(request): for item in items: if item['id'] == int(request.POST['i_id']): ##<<--THIS IS WHERE IT ERRORS amount_charged = item['price'] * int(request.POST['quantity']) try: request.session['total_charged'] except KeyError: request.session['total_charged'] = 0 try: request.session['total_items'] except KeyError: request.session['total_items'] = 0 request.session['total_charged'] += amount_charged request.session['total_items'] += int(request.POST['quantity']) request.session['last_transaction'] = amount_charged HTML FILE <table> <tr> <th>Item</th> <th>Price</th> <th>Actions</th> </tr> <tr> {% for i in items %} <td>{{ i.name }}</td> <td>{{ i.price }}</td> <td> <form action='/buy' method='post'> {% csrf_token %} <select name='quantity'> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <input type='hidden' name='{{ i.id }}'/> <input type='submit' value='Buy!' /> </form> </td> </tr> {% endfor %} </table> -
Django inline model form edit
Using twitter as an example (on the settings / profile edit page) they have a lot of fields where you can edit and then hit save and update things without having to go through an entire form or display an entire form. Instead it's broken down by susection. How would I implement something similar for a django model? -
Is it possible to assign django channels group in connection?
I hope you're all right: my question is whether I can make a connection to web socket from the client to a specific group, I'm currently connecting customers as follows: //connecting client with js var ws_scheme = window. location. protocol == "https:"? "wss":"ws"; //var ws_path = ws_scheme +': //' + window. location. host + "/sync/"; var ws_path = ws_scheme + ": //localhost: 8001"; console. log ("Connecting to " + ws_path); var socket = new ReconnectingWebSocket (ws_path); Okay, that's how it works, The problem is that I want each client to connect to a group created previously example: def ws_connect (message): for x in users: Group (x). add (message. reply_channel) and so sent the message to the respective group Group ("group1"). send ({' text': json. dumps (msg)}) Group ("group2"). send ({' text': json. dumps (msg)}) -
Django multiple database ProgrammingError
I'm trying to fetch data using raw query from mysql. cursor = connections['database2'].cursor() try: cursor.execute("select * from blog") finally: cursor.close() But It throwing following error ProgrammingError at /api/blog/ relation "blog" does not exist LINE 1: select * from blog -
Django - built-in templates tags with variables
I am a new coder with Django. <form action = "{% url 'post:comment' topic=topic user_id=1 %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> I am try to use this code to make a comment function for my website. The following is some relevant functions: def comment(request, topic, user_id): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': topic} # save the data in database save_comments_into_database(topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': topic}) the namespace is already be named as "post" in urls.py However, I get this exception Exception Type: NoReverseMatch Exception Value: Reverse for 'comment' not found. 'comment' is not a valid view function or pattern name. Why the comment function cannot be matched? -
Django template custom form using text area not working
I am using custom template for django form, so i loop over the form fields and create hidden textarea boxes. On hitting the submit button i call the function save code which fills in value of textarea. Earlier i was using input html instead of textarea and it was working fine but I need multiple line value in my form (html input is only single line) so i had to change it to textarea But now probably i am getting 'this field is required' error! (the procedure is same, when i had input tag i did performed document.getelementbyid('id-name').value = required stuff) So i am confused why is it not working with textarea <form method="post" action="{% url 'problem' problem.problem_ID %}"> {% csrf_token %} {% for field in code_form %} <textarea id="{{ field.id_for_label }}" value="{{ field.value }}" style="visibility:hidden;"></textarea> {% endfor %} {% buttons %} <button onclick="save_code()" type="submit" class="btn btn-success center-block">Submit editor</button></td></tr> {% endbuttons %} </form> -
Generating Table of Contents in a Django Blog
How do I dynamically generate table of contents for every post in a Django blog? Thanks in anticipation! -
Running "coverage html" crashes
I'm new to the coverage library for python. But I've immediately encountered a problem and I can't find mention of it on google.. In my virtual environment (pipenv) I do: pipenv install coverage==3.6 coverage run manage.py test <app-name> coverage report coverage html All of them work nicely, I get a nice text report in my shell, but when I run coverage html it crashes... Traceback (most recent call last): File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\parser.py", line 571, in _arcs ch = byte_chunks[byte] KeyError: 22318 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\programming\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\programming\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Win7\.virtualenvs\app-87mb2psT\Scripts\coverage.exe\__main__.py", line 9, in <module> File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 710, in main status = CoverageScript().command_line(argv) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 452, in command_line **report_args) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\control.py", line 615, in html_report return reporter.report(morfs) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 90, in report self.report_files(self.html_file, morfs, self.config.html_dir) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\report.py", line 84, in report_files report_fn(cu, self.coverage._analyze(cu)) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 164, in html_file missing_branch_arcs = analysis.missing_branch_arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 127, in missing_branch_arcs missing = self.arcs_missing() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 88, in arcs_missing possible = self.arc_possibilities() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 76, in arc_possibilities arcs = self.parser.arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\misc.py", line 73, in _wrapped setattr(self, … -
Module Not Found Error: No Module Named 'my_project.settings' django gunicorn
I am trying to deploy on heroku but first I am trying to run on my machine but I keep getting the Module Not Found Error. My directory structure looks like this: To make it more clear, I have a folder called 'imperialtheatre' that holds the venv and requirements and inside that folder i have a folder called 'imperialtheatre' which holds the django project with manage.py etc. Why am I getting this error? I am running this command: gunicorn imperialtheatre.imperialtheatre.wsgi:application -t 120 -w 8 -k gevent --max-requests 250 --log-level debug wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imperialtheatre.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Django Mongoengine leading whitespace being stripped
I have a small issue that I'm struggling to find a solution on. Currently when I recieve the result from a POST with JSON data all leading whitespaces in some of the values as completely gone but all in between the words saved. Is there a setting for MongoEngine that stops this on StringFields?