Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to import path from django.urls
Tried to run command: from django.urls import path Getting error: Traceback (most recent call last): File "< stdin >", line 1, in ImportError: cannot import name 'path' I am using django version (1, 11, 7, 'final', 0) -
serializer returning user_id violates null constraint
I'm trying to add a Invoice object from a json object, where two of the parameters is foreign keys (id's) to Currency and Account. however when i execute i keep getting null value in column "user_id" violates not-null constraint. why am i getting this error when im setting it as PrimaryKeyRelatedField? JSON {'currency': 2, 'task': 1, 'deposit_amount': 1.005, 'receive_amount': 62793.51, 'user': 23} Serializer class InvoiceSerializer(serializers.Serializer): deposit_amount = serializers.FloatField() receive_amount = serializers.FloatField() user = serializers.PrimaryKeyRelatedField(read_only=True) currency = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('currency', 'task', 'deposit_amount', 'receive_amount', 'user') read_only_fields = ('created_at', 'updated_at') def create(self, validated_data): return Invoice.objects.create(**validated_data) View class InvoiceViewSet(viewsets.ModelViewSet): lookup_field = 'user' queryset = Invoice.objects.all() serializer_class = InvoiceSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) if self.request.method == 'POST': return (permissions.IsAuthenticated(),) return (permissions.IsAuthenticated(),) def create(self, request): request.data['user'] = request.user.id serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Google Cloud Platform: "cloud_sql_proxy.exe' is not recognized as an internal or external command, operable program or batch file."
I'm currently trying to follow Google's guide for Running Django on App Engine Standard Environment: https://cloud.google.com/python/django/appengine I get to this set of instructions: Start the Cloud SQL Proxy using the connectionName from the previous step. cloud_sql_proxy.exe -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:3306 Replace [YOUR_INSTANCE_CONNECTION_NAME] with the value of connectionName that you recorded in the previous step. I do this and end up with the message "cloud_sql_proxy.exe' is not recognized as an internal or external command, operable program or batch file." Does anyone know how to fix this? -
Django wagtail adding favicon to root page
I think adding a favicon field for all the page models is not a good way. How can we customize the settings/sites root page to have an image field for favicon? -
Getting started with django-restframework-gis on Windows 10
I have some experience with Python-Django including its REST framework, a reasonable understanding of geographic information (and what GIS is about) and about databases, and I would like to develop a "geo-aware" REST service on my Windows machine based on Django. The application shall be limited to the REST service; visual exploration and other stuff shall be developed independently. Side-remark: once my application is running, it will be ported onto a Linux machine and PostGIS will then be used instead of SpatialLite. After several hours of web-searching, I still haven't come up with a good "Quickstart" guide. There are many tutorials and docs about various aspects related to my task, but they either refer to Linux, or their installation instructions are outdated. Here is what I have done so far: 1) I use miniconda and Pycharm 2) I created a new virtual environment like so: conda create -n locations pip numpy requests activate locations conda install -c conda-forge django djangorestframework djangorestframework-gis 3) I set-up the new Django project and my application and performed a database migration: python [path-to..]\django-admin.py startproject locations cd locations python [path-to..]\django-admin.py startapp myapp cd .. python manage.py migrate 4) I added "rest_framework" and "myapp.apps.MyAppConfig" to the APPLICATIONS … -
Ordering of nested objects using a through model in DRF
i'm using Django rest framework and serialising child objects, but the ordering of the nested objects doesn't seem to be working for me. My models are: ``` class Policy(models.Model): labels = models.ManyToManyField(ClassificationLabel,through='PolicyMemberClassificationLabel') class PolicyMemberClassificationLabel(models.Model): label = models.ForeignKey(ClassificationLabel, related_name='memberLabels') policy = models.ForeignKey(Policy, related_name='parentPolicy') order = models.PositiveSmallIntegerField(blank=True) class Meta: ordering = ['order'] class ClassificationLabel(models.Model): #more model attributes I would like the ordering of the child objects to be based on the order attribute for that model. For example: [ { "displayName": "Policy1", "labels": [ { "displayName": "label1", <=order=1 }, { "displayName": "label2", <=order=2 }, { "displayName": "label3", <=order=3 } ], } ] This isn't working and i'm not getting any sensible ordering for them. I've tried ordering via the model's meta class, and have looked elsewhere on here (like here). I have also tried queries such as returnedPolicy = (Policy.objects.filter(groups__uniqueId__in=allGroups).distinct().order_by('policymemberclassificationlabel__order')[:1]) but these tend to throw FieldErrors. How can I get the returned object to have ordered nested objects based on the through model attribute if i'm querying via the Policy object? -
Push to Heroku failing (Django)
remote: /app/.heroku/python/lib/libpython2.7.a: error adding symbols: Bad value remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PyPOxE/mod-wsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-Ya8Bxl-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-PyPOxE/mod-wsgi/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to testapp. remote: To https://git.heroku.com/testapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/testapp.git' I've been trying to push my Django website to Heroku for the past 2 days and this is the furthest I've gotten. I keep getting this error when running git push heroku master. I've looked at almost every single thread on SO and other websites regarding these errors and no luck. Any help is greatly appreciated! -
Can't get curl to work on windows properly when calling django
I am attempting to make curl work on windows using a bash script. I'm using the git unix tools to make this work. When I run the script, the token from the first request prints twice, and then the error runs: djangocurl.bash: line 15: -X: command not found LOGIN_URL="https://www.myapi.com/login/" FEEDBACK_URL="https://www.myapi.com/packagefeedback/" YOUR_USER="myemail" YOUR_PASS="mypassword" CURL_BIN1="curl -s $LOGIN_URL" CURK_BIN2="curl -s $FEEDBACK_URL" PACKAGE_ID=$1 FEEDBACK=$2 RATING=$3 RESPONSE=$($CURL_BIN1 -d "email_id=$YOUR_USER&password=$YOUR_PASS" -X POST "$LOGIN_URL" | jq -r '.token') ECHO "$RESPONSE" RESPONSE2=$($CURL_BIN2 -X POST "$FEEDBACK_URL" -H "Authorization: Bearer " + "$RESPONSE" -d "package_id=$PACKAGE_ID&feedback=$FEEDBACK&rating=$RATING") ECHO "$RESPONSE2" Is there something I'm doing wrong? -
Django forloop.counter0 to read a list
read a list in a list in the template with example: a_list = ['a', 'b', 'c', 'd'] new_list = [1, 2, 3, 4] how to access to new_list value in the template {% for value in a_list %} <h2>{{ a_new_list.forloop.counter.0 }}</h2> {% endfor %} i do this and It's not work! -
Django unmanaged model returns empty queryset whereas pgcli is not
I've created a view table in Postgres, which consists of fields (a,b_id,c: date, integer foreign key and decimal) Then I've created Django model: class model(Model): class Meta: managed = False db_table = 'table' a = models.DateField(primary_key=True) b = models.ForeignKey(<>) # also checked with b_id=IntegerField() c = models.DecimalField(max_digits=15, decimal_places=6) Problem is, when I query it via Django ORM, it returns an empty queryset. When I'm running the same exact query in pgcli, it returns the rows I need. I'm pretty much sure the database is the same (checked on other managed models of the app). How do I debug and fix this kind of issue? -
How do I host a Django project on Google Cloud Platform?
I've never seen anything so convoluted, tedious, and non-user friendly in my life...can anyone tell me how I can easily host my Django Project on Google Cloud Platform? Or just link me to a detailed video guide? Thanks. -
Trouble Serving Django Static Files
I'm having a lot of difficulty serving static files using runserver. I've included the configurations below, can someone help? STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Here is the top of my base.html file: <!DOCTYPE html> {% load static %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> What I have done so far: I have already issued the 'python manage.py collectstatic' command, and only 'admin' static files where placed in the /staticfiles directory. When running the command 'python manage.py findstatic css/style.css --verbosity 3' I get the following results: C:\Users\john.doe\Desktop\sysnet>python manage.py findstatic css/style.css --verbosity 3 No matching file found for 'css/style.css'. Looking in the following locations: C:\Python27\lib\site-packages\django\contrib\admin\static C:\Users\john.doe\Desktop\sysnet> Why is it searching Python27\lib\site-packages\django\contrib\admin\static ? I'm guessing this is is why the collectstatic command did not place files from /static in the /staticfiles? I have included the directory structure below (minus the files), can anybody help? sysnet ├───.idea ├───chef │ ├───migrations │ └───templates ├───static │ ├───css │ ├───img │ └───js ├───staticfiles │ └───admin │ ├───css │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor │ ├───jquery │ └───xregexp └───sysnet … -
NoReverseMatch at / Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}'
Everytime I run my django project, I get this error NoReverseMatch at / Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}'. I want to list my products and to be honest, I don't even know what the problem is. Full trace: django.urls.exceptions.NoReverseMatch: Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}' not found. 1 pattern(s) tried: ['(?P\w+)/$'] [29/Nov/2017 22:18:22] "GET / HTTP/1.1" 500 180670 My main URLS from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('shop.urls', namespace = 'shop')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) My Models.py page from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=120 , db_index = True) slug = models.SlugField(max_length=200 , db_index = True , unique= True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', kwargs={'slug':self.slug}) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index = True) slug = models.SlugField(max_length=200, db_index = True) image = models.ImageField(upload_to='products/%y/%m/%d', blank=True) description = models.TextField(blank = True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now= … -
Django post_save: database not yet updated?
I'm writing a Django application for ordering stuff. All orders have a certain type Type. If Type.is_common == true, it needs to be included in a delivery no matter if a user orders this type or not. I'm using a post_save signal to check if my db already has a common order for a user for a certain delivery. Here is the code: @receiver(post_save, sender=Order) def create_common_order(sender, instance=None, created=False, **kwargs): """ This signal handler creates common orders (if delivery type definition contains any common types) for every first order of a user for a certain delivery. """ # Don't handle this if the order is not for a delivery if not created or not instance or not instance.delivery: return # Don't handle Order with common types if instance.type.is_common: return # Loop through all types in type definition of delivery for t in Type.objects.all(): # Look for a 'is_common' type if type.is_common: # Get or create an order with the respective values Order.objects.get_or_create( delivery=instance.delivery, user=instance.user, type=type, defaults={'count':1} ) My problem is the following: From time to time it happens that two common orders are created (if two new orders are created at almost the same time). But why? Is the db … -
Django arguments to run migration in different ways
In my app, I currently have a data migration which uses the Steam API, and takes a few hours to build the database: class Migration(migrations.Migration): def forward(apps, schema_editor): """ Generates Game and Tag entities from the SteamSpy and SteamStore APIs. Takes a long time. Testing should use --keepdb flag. """ print() Game = apps.get_model("game_finder", "Game") Tag = apps.get_model("game_finder", "Tag") multiplayer_tags = {'Multiplayer', 'Local Multiplayer', 'Co-Op', 'Co-op', 'Online Co-Op', 'Local Co-Op', 'Massively Multiplayer'} all_tags = {} print("Generating Games and Tags.") content = get_json_response("https://steamspy.com/api.php?request=all") if content: items_len = len(content.keys()) counter = 0 for appid, game_data in content.items(): counter += 1 game_tags = [] game_multiplayer_tags = [] if game_data['tags']: game_tags = game_data['tags'].keys() game_multiplayer_tags = game_tags & multiplayer_tags missing_tags = game_tags - all_tags.keys() # Creates tags as needed. for item in missing_tags: print("Creating Tag: {}".format(item)) if item in multiplayer_tags: tag = Tag(name=item, is_multiplayer=True) else: tag = Tag(name=item) tag.save() all_tags[item] = tag # Creates Games. game_name = game_data["name"] print("Creating Game: {} ({}/{})".format(game_name, counter, items_len)) if len(game_multiplayer_tags) > 0: price = get_price(appid) game = Game(appid=int(appid),title=game_name,price=price, is_multiplayer=True) game.save() else: game = Game(appid=int(appid), title=game_name) game.save() for key in game_tags: game.tags.add(all_tags[key]) game.save() def backward(apps, schema_editor): """ Deletes all Game and Tag entries. """ Game = apps.get_model("game_finder", "Game") Tag = … -
Django custom User model throwing SystemCheckError - The field 'username' clashes with the name 'username'
I'm writing a custom User model in Django, inheriting it from AbstractUser as is mentioned in the official Django tutorials. But this throws an error. django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: redditauth.RedditUser.username: (models.E006) The field 'username' clashes with the field 'username' from model 'redditauth.reddituser'. Here is the code I wrote for the custom user model. class RedditUser(AbstractUser): username = models.CharField(unique=True, primary_key=True, validators=[validate_reddit_username], max_length=20) token = models.CharField(max_length=256) USERNAME_FIELD = username REQUIRED_FIELDS = ['token'] def reddit(self): with open('secret.json', 'r') as f: secret = json.load(f) return praw.Reddit(client_id=secret['client_id'], client_secret=secret['client_secret'], refresh_token=self.token, user_agent='Plan-Reddit by /u/SkullTech101') I have tried renaming it to something other than username, thinking that maybe there was already field named username in AbstractUser, but that didn't solve the problem. -
Elasticsearch port 9300 django
I'm facing a strange issue, using Django Haystack and ElasticSearch so I can't rebuild_index. ElasticSearch is properly running on the machine : $ curl -X GET 'http://localhost:9200' { "status" : 200, "name" : "Ziggy Pig", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.2", "build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec", "build_timestamp" : "2015-09-14T09:49:53Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } But this is the log of ElasticSearch : [2017-11-29 18:25:22,723][INFO ][node] [Ziggy Pig] initialized [2017-11-29 18:25:22,724][INFO ][node] [Ziggy Pig] starting ... [2017-11-29 18:25:22,913][INFO ][transport] [Ziggy Pig] bound_address {inet[/127.0.0.1:9300]}, publish_address {inet[/10.142.0.2:9300]} [2017-11-29 18:25:22,937][INFO ][discovery] [Ziggy Pig] . elasticsearch/HWEvbIkAR3mFwcGeHIa7Cg [2017-11-29 18:25:26,710][INFO ][cluster.service] [Ziggy Pig] new_master [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg][stagelighted] [inet[/10.142.0.2:9300]], reason: zen-disco-join(elected_as_master) [2017-11-29 18:25:26,734][INFO ][http] [Ziggy Pig] bound_address {inet[/127.0.0.1:9200]}, publish_address {inet[/10.142.0.2:9200]} [2017-11-29 18:25:26,734][INFO ][node] [Ziggy Pig] started [2017-11-29 18:25:26,762][INFO ][gateway] [Ziggy Pig] recovered [1] indices into cluster_state [2017-11-29 18:26:22,946][WARN ][cluster.service] [Ziggy Pig] failed to reconnect to node [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg] [stagelighted][inet[/10.142.0.2:9300]] org.elasticsearch.transport.ConnectTransportException: [Ziggy Pig][inet[/10.142.0.2:9300]] connect_timeout[30s] at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:825) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:758) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:731) at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:216) at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:584) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.net.ConnectException: Connection refused: /10.142.0.2:9300 at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79) at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42) at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) I installed JAVA and Elastisearch … -
'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) in djago-admin
First of all I want to mention that I saw nearly all the similar question and non of them was helpful. so I decided to make this new question on SO. I use python 2.7 and django 1.11.7 and nginx as server. models.py: from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Post(models.Model): postTitle = models.CharField('Title', max_length=60) postText = models.TextField('Text') postDate = models.DateTimeField('Date',default=None) def __str__(self): return self.postTitle I use Postgresql as database and this is how I created the database : postgres=# CREATE DATABASE djangodbjavad WITH ENCODING 'UTF8' LC_COLLATE='en_US.UTF-8' TEMPLATE=template0; I tried to write some Persian text in postTitle field at django admin and it fails to handle it. but interesting enough that it can handle Persian text correctly in postText field. Full log available at here : http://dpaste.com/2Z034BV -
Foreign key in serializer is not json serializable
I'm trying to create a serializer that points to two different objects from Account and Currency, but when its called i keep getting following error: TypeError: Object of type 'Account' is not JSON serializable. what am i doing wrong? class InvoiceSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('user', 'currency', 'task', 'deposit_amount', 'receive_amount') read_only_fields = ('created_at', 'updated_at') def create(self, validated_data): user = Account.objects.only('id').get(id=validated_data['user']) currency = Currency.objects.only('id').get(id=validated_data['currency']) return Invoice.objects.create( user=user, currency=currency, task=validated_data['task'], deposit_amount=validated_data['deposit_amount'], receive_amount=validated_data['receive_amount'] ) -
type of map - location field django
This is my model, class Site(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=8) is_active = models.BooleanField(default=True) location = gis_models.PointField(geography=True, blank=True, null=True) gis = gis_models.GeoManager() objects = models.Manager() def __str__(self): return self.name + ', ' + self.city.name This is how I view its location in map, This map is no good for me. If I zoom in, it remains the same and does not show any address. I want a proper map like google shows with proper labeling. How can I achieve that? -
AttributeError: 'NoneType' object has no attribute 'visible_fields'
I'm trying to add a class to <input> on my form. Following the instructions of the first answer to this question, I added some code into my form's __init__ method. However I got the error displayed in the title. forms.py class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) def __init__(self, *args, **kwargs): form = super(SignupForm, self).__init__(*args, **kwargs) for visible in form.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = User fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name',) -
Migrating from SQLite3 to Postgres issues with non-null constraints
I'm trying to move from SQLite to Postgres in my Django application, but now I'm getting errors like this when I try to make a POST request: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 2017-11-29 18:48:23.976207+00, 0, 2017-11-29 18:48:23.976247+00, a2bc5886-baf1-4e91-ad08-03a030bb7be7, Hello, 7, 7, 44). The model is very simple in this case: from uuid import uuid4 from django.db import models from scouting.core import TimestampModerated from profiles.models import Profile from photos.models import Photo class Comment(TimestampModerated): uuid = models.UUIDField(db_index=True, default=uuid4, editable=False) user = models.ForeignKey('auth.User', related_name='user_comments', on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profile_comments', on_delete=models.CASCADE, null=True) photo = models.ForeignKey(Photo, related_name='comments', on_delete=models.CASCADE, null=True) text = models.CharField(max_length=255) class Meta: verbose_name_plural = "comments" def __str__(self): return self.text One thought I have is that it seemed with SQLite I didn't have to explicitly declare the id field. Maybe that is not the case with postgres? -
django ModelForm - this field is required error always shows
I have this in my views but why does it always show the error that the field is required form = ProgressReportForm(request.POST or None): return render(request, template, {'form': form}) Here is my form class ProgressReportForm(ModelForm): class Meta: model = ProgressReport fields = ['title', 'report_progress'] widgets = { 'report_progress': forms.Textarea(attrs={'class': 'form-control'}) } -
Crispy-Forms Include Tag Causing Many Duplicate Templates
I have a Django site that uses the below template to render a crispy-forms model formset. Using django-debug-toolbar, I gathered that the include tags are rendering the bootstrap4 templates many, many times. I think this is what is killing my performance (i.e. 3-4 minutes to load an inline formset with 100 forms in it) How should I replace the include tags to avoid the duplicate rendering? Should I use extend somehow? I can replace the include tags with the actual html from the bootstrap4 crispy-forms templates, but those templates have nested templates as well. That creates an exercising of building a master crispy-forms template that includes everything...which seems like the wrong way to go about this. In addition, I tried replace the bootstrap4/field.html include tag with the actual html, and field.html was still duplicated, and the data lost it's table structure because of the loss of with tag='td'. {% load crispy_forms_tags %} {% load crispy_forms_utils %} {% load crispy_forms_field %} {% specialspaceless %} {% if formset_tag %} <form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}> {% endif %} {% if formset_method|lower == 'post' and not disable_csrf %} {% csrf_token %} {% endif %} <div> … -
Django does not add an extra attribute to the custom ModelForm widget
models.py class MyModel(models.Model): pub_date = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255, blank=False, null=False) text = models.TextField(blank=True, null=True) forms.py class MyModelForm(ModelForm): tos = BooleanField() class Meta: model = models.MyModel fields = ['title', 'text', 'tos'] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}), 'text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Text'}), 'tos': CheckboxInput(attrs={'data-validation-error-msg': 'You have to agree to our terms and conditions'}), } Results: >>> print(forms.MyModelForm()) <tr><th><label for="id_title">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Title" maxlength="255" required id="id_title" /></td></tr> <tr><th><label for="id_text">Text:</label></th><td><textarea name="text" cols="40" rows="10" class="form-control" placeholder="Text" id="id_text"></textarea></td></tr> <tr><th><label for="id_tos">Tos:</label></th><td><input type="checkbox" name="tos" required id="id_tos" /></td></tr> You can see that the in the TOS field data-validation-error-msg attribute is missing. Any ideas?