Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple File Upload inside a inlineformset
Hi I would like to know if it's possible to have a multiple file upload field within a formset. The structure is as following: I have a parent model who get a one to one relationship with one of his possible child. The child have several inline formset with other specific models. And one of those formset need to contain a multiple file upload. They are all edited in the same view. The parent and the related child get created before going to that edit view. This is a capture of my database structure (there is a missing table on the right): Just to give you a vague idea I have: a Task model which have a 1to1 to a GeneralApplicationTask which have a many to one relationship with GeneralApplicationProperty(this is what is used in the inlineformset) So for each GeneralApplicationTask Form I have some fields and then several formset containing property information and each need to contain a multiplefile upload. The problem I am facing is, if I create a modelForm to manage the files and create a Mt1 from the GeneralApplicationProperty model, then I cant properly save the files because I need to know which form (and the … -
old javascript script code in chrome inspect than editor
I am making my personal portfolio using Django and I was writing a javascript for contact form and it is getting some old javascript code I don't know from where. The code I wrote in my script in the editor is new but when I am inspecting in chrome it's showing some old code for the same script file -
How to send data in POST fetch request from one domain and process request on server listening on different domain?
I will admit I don't understand this part of the web technologies. I have a python django app running on localhost:8000 and react client SPA running on localhost:3000. I have implemented REST APIs on the server using django rest framework and I am calling a couple of APIs from the client in browser. There is a issue of CORS which I have patched using django cors headers app. I am able to use GET APIs like this and that is working fine till now. fetch("http://localhost:8000/api/comments", { method: "get" }).then((response)=> { console.log("got response"); return response.json(); }).then((comments) => { console.log("got json", comments); this.setState({ comments: comments }) }).catch((error)=> { console.log("error", error); }); Second I have POST API where add commenter's name, I have tried different variations to call this API, but not with much success. All the variations have one issue and that is, the request body is empty, browser network tab and logs in views.py method agree on that. var headers = new Headers(); // Add a few headers headers.append('Content-Type', 'application/json'); headers.append('X-Requested-With', 'XMLHttpRequest') let payload = { "first_name": first_name.value, "last_name": last_name.value }; var data = new FormData(); data.append( "json", JSON.stringify( payload ) ); const request = new Request("http://localhost:8000/api/user", { method: 'POST', mode: … -
Where to learn advanced/beyond-basic Django web
Hi guys I’m new to web dev and Django but I’ve learnt all the basics and now want to develop my skills. I’ve created some web apps that aren’t too complex since I’m struggling to find follow-along content for advanced web Django dev. Where can I find some? -
clamav timing out when scanning stream for large file
Have a React/Django app that a small group of clients use to submit files to us. Using react-dropzone for the file upload, without any maxSize specified, so it should be react-dropzone causing the issue. The file I'm working with is an Excel file of about 160MB. When the files are uploaded, clamav (called from Django) scans the files in stream before writing to disk. I have run into issues in the past with clamav and default maximum file sizes being removed, so I have those either removed or set very high. Initially it was timing out after 30 seconds. I looked at the scan.conf for anything related to time and 30, which brought me to IdleTimeout which defaults to 30. I changed it to 360 and now it times out after about 90 seconds. Nothing in the scan.conf has a 90 associated with it, so I'm puzzled as to what else I could change to get this to work. These are settings I've changed and the value I have them at: LogFile /home/log/clamd.log LogTime yes LogSyslog yes LogVerbose yes LocalSocket /var/run/clamd.scan/clamd.sock StreamMaxLength 2048M ReadTimeout 360 IdleTimeout 360 MaxScanSize 0 MaxFileSize 0 OnAccessMaxFileSize 0 # 0 disables any limit Any suggestions … -
Invalid block tag on line 21: 'transaction'. Did you forget to register or load this tag?
I am getting the error on the transaction models, not sure what i am missing. See the error below i am on the view from django.db import models class Status(models.Model): description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "status" def __str__(self): return self.description class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) password = models.CharField(max_length=128) created_at = models.DateTimeField() updated_at = models.DateTimeField() signed_agreement = models.BooleanField() class Meta: db_table = "users" def __str__(self): return self.first_name + ' ' + self.last_name class Inventory(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "inventory" def __str__(self): return self.description class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE,related_name='inventory') checkout_time = models.DateTimeField() scheduled_checkin_time = models.DateTimeField() actual_checkin_time = models.DateTimeField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "transactions" def __str__(self): return self.user.first_name + ' ' + self.inventory.description -
psycopg2 copy_from csv with null foreign key field
I'm downloading a CSV file from a URL then trying to load it into a PostgreSQL table using copy_from. On the Product model there's a foreign key field, nutrition, with null=True. class Product(models.Model): ... nutrition = models.ForeignKey( NutritionFact, blank=True, null=True, on_delete=models.SET_NULL, ) In the file a null nutrition field is represented by an empty string ("") which is causing an error: psycopg2.DataError: invalid input syntax for integer: "" CONTEXT: COPY product_product, line 1, column nutrition_id: "" def copy_from_csv(model, reader): opts = model._meta table = f'{opts.app_label}_{opts.model_name}' columns = next(reader) # first row of csv is columns buffer = io.StringIO() writer = csv.writer(buffer, delimiter='\t') for row in reader: writer.writerow(row) model.objects.all().delete() buffer.seek(0) with closing(connection.cursor()) as cursor: cursor.copy_from( buffer, table=table, sep='\t', columns=columns, ) I've tried csv.writer(buffer, delimiter='\t', escapechar='\\', quoting=csv.QUOTE_NONE) but the error persists. -
Can't convert Request to PhoneNumber. django rest custom token auth
I am trying to create custom token authentication end point which accepts phone number and token and status in request POST then response shoud ba as follows Successful response should create a status object linked to the user object Failing request can be either unauthorized request or bad request based on auth-token/phone number combination. to do that I wrote following snippets: serializers.py class TokenSerializer(serializers.Serializer): phone_number = serializers.CharField(required=True, allow_blank=False) def validate(self, attrs): phone_number = attrs.get('phone_number') user = authenticate(request=self.context.get('request'),phone_number=phone_number) if user is None: msg = ('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = ('Must include "phone_number.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs views.py class TokenView(APIView): serializer_class=TokenSerializer authentication_classes = (CustomTokenAuthentication, ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data login(request,user) token, created = Token.objects.get_or_create(user=user) return Response({ 'user':new_data, 'token':token.key }) authbackend.py: class CustomTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, key,phone_number): try: user = UserProfile.objects.get(phone_number=username) return user except ObjectDoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). raise exceptions.AuthenticationFailed('Invalid phone ') try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') return (token.user, token) when try to login I got this … -
Access Django ManyToMany field values within Model.clean()
It seems (though I'm having trouble finding it in the Django documentation) that ManyToMany fields are deferred when they are selected in the Django admin, and so effectively not set, during the call to a Django Model's .clean() method. Here's an example to illustrate. models.py: import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ class Country(models.Model): code = models.SlugField(max_length=2, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class Region(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class SampleModel(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) regions = models.ManyToManyField(Region, blank=True) countries = models.ManyToManyField(Country, blank=True) field1 = models.PositiveIntegerField() field2 = models.CharField( max_length=3, choices=[("foo", "FOO"), ("bar", "BAR")] ) def clean(self, *args, **kwargs): print( "Got id=%s, regions=%s, countries=%s, field1=%s, field2=%s" % (self.id, self.regions.all(), self.countries.all(), self.field1, self.field2) ) if self.regions.exists() and self.countries.exists(): raise ValidationError(_("'Regions' and 'Countries' are mutually exclusive")) super().clean(*args, **kwargs) admin.py: from django.contrib import admin from my_app.models import SampleModel @admin.register(SampleModel) class SampleModleAdmin(admin.ModelAdmin): fields = ("regions", "countries", "field1", "field2") In Django shell after ./manage makemigrations && ./manage migrate: from my_app.models import Country, Region Country.objects.bulk_create([ Country(code="US", name="United States"), Country(code="UK", name="United Kingdom"), ]) Region.objects.bulk_create([ Region(name="North America"), Region(name="EMEA"), ]) Above, SampleModel overrides .clean() to enforce that regions and countries are mutually exclusive. (Specify one … -
【Django×Google App Engine】No module named 'MySQLdb' when deploying
I'm setting GitHub source ↓ https://github.com/priyankavergadia/Django-Dialogflow-GoogleVisionAPI But I have trouble in [Deploy the app to the App Engine standard environment] phase. At a glance Deploying have been done well.But I'm trying to access webservice, so [502 Bad Gateway] appears. At local environment(running python manage.py runserver), this program works well. Please give me some advices. My environment: ・Windows10 ・Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 ・django 2.2.4 ・MySQL second generation 5.7 mysql django I serched and tried. 1. install mysqlclient and uninstall PyMySQL 2. rewrite [import ~]part in various pattern... description in Django setting.py below # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter # See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers # for more information import MySQLdb as sql# noqa: 402 # [START db_setup] if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/michatbot-250809:us-central1:polls-instance2', 'USER': 'test', 'PASSWORD': '', 'NAME': 'polls', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: … -
django soft deleted objects appear in filters
I implemented soft deletion by adding a BooleanFeild "deleted" to my models, overriding the delete method for CASCADING deletion and updating deleted field and changing objects with a custom manager which filters deleted objs. the problem is when I'm filtering other models on relations, the deleted rows affect the result. here's an example of my implementation: models: class Model_B(models.Model): # somefields... class Model_A(models.Model): label = models.CharField(max_length=30) deleted = models.BooleanField(default=False) model_bs = models.ManyToManyField(Model_B, through='RelationModel') # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() def delete(self, *args, **kwargs): # first we set deleted flag of Zone to True self.deleted = True self.relationmodel_set.update(deleted=True) # save zone self.save() class RelationModel(models.Model): model_a = models.ForeignKey(Model_A, models.CASCADE) model_b = models.ForeignKey(Model_B, models.CASCADE) deleted = models.BooleanField(default=False) # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() manager: class BaseManager(models.Manager): """ this manager will filter deleted """ use_for_related_fields = True def get_queryset(self): return super().get_queryset().filter(deleted=False) class AllManager(models.Manager): """ all """ def get_queryset(self): return super().get_queryset() query: Model_B.objects.filter(model_a__isnull=False) this returns Model_B objects which has a relations to deleted Model_A objects too. I tried: Model_b.objects.filter(model_a__isnull=False, model_a__deleted=False) this one returns … -
How to dump an object that is a child of a class (knowing that class casting is impossible in Python)?
I have a 3 models: Entity, Person which is a child of Entity, and Agenda: class Entity(models.Model): is_physical = models.BooleanField(default=True) class Person(Entity): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) agendas = models.ManyToManyField('Agenda') def simple_desc(self): return str(self.user) if self.user is not None else '? no user ?' class Agenda(models.Model): owner = models.ForeignKey(Entity, blank=True, null=True, on_delete=models.CASCADE, related_name='owner') You (almost) can't do simpler! Now I would like to list all the owners of all the agendas starting with agendas like: for agenda in Agenda.objects.all(): print(agenda.owner.simple_desc()) Because owner is an Entity, it doesn't know about simple_desc() (which is in its child Person). It's impossible to cast the owner into a Person. How would you do? Note aside: Right now, all owner are Person, but in a near futur, I'll create Company(Entity) which could also be owner of an Agenda, so I need to keep my models like this, don't suggest to change this organization this is not a valid solution. It's important, I have a more complex query, to make my loop with Agenda (and not Person) -
Django annotate sum subquery
How to sum a field of a subquery ( with OuterRef ) and annotate it on outer model? note that I have a common my_special_queryset_annotator that alter queryset by adding some annotations, ... so i dont want to use direct Sum('books__sections__page') let assume following models class Library(models.Model): votes=models.IntegerField() class Book(models.Model): library=models.ForiegnKey(Library) class Section(models.Model): book=models.ForiegnKey(Book) pages=models.IntegerField() # this works, but when want to use `my_special_queryset_annotator` # we could not do this simple annotation Library.annotate( all_pages=Sum('books__sections__pages'), ) # when want to sum on a Subquery, its must constructed like below but it dont work Library.objects.annotate( all_pages=SUM( # <-- problem Subquery( my_special_queryset_annotator( Section.objects.filter(book__libraray_id=OuterRef('id')) ).values('altered_pages') ) ) ) -
ModuleNotFoundError: No module named view, models
Tenho o seguinte problema tenho duas app Quero que um model de uma dessas apps passe informação para outra app exemplo Projeto: APP1.models APP2.view View da APP2 from projeto.app1.models import ObjetoX objeto_x = ObjetoX(parm=1) Ao fazer isso surge o seguinte erro: ModuleNotFoundError: No module named 'projeto.app1' -
Managing Urls while clicking on User profile
I'm managing to send emails to users that are present in my table and then showing success message on the same page. I'm successfully sending email to users(taking their id and then their email to send). While creating urls, I need to mention id as well which redirects me to another page. But what I want is to be redirected on the same page. Here's the table which contains the users: After clicking Send Mail, I'm taking the userid then email with this and then sendig mail. Taking userid: <a href="{% url 'profiles:sendMails' id=p.id %}"></button><span class="badge badge-success">Send Mail</span></a> Here's my views.py code on this button: def sendMails(request, id=None): query_user = get_object_or_404(NewUser, id=id) user_email = query_user.user admin_email = request.user.email result = send_emails(request, admin_email, user_email) context = { 'code': result } return render(request,'requested_users.html', context) And urls.py: path('dashboard/requested_users/<id>', views.sendMails, name='sendMails'), What I want to be on same page even after sending mail(such that the urls will be): path('dashboard/requested_users/', views.sendMails, name='sendMails'), But if I'm not providing the id in the urls, it's giving me the error: Reverse for 'sendMails' with keyword arguments '{'id': 1}' not found. I know I've asked a long question, but I'm really stuck into this. Thank you in advance. -
Error while upgrading django cms to 3.5 migration of "cms.0018_pagenode" stops saying Cannot resolve keyword 'title_set' into field
I am trying to upgrade an existing project from django-cms 3.4 to 3.5. I have Django 1.8 and while migrating at some point it stops giving an error : django.core.exceptions.FieldError: Cannot resolve keyword 'title_set' into field. in the documentation for 3.5 they have this sentence: Never-published pages can no longer have a ‘pending’ publishing state. A data migration, cms/migrations/0018_pagenode.py, removes this. my problem seems to be related to this. Can somebody helm me with that? I don't get it. Applying cms.0017_pagetype... OK Applying cms.0018_pagenode...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 147, in apply_migration state = migration.apply(state, schema_editor) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/operations/special.py", line 181, in database_forwards self.code(from_state.apps, schema_editor) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/cms/migrations/0018_pagenode.py", line 38, in unpublish_never_published_pages publisher_public__isnull=True, File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) … -
telling the cmd what version of python im using
IM trying to make a website with django and im following a tutorial that is telling me i need to tell my cmd prompt what version of python im using. this is the video https://www.youtube.com/watch?v=FNQxxpM1yOs at the 10:46 mark he says to put C:/Python35/ python manage.py runserver. I am putting thi but it is not working. I am using version 3.7 so i replaced 35 with 37 but it is still not working. can someone please helps with this. -
Is raise ImproperlyConfigured is missing in django library
django library path: django\views\generic\detail.py class : SingleObjectTemplateResponseMixin why raise ImproperlyConfigured is not mentioned in 2nd last line of the code? class SingleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_field = None template_name_suffix = '_detail' def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_field`` field on the object instance that the view is operating upon (if available) * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If self.template_name_field is set, grab the value of the field # of that name from the object; this is the most specific template # name, if given. if self.object and self.template_name_field: name = getattr(self.object, self.template_name_field, None) if name: names.insert(0, name) # The least-specific option is the default <app>/<model>_detail.html; # only use this if the object in question is a model. if isinstance(self.object, models.Model): object_meta = self.object._meta names.append("%s/%s%s.html" % ( object_meta.app_label, object_meta.model_name, self.template_name_suffix )) elif getattr(self, 'model', None) is not None and issubclass(self.model, models.Model): names.append("%s/%s%s.html" % … -
How do i fix this issue with django start project?
after i installed django i wrote the start project command to verify django is working or not. i.e, django-admin startproject mysite cd mysite python manage.py runserver after that i got a ip address(http://127.0.0.1:8000/) but when i link to this http://127.0.0.1:8000/, it is showing unable to connect. what should i do now? -
Django POST method returns 500 server error on EC2 server
I am trying to build a web app using Django Rest framework. When I run the app on localhost 127.0.0.0/8000 it works fine. But when I deploy it on an EC2 server the POST methods return 500 server error. Here is one of the post methods in the views.py - class customer_location(APIView): def post(self, request, *args, **kwargs): customer_id = json.loads(request.body).get('customer_id') queryset = customers.objects.filter(cid= customer_id) serialize = customer_details(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) The urls.py is like this - from django.conf.urls import include, url from django.urls import path from rest_framework import routers from . import views urlpatterns = [ url(r'^customer_location/$', views. customer_location.as_view(), name='customer_location'), ] The DEBUG mode is set to False and the EC2 instance IP address is added in the ALLOWED_HOSTS. The GET methods are working fine but the POST methods give error. How to solve this ? -
Queryset with different datasets based on obj type
I want to implement in my application something similar to instagram's local notifications. The main problem is that local notifications can be different types. For example: 1) Simple one: "user started following you" (this is pretty straightforward) 2) More complicated: "user and +7 other liked your photo X" The first step of solution is to GROUP all notifications by targeted_user, event_type and user_who_triggered_event. For the first case it's okay as we will have all information. For the second case we will lack some information as Count of similar notifications. Also what if I need some additional information about those +7 user's who also liked photo X? class Notification(TimeStampedModel): OPEN_QUEST = 'open_quest' OPEN_PHOTO = 'open_photo' ACTION_CHOICES = ( (OPEN_PROFILE, _('Open profile')), (OPEN_PHOTO, _('Open photo')), ) LIKED_PHOTO = 'liked_photo' NEW_FOLLOWER = 'new_follower' EVENT_CHOICES = ( (LIKED_PHOTO, _('Liked photo')), (NEW_FOLLOWER, _('New follower')) ) action = models.CharField( max_length=255, choices=ACTION_CHOICES, ) event = models.CharField( max_length=255, choices=EVENT_CHOICES, ) title = models.CharField( max_length=255, ) body = models.TextField() class Meta: db_table = 'notifications' For this example I have 2 notifications in data base. Also I have ReceivedNotification model with FK to user and FK to notification and also data field(JSONField) to store actual information which particular user will … -
django ,model migrate: TypeError: an integer is required (got type str)
I am writing a apps and run makemigrations and migrate multiple time when i add new field. And now i have added a new foreignKey Field in models and then i run the command: python3 manage.py makemigrations after this, i run this command python3 manage.py migrate but it throws me following error TypeError: an integer is required (got type str) and later again i run this command pythion3 manage.py migrate --fake and i have successfully migrated and got another problem, when i go to django admin templates and click on my models to add data, it throws me this error: OperationalError at /admin/booking/seats/ no such column: booking_seats.seat_for_id I am not getting whats wrong with it, can anyone help me to fix this? for your reference, see my models: class Seats(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) seat_no = models.IntegerField( choices=SeatChoices.choices(), ) availability = models.IntegerField( choices=SeatAvailability.choices(), default=SeatAvailability.AVAILABLE ) seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) def __str__(self): return str(self.seat_no) class Show(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) show_schedule = models.IntegerField( choices=ShowSchedule.choices(), ) movie = models.CharField(max_length=50) def __str__(self): return str(self.show_schedule) I just added this new field seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) then i facing the problem Can anyone help me in this case? -
Chartjs in Django, special characters in label not supported?
I have some values passed to Chart.js but I found neither / nor - is supported. If the labels are harded coded as UK-aaa or N/A, it works fine. If it is passed as a varible which the project requires, UK or N (letters before the special characters will not recognized and no chart shows. Is there a workround on Javascript other than removing special characters in labels? Thanks. var C3 = document.getElementById(canv3.getAttribute('id')); if (C3.getContext) { if (C3.getContext) { new Chart(document.getElementById(canv3.getAttribute('id')), { type: 'bar', data: { labels: [{{res.21}},{{res.22}},{{res.23}}], //this is not supported if same value as below passed. //labels: ['UK-aaa','N/A','N/A'], //this is supported datasets: [ { backgroundColor: "rgba(35, 35, 0.5)", borderColor : "rgba(149, 62, 205, 1)", pointBackgroundColor: "rgba(62, 149, 205, 1)", data: [{{res.18}},{{res.19}},{{res.20}}] //numeric value }, ] }, options: { responsive: false, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); }} -
making modal for every entry in a list view using Js?
I have a page where multiple images are present and I want to make the users able to crop any of them so I made a for loop to make a modal for each image and I looped the js function also. this is my modal. {% for image in Patient_detail.images.all %} <div class="modal fade" id="modalCrop{{image.pk}}"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Crop the photo</h4> </div> <div class="modal-body"> <img src="" id="image{{image.pk}}" style="max-width: 100%;"> </div> <div class="modal-footer"> <div class="btn-group pull-left" role="group"> <button type="button" class="btn btn-default js-zoom-in"> <span class="glyphicon glyphicon-zoom-in"></span> </button> <button type="button" class="btn btn-default js-zoom-out"> <span class="glyphicon glyphicon-zoom-out"></span> </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Nevermind</button> <button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button> </div> </div> </div> </div> {% endfor %} and here's the function I used {% for image in Patient_detail.images.all %} $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#crop{{image.pk}").click(function () { var img_src = document.getElementById("img{{image.pk}}").src $("#image{{image.pk}}").attr("src", img_src); $("#modalCrop{{imahge.pk}}").modal("show"); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image{{image.pk}}"); var cropBoxData; var canvasData; $("#modalCrop{{image.pk}}").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", … -
django usercreationform is_valid always return false
i'm green hand to django, when i try to use the usersignupform, the request post is like `<QueryDict: {'csrfmiddlewaretoken': ['Wxlj42vbyAweKevBeSs5TvGj1ot8tJknUOGzmlKCphs5cDnqvsmriCSK9wYDuAof'], 'username': ['dulong11'], 'email': ['stephen.du@abc.com'], 'password1': ['dulong'], 'password2': ['dulong'], 'submit': ['']}` then the usercreationform.is_valid() will always return false, i do not know why, and how it happens? why it cannot work?? form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserSignUpForm(UserCreationForm): #username = forms.CharField() email = forms.EmailField(max_length=100) #password1 = forms.CharField() #password2 = forms.CharField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2') register.html <form action="." method="post" id="frm" class="frm"> {% csrf_token %} <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="text" name="username" placeholder="用户名" autocomplete="off"> <span class="error" id="tel_error"></span> </div> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="email" name="email" placeholder="请输入邮箱" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password1" placeholder="请输入密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password2" placeholder="请再次输入你的密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="protocol"> <span class="checkbox-checked" id="accept">我已阅读并同意<a href="#" target="_blank">《IPLink用户协议》</a>和<a href="#" target="_blank">《隐私保护》</a></span> </div> </div> <div class="r-list"> <span class="error"></span> <!--a href="#" class="btn" id="btn">同意协议并注册</--a>--> <button type="submit" class="btn" name="submit" id="btnSubmit" style="width:380px">同意协议并注册</button> </div> </form>