Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Shared global variables among apps
Suppose I have two apps: data and visual. App data executes a database retrieval upon starting up. This thread here and this doc advises on how and where to place code that executes once on starting up. So, in app data: #apps.py from django.apps import AppConfig global_df #want to declare a global variable to be shared across all apps here. class DataConfig(AppConfig): # ... def ready(self): from .models import MyModel ... df = retrieve_db() #retrieve model instances from database ... return df In the code above, I am looking to execute ready() once on starting up and return df to a shared global variable (in this case, global_df). App visual should be able to access (through import, maybe) this global_df. But, any further modification of this global_df should be done only in app data. This thread here advised to place any global variable in the app's __init__.py file. But it mentioned that this only works for environmental variable. Two questions: 1 - How and where do I declare such a global variable? 2 - On starting up, how to pass the output of a function that executes only once to this global variable? -
Where to set the author as request.user
Problem In my model I have the field author which I want to enter as a ForeignKey with the UserModel with the user who has authenticated himself via JWT Token. My API and JWT authentication works fine, but I don't know where to set the author = request.user in the backend. My Code: apis.py class AlarmstichworteCreateApi(ApiErrorsMixin, APIView): permission_classes = [IsAuthenticated] class InputSerializer(serializers.ModelSerializer): author = UserListAPI.OutputSerializer(source='UserListAPI_set', many=True) created = serializers.DateTimeField() updated = serializers.DateTimeField() name = serializers.CharField(max_length=100) class Meta: model = AlarmstichworteConfig fields = ( '__all__' ) def post(self, request, *args, **kwargs): serializer = self.InputSerializer(data=request.data) #! serializer = self.InputSerializer(data=request.data, author=request.user) # Try 1 serializer.is_valid(raise_exception=True) create_alarmstichwort(**serializer.validated_data) #! create_alarmstichwort(**serializer.validated_data, author=request.user) # Try 1 return Response(status=status.HTTP_201_CREATED) services.py def create_alarmstichwort( *, author: ForeignKey, created: datetime, updated: datetime, name: str, ) -> AlarmstichworteConfig: if AlarmstichworteConfig.objects.filter(id=id).exists(): raise ValidationError('Alarmstichwort existiert bereits') alarmstichwort = AlarmstichworteConfig.objects.create( author=author, created=created, updated=updated, name=name, ) alarmstichwort.full_clean() alarmstichwort.save() return alarmstichwort I would be happy if anyone could help me. Many thanks in advance! -
Webpack/babel not compiling ReactDOM.render
Objective: I am trying to get webpack/babel to compile JSX so that I can make a website with react front end, and django rest api backend. I have gone through many tutorials and Stackoverflows, but never gotten JSX to compile to make combo work. I debugged for a LONG time, and found that the crux of the JSX problem seems to be centered around reactDOM.render. If I use react components without reactDOM.render, it all works, with is breaks down with errors such as "App.js:12 Uncaught ReferenceError: ReactDOM is not defined" or the one I get most often, "Module parse failed: Unexpected token (13:12) You may need an appropriate loader to handle this file type" here is the code-- my .babelrc file: { "presets": [ "@babel/preset-env", "@babel/preset-react" ] } webpack.config.js: module.exports = { module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; packages.json: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --entry ./src/index.js --output-path ./static/frontend", "build": "webpack --mode production --entry ./src/index.js --output-path ./static/frontend" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.14.6", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": … -
I just want to pull only value datas from a sql ResulSet
Here is my output value when I print test variable in my code: ResultSet({'('device_frmpayload_data_Sayac', None)': [{'time': '2021-07-03T15:50:00.359986Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}, {'time': '2021-07-03T15:48:56.204781Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}]}) I do not know the type of this variable and can not check because it gives an error: typeerror 'builtin_function_or_method' object is not subscriptable .it has 0 attributes btw when I checked it. Here is my code: def amChartsDbData(request): client = InfluxDBClient(host=lora_host, port=####) client.switch_database('loradb') sayac = client.query("SELECT * From device_frmpayload_data_Sayac WHERE time > now() - 5d ORDER BY time DESC LIMIT 2") sayactimeLuna = client.query("SELECT elapsed(value,1s) FROM device_frmpayload_data_Sayac WHERE dev_eui='######201a0000009'") sycLuna = list(sayac.get_points(tags={'dev_eui': '#######1a0000009'}))[-1:] sycBaylan = list(sayac.get_points(tags={'dev_eui': '######1a0000010'}))[-1:] lunaTable = list(sayac.get_points(tags={'dev_eui': '#####a0000009'}))[-3:] baylanTable = list(sayac.get_points(tags={'dev_eui': '########a0000010'}))[-3:] timeLuna = list(sayactimeLuna.get_points())[-1:] test = sayac Finally, I also want the time value in proper format as: YYYY-MM-DD-HH-MIN-SEC. Thanks a lot. -
Java library for building Django Q and F queries
A Java/Spring project I work on builds a lot of Q and F queries manually to make requests to an external API. Is there a Java library out there for building Django REST queries, or maybe something just considered a best practice for this use case? -
Django searching a function for a string within it
I am attempting to setup a database driven search for the User Guide of a system. Overall I am writing a Django command that loops over the URLs in the User Guide, from that I need to also gather the Template that is being rendered by Django at the URL so I can render it to HTML and naturally search it, but gathering the Template is seeming to be quite difficult. Here is my current code: import importlib from django.core.management.base import BaseCommand def get_user_guide_urls_as_dict(): """ Used to return the list of url names and urls found in the application. { url_name: url } :return: """ from django.apps import apps list_of_all_urls = list() class UserGuideConfig: def __init__(self): pass for name, app in apps.app_configs.items(): # only gather user guide stuff if 'user_guide' in app.name: mod_to_import = f'apps.{name}.urls' urls = getattr(importlib.import_module(mod_to_import), "urlpatterns") list_of_all_urls.extend(urls) for url in list_of_all_urls: # the function/ callback should have the template name I need, # how do I get it rendered as a string print(url.callback.__wrapped__) class Command(BaseCommand): """ Used as a method to generate user guide searchable items in db """ help = "" def handle(self, *args, **options): # loop urls url_dict = get_user_guide_urls_as_dict() The best way I can … -
Installing Django dev environment - Errno 13
I am trying to set up my dev environment. I am supposed to install pipenv but am getting an error: [pipenv.exceptions.InstallError]: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: [pipenv.exceptions.InstallError]: Check the permissions. ERROR: Couldn't install package: psycopg2 I am on a mac and I used pipx to install pipenv, the other options didn't work for me. I have tried the following: pipenv install psycopg2 pipenv run pip install psycopg2 pipenv install psycopg2-binary -
How do I get rid of this !!!!! (Django) [closed]
enter image description here please someone show me how to get rid of that 'This field is required' li tag (see image) Thanks note: I've tried blank=True, null=True -
Using Postgres roles and privilege in Django project
I am using Django Rest Framework with postgres. From the beginning of the project we used django-guardian to provide opportunity of using object permissions. But django-guardian can slow down all of the app when we have large amount of users, groups and permissions to them. What about of using postgres roles in django project? What about of storing each user as postgres role? What difficulties can we face? We will have a large number of users and roles, can it give problems to us if we will use postgres? -
wagtail admin list_editable fields
Is there an analogue of list_editable (django) in wagtail admin indexview (listview)? I have an integer field that I want to be able to edit from the list of records page (without going to the specific record edit page). -
Unable to load environment variable (.env) in Django App
I am trying to launch a Django project and am unable to do so because it seems my local environment is disconnected from my .env file in the root directory. I've never had this problem before and assume there is an easy fix but I can't seem to figure it out. When I run basic commands like runserver I get the following error: RATE_LIMIT_DURATION = int(os.environ.get("RATE_LIMIT_DURATION")) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' In my .env file, I have defined the variable as: RATE_LIMIT_DURATION = 10 I have already confirmed that my database is setup and I am pretty sure my settings are in good shape otherwise. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASSWORD"), "HOST": "localhost", "PORT": 8000, } } -
PayPal: Is it possible to pay for an order just by the order id/details
I am trying to create the order on the backend and then pass the order id to the smart button's javascript so that i can execute the order without allowing the user to edit the order. i have successfully done this before with a subscription by creating a plan and then passing in the plan id to execute the payment but i don't know what button action to use to do this with orders. How should i do this? Here is how i am doing this on the backend: headers = { "Content-Type": "application/json", "Authorization": bearer_token, } data = { "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "GBP", "value": str(order.credits) } } ] } response = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=headers, json=data).json() order_id = response["id"] context = { 'order_id': order_id, } and here is what i have tried on the frontend: paypal.Buttons({ style: { size: 'responsive', }, createOrder: function(data, actions) { return actions.order.create({ "id": "{{ order_id }}" }); }, onApprove: function(data, actions) { } }).render('#paypal-button-container'); / -
django get coroutine object data using sync_to_async way
def compute_topics_to_eventabis() -> Dict: "Loop through all contracts in our DB and compute topics to ABI mapping" topics_to_event_abis = {} contracts = sync_to_async(EthereumContract.objects.all)() print(contracts) for contract in contracts: # we could use contract.web3_objects().events as well for entity in contract.abi: if entity["type"] == u"event": topics = construct_event_topic_set(entity, get_infura_server().codec) for topic in topics: topics_to_event_abis[topic] = entity return topics_to_event_abis Task exception was never retrieved future: <Task finished name='Task-2' coro=<get_new_heads() done, defined at watcher.py:145> exception=TypeError("'coroutine' object is not iterable")> Traceback (most recent call last): File "watcher.py", line 173, in get_new_heads process_block(formatted_result['blockNumber'], File "watcher.py", line 142, in process_block return replay_block(block_id, get_infura_server()) File "watcher.py", line 132, in replay_block return process_each_log_and_spawn_event(logs) File "watcher.py", line 117, in process_each_log_and_spawn_event for event in process_each_log_and_yield(logs): File "watcher.py", line 105, in process_each_log_and_yield TOPICS_TO_EVENT_ABIS = compute_topics_to_eventabis() File "watcher.py", line 93, in compute_topics_to_eventabis for contract in contracts: TypeError: 'coroutine' object is not iterable /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'SyncToAsync.__call__' was never awaited self._context.run(self._callback, *self._args) RuntimeWarning: Enable tracemalloc to get the object allocation traceback Here when i am using sync_to_async it is throwing above error How to read and loop over contracts ? Am i doing it correctly ? Please take a look. How can i solve it . -
405 error method is not allowed python django
I am working on shopping cart application in Django(Book Example). When I tried to test it via browser it is responding 405 method not allowed error. As I understand when I am sending request via form(method='post') it is sending http GET request.As I undertand, It is a reason of error(405). Here is HTML form: <form action="{% url 'cart:cart_add' product.id %}" method="POST"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Add to cart"> </form> forms.py file: from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1,21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py file: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], override_quantity=cd['override']) return redirect('cart:cart_detail') @require_POST def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') @require_POST def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) -
Form validation is not working in Ajax form submitting
I am building a small Blog App with comment Functionality so, I am trying to prevent bad words in comments. ( If anyone tries to add selected bad words then the error will raise ). BUT when i add text validation in model field and try to enter bad word then it is saving without showing any errors of validation. When i try to save form without ajax then the error is validation successfully showing. BUT error is not showing in ajax. models.py class Comment(models.Model): description = models.CharField(max_length=20000, null=True, blank=True,validators=[validate_is_profane]) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) views.py def blog_detail(request, pk, slug): data = get_object_or_404(Post, pk=pk) comments = Comment.objects.filter( post=data) context = {'data':data,'comments':comments} return render(request, 'mains/blog_post_detail.html', context) if request.GET.get('action') == 'addComment': if request.GET.get('description') == '' or request.GET.get( 'description') == None: return None else: comment = Comment(description=request.GET.get('description'), post=data, user=request.user) comment.save() return JsonResponse({'comment': model_to_dict(comment)}) blog_post_detail.html {% for comment in comments %} {{comment.comment_date}} <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#commentReadMore{{comment.id}}').click(function (event) { event.preventDefault() $('#commentDescription{{comment.id}}').html( `{{comment.description}}`) }) }) }) </script> {% endfor %} I have tried many times but still not showing the validation error. Any help would be much Appreciated. Thank You in Advance. -
django use function from other views
I want to use part of the data from an existing function in another view.py for example: result/view.py def result(request,slug) datas = modle.objects.get(slug=slug) somecodes... return render(request,"result.html",data1,data2,data3,data4) And I want part of the data (ex. data1,data2) to use in another view files, how do i do that ? -
text under symbols in the sidebar menu
Very new to CSS and HTML, but right now working on Django one-page project. Under icons, I would like to place some text, but there is an issue with the borders. sample img Right now text wrapping works not very well, I would like to center text under the icon and have at least 3 or 4 straight strings. Maybe there are issues that this text and icons should be in the container, IDK, will be very happy to hear any solution and suggestions for my portfolio project. Thank you! Here is my HTML: <!DOCTYPE html> {% load static %} <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="{% static 'style.css' %}"> <script src="https://kit.fontawesome.com/5476287230.js" crossorigin="anonymous"></script> </head> <body> <div class="social-menu"> <ul> <li><a href="https://www.instagram.com/kseniia_ifbb_latvia"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.tiktok.com/@kseniiasherr"><i class="fab fa-tiktok"></i></a></li> <li><a href="https://www.facebook.com/profile.php?id=100009190064504"><i class="fab fa-facebook"></i></a></li> </ul> </div> <div class="title"> <h1>ЧТО ВЫ ПОЛУЧАЕТЕ?</h1> </div> <div id="background"></div> <div class="icons"> <li><i class="fas fa-utensils"></i></li> <li><i class="fas fa-dumbbell"></i></li> <li><i class="fas fa-clock"></i></li> <li><i class="fas fa-heartbeat"></i></li> </div> <div class="icons-text"> <li><h1>План питания с учетом Ваших вкусовых потребностей</h1></li> <li><h1>Тренировки для любого уровня подготовки</h1></li> <li><h1>Максимально быстрые результаты</h1></li> <li><h1>Тело, о котором Вы могли только мечтать</h1></li> </div> </body> </html> And CSS: body{ background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; } … -
django mptt no such column: appname_modelname.lft
models.py -> class Category(MPTTModel): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) parent = TreeForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Card(BaseModel): categories = TreeManyToManyField(Category, related_name='category_cards', blank=True, default=None) admin.py -> @admin.register(Category) class CategoryAdmin2(DraggableMPTTAdmin, BaseAdmin): list_display = ('tree_actions', 'indented_title',) list_display_links = ('indented_title',) I ran both "python manage.py migrations" and "python manage.py migrate" commands. No error occurs. Migration File -> migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField(auto_now_add=True)), ('modified_date', models.DateTimeField(auto_now=True)), ('title', models.CharField(max_length=200)), ('description', models.TextField(blank=True, null=True)), ('lft', models.PositiveIntegerField(editable=False)), ('rght', models.PositiveIntegerField(editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='w2mmcards.category')), ], options={ 'verbose_name': 'category', 'verbose_name_plural': 'categories', }, ), migrations.AddField( model_name='card', name='categories', field=mptt.fields.TreeManyToManyField(blank=True, default=None, related_name='category_cards', to='w2mmcards.Category'), ), In admin interface, I get this error: OperationalError at /admin/myapp/category/ no such column: myapp_category.lft How to solve it? -
cannot create 'builtin_function_or_method' instances
I want to see the type of a list element but I am not able to see this, it gives this error: "cannot create 'builtin_function_or_method' instances". Normally, it seems to keep dict but I cannot use the dict methods on this variable (like .items). So, I need to learn the type of it. This is the variable : [{'time': '2021-07-03T15:44:40.124358Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}]. I want to use the value parameter only. How can I take the value? Thanks a lot. this is the error and this is the code -
Django - how to get user from built in LoginView
I simply want to grab the user after login but for some reason can't think of the best way to do that while using class based LoginView. I just want to flash a message with the specific user who logged in. I am not sure how to grab the request.user from the built in login view. My very simple view is as follows: class MyLoginView(SuccessMessageMixin, LoginView): template_name = 'registration/login.html' success_message = 'Welcome' -
AttributeError : Can't get attribute 'myfunctionname' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> : Django Project
I am using a custom module in my Django app, facing issues while deploying in Heroku. This is the content of my custom module- defs.py: import numpy as np def myfunctionname(x): return np.log(x + 1) this file is being called in manage.py as from defspack.defs import myfunctionname procfile : web gunicorn appname.wsgi --log-file - Traceback: 2021-07-06T11:28:32.195664+00:00 app[web.1]: obj = unpickler.load() 2021-07-06T11:28:32.195665+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1212, in load 2021-07-06T11:28:32.195665+00:00 app[web.1]: dispatch[key[0]](self) 2021-07-06T11:28:32.195666+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1537, in load_stack_global 2021-07-06T11:28:32.195667+00:00 app[web.1]: self.append(self.find_class(module, name)) 2021-07-06T11:28:32.195667+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1581, in find_class 2021-07-06T11:28:32.195668+00:00 app[web.1]: return _getattribute(sys.modules[module], name)[0] 2021-07-06T11:28:32.195668+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 331, in _getattribute 2021-07-06T11:28:32.195668+00:00 app[web.1]: raise AttributeError("Can't get attribute {!r} on {!r}"2021-07-06T11:28:32.195669+00:00 app[web.1]: AttributeError: Can't get attribute 'myfunctionname' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> can anyone help me on this -
Django custom __in lookup
I get custom lookup for filtering foreign key field from this answer. from django.db.models import Lookup class EfficientInLookup(Lookup): lookup_name = "ineff" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + list(rhs_params) return "%s IN (SELECT unnest(ARRAY(%s)))" % (lhs, rhs), params But I have an error in the string lhs, lhs_params = self.process_lhs(compiler, connection) when I am trying use it. Using: queryset = queryset.filter(child__id__ineff=[1,2,3] Error: int() argument must be a string, a bytes-like object or a number, not 'list' How can I write a custom lookup for foreign key fields? -
How to fetch swipe up count from Instagram story insights graph API?
I need to fetch swipe up count which show in the insights of Instagram.As Facebook is not providing swipe up count through their graph API so how can I get that data. Scraping won't work as I already did and I want to fetch those data in python or javascript Thanks in advance for help -
Someone please tell me what is wrong with my code?
I am coding for a complaint management system and so far for creating new complaints the form is kind of made but the complaints that are being made are not getting saved in my admin panel. I have tried everything and I don't understand where i'm going wrong models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: class ComplaintForm(ModelForm): class Meta: model = Complaints highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') views.py: def NewComplaint(request): user = request.user if request.method == 'POST': form = ComplaintForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = user form.save() submitbutton= request.POST.get('Submit') if submitbutton: messages.success(request, 'Submitted!') context = {'form': form} return render(request, 'new.html', context) else: form = ComplaintForm() context = {'form': form} return render(request,'new.html',context) template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr ">{{form.description}}</div> … -
How to make a django custom widget with 2 fields/controls (amount and credit/Debit)
I have one numeric field in my model If the field is negative its debit and if its positive its Credit Now the user has the always enter a positive number and then select Credit or Debit When the data is saved to the field accordingly the sign is assigned The user is not supposed to enter a negative amount How to create a custom widget to achieve this so that I can use it in ModelForm s