Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post empty date field error with Django rest framework
#model.py class Form(models.Model): no = models.IntegerField() finish_date = models.DateField(blank=True, null=True) >http http://127.0.0.1:8000/api/forms no=112 "finish_date"="" Return error: "finish_date": [ "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]." ] If I set "finish_date" to null , this post works. And StringField(blank=True, null=True) will not get the error. How to solve? -
many to many table in django without using manytomanyfield
rather than using the models.ManyToMany field in django i just set up a intermediary field with a bunch of foreign keys. is there any reason why this wouldn't work. I can't think of any but why not see if any of you have tried the same. class Authorization(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) permission = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True) #venue = models.ForeignKey(venue) <-- commented out cause I haven't made the model its referencing yet. -
Django - Comment form in an existing template. How to define it in views.py?
I have 4 models: Post, Comment, Blogger and User. I have an post_description template, in below of that, i has placed an comment form. But how to define it in views? I'm getting problem in - to get its username, like the user who is logged in will be stored as "posted_by" and in which blog post he post will be stored as "topic" of the blog. How to store these information, so they automatically get added? Form that i has described in post_desc.html {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="text" name="comment" style="width: 800px; height: 145px;"> <button type="submit">Submit Comment</button> </form> {% else %} <p><a href="{% url 'login' %}">Login</a> to comment</p> {% endif %} Current view of that post_desc: def post_desc(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_desc.html', {'post': post}) -
Python not importing dotenv module
I am setting up an imageboard that uses Django and when i try to load manage.py for the first time i am greeted with this error message Traceback (most recent call last): File "./manage.py", line 3, in import dotenv ImportError: No module named 'dotenv' I have tried using python-dotenv rather than dotenv and it still doesn't work. Any solution for this? -
Automatically update a field on one model after saving another [Django 1.11][Python3.x]
I am learning how to use the post_save signal on Django. Though I am not getting any errors, what I want to do will not work. I have a model (Model) that is supposed to aggregate and average the ratings from the Review model and saves that number in a field called "average_rating." I want the averaging to be done once a user provides a rating on the "Review" model and for the average rating to automatically be calculated and updated on the "Model" model. I know that I can do this with a post_save signal. But I am not sure how. How can I do what I am trying to do? Thanks in advance. models.py from django.db import models from django.db.models import Func, Avg from django.urls import reverse from django.template.defaultfilters import slugify from django.db.models.signals import post_save from django.dispatch import receiver class Model(models.Model): name = models.CharField(max_length=55, default='') slug = models.SlugField(unique=True) average_rating = models.DecimalField(decimal_places=1, max_digits=2, default=0.0, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.average_rating = self.review_set.aggregate( rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating'] self.slug = (slugify(self.name)) super(Model, self).save(*args, **kwargs) class Review(models.Model): RATING_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ] model = models.ForeignKey(Model, null=True) rating = models.IntegerField(choices=RATING_CHOICES, default=1) review_date … -
NameError: name 'Honeywords' is not defined ; custom password hasher
hye im little bit confused on how to define Honeywords actually . can anyone help me ? im trying to create a custom password hashers called Honeyword and i already create an app called honeywordHasher and already install it in INSTALLED_APP in settings.py . i manage to make the django to not hash the password by default and use my honeywordHasher but unfortunately it did not store in the db . can anybody give a tip on how to fix this ? i try to figure out this for a week already hashers.py : def salt(self) salt = get_random_string() while Honeywords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt -
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